打表找规律

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

题解:此题数据规模较大,如果运用直接暴力方法显然不可行。对于公式 f[n] = A * f[n-1] + B * f[n-2]; 后者只有7 * 7 = 49 种可能,为什么这么说,因为对于f[n-1] 或者 f[n-2] 的取值只有 0,1,2,3,4,5,6 这7个数,A,B又是固定的,所以就只有49种可能值了。由该关系式得知每一项只与前两项发生关系,所以当连续的两项在前面出现过循环节出现了,注意循环节并不一定会是开始的 1,1 。 又因为一组测试数据中f[n]只有49中可能的答案,最坏的情况是所有的情况都遇到了,那么那也会在50次运算中产生循环节。找到循环节后,就可以轻松解决了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstring>
#include<string>
using namespace std;
const int maxn=50;
int s[maxn];
int main()
{
    int a,b,n;
    while(cin>>a>>b>>n)
    {
        if(a==0&&b==0&&n==0)
            break;
        memset(s,0,sizeof(s));
        s[1]=1;
        s[2]=1;
        for(int i=3;i<50;i++)
            s[i]=(a*s[i-1]+b*s[i-2])%7;
        n%=49;
        cout<<s[n]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wolf940509/p/4268421.html