Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 175464 Accepted Submission(s): 43356Problem 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 0Sample Output
2
5
思路
1、审清楚题目Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000).
C解法(AC了)
#include <stdio.h>
int main()
{
int a,b,n;
while(scanf("%d %d %d",&a,&b,&n))
{
int i;
int seq[1000]={0};
seq[1]=1;
seq[2]=1;
int t;
if(a==0&&b==0&&n==0)
{
break;
}
for(i=3;i<=49;i++)
{
seq[i]=(a*seq[i-1]+b*seq[i-2])%7;
}
t=n%49;
printf("%d\n",seq[t]);
}
return 0;
}
这段代码之所以能AC,因为它的时间复杂度不高(待会会给出时间复杂度高而不能AC的代码),主要算法是在
for(i=3;i<=49;i++)
{
seq[i]=(a*seq[i-1]+b*seq[i-2])%7;
}
t=n%49;
printf(“%d\n”,seq[t]);
1、首先看到题目给出的公式有%7,这个足以说明f[n]的值一定在0—6之间,所以根据知道的f[1]和f[2]的值,重新回到1 1说明一个周期,所以两两配对,一共有7个数据,所以总共有49种可能
2、既然有49种可能,那么n%49的余数肯定是小于49的所以利用for循环将f[n]的数据都存入seq数组中,而且只要49次循环即可(时间复杂度低)
上面之所以能AC是因为控制循环变量不大。
若使用迭代法或者递归法控制循环变量都是1到100,000,000,那时间复杂度就太高导致Time Limit Exceeded或Runtime Error(STACK_OVERFLOW)
C递归解法(RuntimeError(STACK_OVERFLOW))
(类似斐波那契数列)
#include<stdio.h>
int A,B;
int process(int n)
{
if(n!=1&&n!=2)
return (A*process(n-1)+B*process(n-2))%7;
else
return 1;
}
int main()
{
int n;
while(1)
{
scanf("%d %d %d",&A,&B,&n);
if(A!=0&&B!=0&&n!=0)
printf("%d",process(n));
else break;
}
}
C迭代法(Time Limit Exceeded)
#include <stdio.h>
int main()
{
int a, b;
int n;
int i;
int t;
int c,d;
while(1){
scanf("%d %d %d", &a, &b, &n);
if (a == 0 && b == 0&&n == 0)
break;
for(i=2;i<n;i++)//依靠n控制循环,每下一次循环c将覆盖d的值(f[n-1]和f[n-2]),然后f[n]的值也将覆盖f[n-1]的值,所以t赋值给c,然后通过n结束的出c即f[n]
{
t=(a*c+b*d)%7;
d=c;
c=t;
}
printf("%d\n",c);
}
return 0;
}
主要算法部分:依靠n控制循环,每下一次循环c将覆盖d的值(f[n-1]和f[n-2]),然后f[n]的值也将覆盖f[n-1]的值,所以t赋值给c,然后通过n结束的出c即f[n]