这道题虽然不是很难(看着好像不难),代码量也不大,但是我经历了超时,超内存才整出来,所以把这题记录下来
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
Time Limit Exceeded
#include<cstdio>
int main()
{
int A,B,n;
while(scanf("%d%d%d",&A,&B,&n)!=EOF)
{
if(A==0&&B==0&&n==0)
break;
int fn_1=1,fn_2=1;
int fn_3;
for(int i=2;i<n;i++)
{
fn_3=(A*fn_2+B*fn_1)%7;
fn_1=fn_2;
fn_2=fn_3;
}
printf("%d\n",fn_3);
}
return 0;
}
代码思路是简单,就暴力求解……n的数据很大,就会超时
Memory Limit Exceeded
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
int A,B,n;
while(scanf("%d%d%d",&A,&B,&n)!=EOF)
{
if(A==0&&B==0&&n==0)
break;
vector<int> m;
int fn_1=1,fn_2=1;
int fn_3;
m.push_back(fn_1);m.push_back(fn_2);
for(int i=2;i<n;i++)
{
fn_3=(A*fn_2+B*fn_1)%7;
fn_1=fn_2;
fn_2=fn_3;
if(fn_2==1&&fn_1==1)
{
break;
}
else
m.push_back(fn_2);
}
if(n==1||n==2)
printf("1\n");
else
printf("%d\n",m[(n-1)%(m.size()-1)]);
}
return 0;
}
用vector来解,空间不够……这个的思路就是求循环的一个周期,跟着计算就可
AC代码
#include<cstdio>
int main()
{
int A,B,n;
while(scanf("%d%d%d",&A,&B,&n)!=EOF)
{
int m[49];
if(A==0&&B==0&&n==0)
break;
int fn_1=1,fn_2=1;
int fn_3;
m[0]=1;m[1]=1;
for(int i=2;i<49;i++)
{
fn_3=(A*fn_2+B*fn_1)%7;
fn_1=fn_2;
fn_2=fn_3;
m[i]=fn_2;
}
printf("%d\n",m[(n-1)%49]);
}
return 0;
}
f(n-1)与f(n-2)的取值范围为[0,6],七种情况,49(7*7)是一个循环(也可能比49小)
只记录49之前的就可