HDU 1005 Number Sequence

HDU-1005

题解:每次的数都会对7进行mod操作,mod之后数的范围一定在[0,6]之间,如果每次都循环到n的话明显会TLE,那么就说明这个结果会出现一个周期,我们只要找到这个周期,然后根据周期进行mod,然后找到结果就好了。

PS:讨论区的最简代码的mod48操作我也不是很理解,但是有人是说错的,hdu数据水而已,2333。(反正我觉得找周期靠谱)

代码:

 1 #include<iostream>
 2 using namespace std;
 3 const int N = 7;
 4 long long A, B, n,f1,f2,f3;
 5 int math[100000];
 6 int main()
 7 {
 8     ios::sync_with_stdio(false);
 9     cin.tie(0);
10     while(cin >> A >> B >> n &&(A ||B|| n)){
11          if(n==1||n==2){
12             cout << 1 << endl;
13             continue;
14         }
15         math[1] = math[2] = 1;
16         int i, j, crr = 0, star;
17         for(i = 3; i <= n; i++){
18             math[i] = (A*math[i-1]+B*math[i-2])%7;
19             for(j=2; j < i; j++){
20                 if(math[j-1]==math[i-1] && math[j]==math[i]){//找到周期
21                     crr = i - j;
22                     i = n + 2;
23                     star = j - 1;
24                     break;
25                 }
26             }
27         }
28         if(i==n+1)
29             cout << math[n] << endl;
30         else{
31             n = n - star;
32             n %= crr;
33             n += star;
34             cout << math[n] << endl;
35         }
36     }
37     return 0;
38 }
原文地址:https://www.cnblogs.com/MingSD/p/8460484.html