免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: loveguohuasai
打印 上一主题 下一主题

[算法] 母牛数量算法 [复制链接]

论坛徽章:
0
1 [报告]
发表于 2003-08-11 22:55 |显示全部楼层

母牛数量算法


  1. #include <iostream>;
  2. #include <vector>;
  3. #include <cstdlib>;
  4. using namespace std;

  5. int
  6. main(int argc, char** argv)
  7. {
  8.         if(argc != 2)
  9.         {
  10.                 exit(1);
  11.         }
  12.         int year = atoi(argv[1]);
  13.         vector<long long>; count(year, 1);
  14.         for ( int i = 2; i < year; i ++)
  15.                 count[i + 1] = count[i] + count[i - 2];
  16.         cout << "In the " << year <<"th year, there are(is) "
  17.              << count[year - 1] << " cows\n";
  18. }
复制代码


关键就在那个for循环。
就是f(n) = f(n - 1) + f(n - 3) 的实现。[/code]

论坛徽章:
0
2 [报告]
发表于 2003-08-11 23:05 |显示全部楼层

母牛数量算法


  1. #include <deque>;
  2. #include <cstdlib>;
  3. #include <iostream>;
  4. using namespace std;

  5. int
  6. main(int argc, char** argv)
  7. {
  8.         if(argc != 2)
  9.         {
  10.                 cout << "just accept 1 parameter\n";
  11.                 exit(1);
  12.         }
  13.         int year = atoi(argv[1]);
  14.         deque<long long>; count(4, 1);
  15.         count.pop_back();
  16.         for ( int i = 2; i < year; i ++)
  17.         {
  18.                 count.push_back(count[0] + count[2]);
  19.                 count.pop_front();
  20.         }
  21.         cout << "In the " << year <<"th year, there are(is) "
  22.              << count[1] << " cows\n";
  23. }
复制代码

同样是n级别的时间复杂度,但是空间复杂度变为1,deque的空间只有4.
不知道这个在时间上跟上一个有什么区别,不过估计也很难反映出来测试到117时就溢出了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP