最朴素的方法:
#include<cstdio> int main(){ int a,maxn=-1,minn=32769; scanf("%d",&a); if (a%2==0) maxn=a/2; if (a%4==0) minn=a/4; for (int t=1;t<=a/4;t++) for(int j=1;j<=a/2;j++) if(4*t+2*j==a){ if (t+j<minn) minn=t+j; if (t+j>maxn) maxn=t+j; } if (maxn==-1&&minn==32769) printf("0 0\n"); else printf("%d %d\n",minn,maxn); return 0; }
时间:32768/4*32768/2=134217728~1*108
如果测试数据过大未必能通过
简单优化:
#include<cstdio> int main(){ int a,maxn=-1,minn=32769; scanf("%d",&a); if (a%2==0) maxn=a/2; if (a%4==0) minn=a/4; if (a%2>0){ printf("0 0\n"); return 0; } if (maxn==-1||minn==32769) { for (int t=a/4;t>=0;t--) for(int j=1;j<=a/2;j++) if(4*t+2*j==a){ if (t+j<minn) minn=t+j; if (t+j>maxn) maxn=t+j; } } if (maxn==-1&&minn==32769) printf("0 0\n"); else printf("%d %d\n",minn,maxn); return 0; }
继续优化:保留一重循环
如果有解则a定为偶数,则最大值定为a/2。如果a%4==0则最小值为 minn=a/4;
//如果有解则a定为偶数,则最大值定为a/2。如果a%4==0则最小值为 minn=a/4; #include<cstdio> int main(){ int a,maxn=-1,minn=32769; scanf("%d",&a); if (a%2==0) maxn=a/2; else {//如果a非偶肯定无解 printf("0 0\n"); return 0; } if (a%4==0) minn=a/4; if (minn==32769) for (int t=1;t<=a/4;t++){ int j=(a-4*t)/2; if (t+j<minn) minn=t+j; } // if (maxn==-1&&minn==32769) printf("0 0\n"); printf("%d %d\n",minn,maxn); return 0; }
三种方法的时间复杂度:
时间: 2024-10-27 18:23:08