hdu1005 找规律 枚举

来源:互联网 发布:前端如何请求后台数据 编辑:程序博客网 时间:2024/04/28 22:03

如果直接做 则会超时。。

#include <iostream>using namespace std;int main(){    int A,B,n,f[4];    while(cin>>A>>B>>n)    {        if(!(A || B || n)) return 0;        else        {            f[1] = 1;f[2] = 1;            for(int i = 1;i <= n -2;i++)            {                f[3] = (A * f[2] + B * f[1]) % 7;                f[1] = f[2];                f[2] = f[3];            }            cout<<f[3]<<endl;        }    }    return 0;}

仔细观察 f[n] = (A*f[n-1] +B*f[n-2]) % 7

所以f[n]的取值为0到6;

在计算f[n]的过程中 f[n-1]和f[n-2] 要是和初始值f[1] = 1,f[2] =1 相等的话则后面就开始产生循环了

那么   f[n-1]和f[n-2] 有多少种组合了 很明显有 7 * 7 = 49 中组合 所以这个序列的周期必然小于等于49

第一步先来个循环把序列的周期算出来 

第二步把要算的序列总的第n个数mod周期即可

#include <iostream>#include<cstdio>using namespace std;int main(){    int A,B,n,i,f[60];//    freopen("data.txt","r",stdin);//    freopen("out.txt","w",stdout);    while(cin>>A>>B>>n && (A||B||n))    {        f[1] = 1;        f[2] = 1;        for(i = 3; i <= 49; i++)        {            f[i] = (A * f[i-1] + B * f[i-2]) % 7;            if( f[i-1] == 1 && f[i] == 1)break;        }        n = n % (i - 2);        if(n == 0) n = i -2;        cout<<f[n]<<endl;    }    return 0;}

其实我们也可以不算周期 

已经知道了周期必然小于等于49

那我们直接先把序列的钱49个值直接算出来

要算序列的第N个值直接mod 49即可 

这样更方便快捷容易理解

#include <iostream>#include<cstdio>using namespace std;int main(){    int A,B,n,i,f[50];    while(cin>>A>>B>>n && (A||B||n))    {        f[1] = 1;        f[2] = 1;        for(i = 3; i <= 49; i++)            f[i] = (A * f[i-1] + B * f[i-2]) % 7;        n = n % 49;        if(n == 0) n = 49;        cout<<f[n]<<endl;    }    return 0;}

容易出错的地方就是数组越界。。。委屈越界后没有报错。。n直接变成1了  

另外还有人用矩阵的快速幂 mark一下 以后在尝试用这种方法做做

hdu 1005Number Sequence (矩阵快速幂)


0 0
原创粉丝点击