sicily 6272. n钱m鸡问题
Description
一只公鸡值五文钱;
一只母鸡值三文钱;三只小鸡值一文钱
。请问用n文钱买m只鸡的方案有多少种?
Input
输入有多个case,
每个case如下
n m
其中n,m <= 100,
输入以EOF结束。
Output
对于每个case输出一行,
这一行只有一个整数,表示解的个数
后记:除了小鸡数=总数-公鸡数-母鸡数以外,还可以用只有小鸡数能被3整除时才开始计算花费,而不是在枚举时检验花费的同时一起检验小鸡数是否能被3整除的方法进一步减少计算量。
一开始用做实验的算法直接提交,WA无数次,屡改屡败。
被报错n次的其中一种,用小鸡数=总数-公鸡数-母鸡数控制枚举次数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 int main() 3 { 4 int cock, hen, chick, n, m, cost, counter=0, num; 5 6 while( scanf("%d%d", &n, &m ) != EOF ) 7 { 8 for( cock = 0; cock <= n/5; cock++ ) 9 { 10 for( hen = 0; hen <= n/3; hen++ ) 11 { 12 chick = m - cock - hen; 13 cost = cock * 5 + hen * 3 + (chick / 3); 14 num = hen + chick + cock; 15 if ( (cost == n) && (num == m) && (chick % 3 ==0 ) ) 16 counter++; 17 } 18 } 19 printf("%d\n",counter); 20 counter = 0; 21 } 22 return 0; 23 }
实在无奈,只好用比较笨的办法,三个循环,不控制枚举次数,居然成功AC了,但是run time达到了0.02sec
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 int main() 3 { 4 int cock, hen, chick, n, m, cost, counter=0; 5 6 while( scanf("%d%d", &n, &m ) != EOF ) 7 { 8 for( cock = 0; cock <= n/5; cock++ ) 9 { 10 for( hen = 0; hen <= n/3; hen++ ) 11 { 12 for( chick = 0; chick <= 3*n; chick++ ) 13 { 14 cost = cock * 5 + hen * 3 + (chick / 3); 15 if ( (cost == n) && (hen + chick + cock == m) && (chick % 3 ==0 ) ) 16 counter++; 17 } 18 19 } 20 } 21 printf("%d\n",counter); 22 counter = 0; 23 } 24 return 0; 25 }
在自己看来这两种算法本质都差不多,实在想不通为什么会出现不同的情况。于是存下来自己设计测试对比,在用100 20测试的时候发现了不同。
AC的程序在用100 20测试时解出的是1,而WA的那个是5.
修改代码查看具体每种解法
问题关键出现了,第二种算法把小鸡数为负的状况也算进去了。在控制条件里再加一个小鸡数不小于0,成功AC,Run Time 0sec
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 int main() 3 { 4 int cock, hen, chick, n, m, cost, counter=0, num; 5 6 while( scanf("%d%d", &n, &m ) != EOF ) 7 { 8 for( cock = 0; cock <= n/5; cock++ ) 9 { 10 for( hen = 0; hen <= n/3; hen++ ) 11 { 12 chick = m - cock - hen; 13 cost = cock * 5 + hen * 3 + (chick / 3); 14 num = hen + chick + cock; 15 if ( (cost == n) && (num == m) && (chick % 3 ==0 ) && (chick >= 0) ) 16 { 17 counter++; 18 } 19 } 20 } 21 printf("%d\n",counter); 22 counter = 0; 23 } 24 return 0; 25 }
还有一种更简单的办法,声明变量时使用unsigned,就直接避免了负数的出现,也AC了,Run Time 0sec
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)