HDU-—Number Sequence-1005(找规律)

Number Sequence

原题链接http://acm.hdu.edu.cn/showproblem.php?pid=1005

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,a,b,已知一序列满足f(1) = 1, f(2) = 1, f(n) = (a * f(n - 1) + b* f(n - 2)) mod 7.
让你求f(n)。

解题思路:相信你一开始也会想到利用递推求解吧,结果也肯定是意料之中,没错!超时!那么,针对这种数据这么大的,这么做肯定是行不通的,肯定是有规律可循的。我们来分析:
f(n)=(a*f(n-1)+b*f(n-2))%7=(a*f(n-1)%7+b*f(n-2)%7)%7,这里是利用了取余的运算法则,我们来看第一个a*f(n-1)经过7取余后只有7种可能得值0,1,2,3,4,5,6.第二个也是一样。而且a和b是固定的,故7*7=49种可能,经过这49次之后必然出现重复,故我们只需要对49取余即可。(其实还有种更无赖的方法,直接输出所有的值,我们找周期T就好。)

AC代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<cstring>
#include<memory.h>
#include<map>
#include<iterator>
#include<list>
#include<set>
#include<functional>

using namespace std;

const int maxn=1e8+2;
int n;
int a,b;
int result[maxn];
void solve(int n,int a,int b){
	result[0]=1;result[1]=1;
	for(int i=2;i<49;i++){
		result[i]=(a*result[i-1]+b*result[i-2])%7;
	}
	cout<<result[(n-1)%49]<<endl;//因为我们是从0开始的,减1即可。
}
int main(){
    while(cin>>a>>b>>n&&(a+b+n))
		solve(n,a,b);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzf0701/article/details/107611584
今日推荐