HD1005Number Sequence

Number Sequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 83963 Accepted Submission(s): 19894

Problem Description

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

 

和许多同志一样,看到这道题之后,都会想到用递归去做,然后就会发现去溢出,然后再会去找这个sequence里面的规律,发现会是一个循环。这应该也是做题的一个过程吧,在讨论区里看到有大神说测试数据有问题(应该是很久以前的数据),便更加觉得这到题目有意思,虽然数学有点水,但谁叫自己是一个ACMer了,那就花点时间去会一会这倒题吧。

 

题解思路:
 
一个非负数数 % 7,结果是0 ~ 6。
假设你有两个数n和m,满足f(n)=f(m);f(n-1)=f(m-1),则按照题目所给公式,f(n)f(m)和前后的数会在一定范围内一一对应相等,所以会有一个循环周期存在,因为f(n)是依赖于f(n-1)和f(n-2),因此有7*7=49种情况,即循环周期是49;

以下是ac代码:
 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     int a,b,c, f[100],temp;
 5     while(cin>>a>>b>>c && !(a==0 && b==0 && c==0)){
 6      f[2]=1,f[1]=1;
 7      temp = c % 49;
 8         for(int i=3; i<=49;i++){
 9             f[i] = (a * f[i-1] +b * f[i-2]) % 7;
10         }
11         cout<<f[temp]<<endl;
12     }
13     return 0;
14 }

 

 

posted @ 2013-08-19 21:31  兰幽  阅读(669)  评论(0编辑  收藏  举报