Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 169743 Accepted Submission(s): 41874
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
呵呵,这题还是比较简单的,当然暴力解法是得不到ac的,因为递归一定会消耗大量的内存,还是把暴力解法贴出来吧:
#include<iostream>
#include<cstdio>
//#define LOCAL
using namespace std;
int f(int,int,long long );
int main(int argc, char **argv)
{
#ifdef LOCAL
freopen("data.in","r",stdin);
#endif
int A,B;
long long n;
while(cin>>A>>B>>n)
{
if(!(A||B||n))
break;
cout<<f(A,B,n)<<endl;
}
return 0;
}
int f(int A,int B, long long n)
{
if(n==1||n==2)
return 1;
return (A*f(A,B,n-1)+B*f(A,B,n-2))%7;
}
去测试了一下,没有什么大问题,直接就是超内存了,一点面子不给!!!
呵呵,当然,如果强行遍历,还会超时:
#include<iostream>
#include<cstdio>
//#define LOCAL
using namespace std;
int main(int argc, char **argv)
{
#ifdef LOCAL
freopen("data.in","r",stdin);
#endif
int A,B;
long long n;
int f1 = 1,f2 = 1,ans; //前面第一个,前面第二个
while(cin>>A>>B>>n)
{
if(!(A||B||n))
break;
if(n==1||n==2)
cout<<1<<endl;
int i;
for(i = 3; i <= n; i++)
{
ans = (A*f1+B*f2)%7;
f1 = f2;
f2 = ans;
}
cout<<ans<<endl;
}
return 0;
}
好了,不哔哔了,这里的n比较大,达到了一亿,所以暴力解法是不起作用的,考虑到后面有一个mod7,所以f(n-1),f(n-2)的范围一定在0,1,2,3,4,5,6中,所以利用排列组合的知识不难得知,最终答案最多有7X7=49类:
#include<iostream>
#include<cstdio>
//#define LOCAL
using namespace std;
int main(int argc,char **argv)
{
#ifdef LOCAL
freopen("data.in","r",stdin);
#endif
long long n;
int A,B;
int ans[49] = {1,1};
while(cin>>A>>B>>n)
{
if(!(A||B||n))
break;
for(int i = 2; i < 49; i++)
{
ans[i] = (A*ans[i-1]+B*ans[i-2])%7;
}
cout<<ans[(n-1)%49]<<endl;
}
return 0;
}