最朴素的方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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
如果测试数据过大未必能通过
简单优化:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//如果有解则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; }
三种方法的时间复杂度:
思考:
可以不用循环来实现吗?
最小值肯定是腿先分配给兔子,剩下不够的才能分配给鸡。(其实最多剩2只腿,也就是说最多有1只鸡)
那么兔子的数量为a/4,鸡的数量为(a%4)/2,则最小值为:a/4+(a%4)/2。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> int main(){ int a,maxn=-1,minn=32769; scanf("%d",&a); if (a%2>0){ printf("0 0\n"); return 0; } maxn=a/2; minn=a/4+(a%4)/2; printf("%d %d\n",minn,maxn); return 0; }