标签:++ 变量 back int tip for false cas cto
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 63888 Accepted Submission(s): 14701
Problem Description
A number sequence is defined as follows:
1 #include <iostream> 2 using namespace std; 3 static int count; 4 int f(int a,int b,int n); 5 int mod(int n); 6 int main() 7 { 8 int a,b,n; 9 while(cin>>a>>b>>n) 10 { 11 if(a>=1 && a<=1000 && b>=1 && b<=1000) 12 { 13 count=0; 14 cout<<f(a,b,n)<<endl; 15 } 16 else 17 break; 18 } 19 return 0; 20 } 21 int f(int a,int b,int n) 22 { 23 if( n == 1 ) 24 return 1; 25 else if( n == 2) 26 return 1; 27 else 28 return mod(a*f(a,b,n-1)+b*f(a,b,n-2)); 29 } 30 int mod(int n) 31 { 32 while(n>7) 33 { 34 n=n-7; 35 } 36 return n; 37 }
网上大神的代码:
#include <iostream> #include <vector> using namespace std; vector<int> ivec; //布尔数组元素flag[i][j]如果为true,则说明前面已经出现了i 和 j两者的组合 bool flag[7][7]; void init(void) { int i,j; for(i = 0;i < 7;++i) for(j = 0;j< 7;++j) flag[i][j] = false; } int main() { int a,b,n; while(cin>>a>>b>>n) { if(a == 0&&b == 0&&n == 0) break; ivec.clear(); init(); ivec.push_back(1); ivec.push_back(1); flag[1][1] = true; int count = 1,f; while(1) { f = (a*ivec.at(count)%7 + b*ivec.at(count - 1)%7)%7; ivec.push_back(f); ++count; //如果flag变量为true,则说明前面已经出现了这两者的组合,出现重复,无需下一步计算,直接break退出即可 if(flag[ivec.at(count)][ivec.at(count - 1)] == true) break; else flag[ivec.at(count)][ivec.at(count - 1)] = true; } //count中存放的是ivec中出现循环前的元素总个数,注意ivec中的下标是从0开始计数的 count = count - 1; if(n < count) cout<<ivec.at(n-1)<<endl; else { int j; //for循环的目的是找出从那个地方开始重复,此处应该是从j处开始循环,注意j是从0下标开始计数的 for(j = 0;;++j) if(ivec.at(count) == ivec.at(j) && ivec.at(count + 1) == ivec.at(j+1)) break; n = (n - j)%(count - j); if(n == 0) n = count - j; n += j; cout<<ivec.at(n-1)<<endl; } } return 0; }
标签:++ 变量 back int tip for false cas cto
原文地址:http://www.cnblogs.com/luozhijun/p/6880471.html