代码改变世界

Number Sequence

2016-02-26 14:56  想打架的蜜蜂  阅读(209)  评论(0)    收藏  举报

Number Sequence

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

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

这题一看很简单,但是有陷阱,就是内存限制,看题目公式知道是个递归,大家都知道递归是消耗栈空间的

本人菜鸟,一开始也是内存限制问题弄错了,后来看网上大牛的思路如下:

这题的关键就在于时间,因为n可能很大很大.
但因为有mod 7,所以f(n)取值是0-6,共7个取值,而f(n)又由f(n-1) 和 f(n-2)两个决定,因此最多有7*7=49种可能的组合,因此在50以内必然出现循环,
所以我们用数组模拟前49组数组,后面的数据只要mod (模除)循环节就可以了,对应的的数组里头取值

以下是我的代码,已经被accept:

#include<iostream>

using namespace std;

int main()
{
int int_A=0;
int int_B=0;
int int_n=0;
while(cin>>int_A>>int_B>>int_n)
{
if((int_A==0)&&(int_B==0)&&(int_n==0)) break;
if((int_n<1)||(int_A<1)||(int_B>1000)||(int_n>100000000))
{
break;
}
else
{
int result[52]={1,1,0};
for(int i=2;i<52;i++)
{
result[i]= (int_A * result[i-1] + int_B * result[i-2]) % 7;
}
//找出循环的间隔
int jiange=0;
for(int i=3;i<52;i++)
{
if((result[2]==result[i]))//&&(result[3]==result[i+1])
{
jiange=i-2;
}
}
cout<<result[int_n%jiange-1]<<endl;
}

}
return 0;
}