HDOJ 1005

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 63888    Accepted Submission(s): 14701
Problem Description
ios

A number sequence is defined as follows:數組

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
 Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
 Output
For each test case, print the value of f(n) on a single line.
 
Sample Input
1 1 3 1 2 10 0 0 0
 Sample Output
2 5
我本身作的時候 忽略了n的大小,因此遞歸的時候棧溢出了.....
個人代碼:
 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 }

網上大神的代碼:this

#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; }
相關文章
相關標籤/搜索