POJ 1207 求最大数链长度 暴力枚举数学题

来源:互联网 发布:c语言程序停止运行 编辑:程序博客网 时间:2024/05/19 10:33

这个题目直接用的暴力枚举,但是还是WA了几次

原因是这句话You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j. 

注意i可能大于j,此时需要交换顺序,但是输出的时候还会是原始顺序

比如 输入1 10 输出 1 10 20 ;输入10 1 输出 10 1 20

因此交换i和j需要用标志位记录一下

Source Code

Problem: 1207 User: yangliuACMerMemory: 244K Time: 16MSLanguage: C++ Result: Accepted
//暴力枚举//21:22#include <iostream>using namespace std;int main(){int i,j,k,count,max,newk,temp;bool flag;while(cin>>i>>j){max = 1;flag = true;if(i > j){temp = i;i = j;j = temp;flag = false;}for(k = i; k <= j; k++){count = 1;newk = k;//注意计算循环节的时候k的值会发生变化while(newk != 1){count++;if(newk % 2) newk = 3 * newk + 1;else newk/=2;}if(count > max) max = count;}if(flag)cout<<i<<" "<<j<<" "<<max<<endl;else cout<<j<<" "<<i<<" "<<max<<endl;}return 0;}//21:42


原创粉丝点击