Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 154435 Accepted Submission(s): 37724
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).
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
Author
CHEN, Shunbao
Source
Recommend
JGShining
题意:给出计算f(n)的公式,求f(n)。
分析:由于给出的n的范围非常大,递归超时,也没有办法生成很大的数组,考虑找规律。由于结果都是对7取余的,可以打个表,很容易发现结果都是区间循环的,在这里我生成了长度为10005的表,从中可以进行暴力匹配,从i=3开始,1到i-1区间是被比对区间,i到2*i-2区间是匹配区间,一旦全部匹配说明发现了循环区间,此时只需要n对区间长度取余赋值即可得出结果。具体见AC代码:
#include<stdio.h>
const int maxn=10005;
int f[maxn];
int main()
{
int a,b,n;
while(~scanf("%d%d%d",&a,&b,&n)&&!(!a&&!b&&!n))
{
f[1]=1;
f[2]=1;
for(int i=3; i<maxn; i++)//先 生成一个数组
f[i]=(a*f[i-1]+b*f[i-2])%7;
int cnt;
for(int i=3; i<maxn; i++)
{
int flag=1;
for(int j=i; j<=2*i-2; j++)//1到i-1 和 i到2*i-2 进行匹配
if(f[j-i+1]!=f[j])
{
flag=0;
break;
}
if(flag)
{
cnt=i-1;//cnt是循环数组的长度
break;
}
}
n%=cnt;
if(n==0)
printf("%d\n",f[cnt]);
else
printf("%d\n",f[n]);
}
}
特记下,以备后日回顾。