HDU 1005 Number Sequence (迴圈節)

來源:互聯網
上載者:User

標籤:hdu 1005   number sequence   f1 1   f2 1   fn a fn - 1 + b f   


首先暴力打表就很容易發現有迴圈節,於是一開始的寫法是直接暴力找迴圈節,結果一直WA,

原因是有的迴圈並不是從1,1開始的,詳細有證明戳這裡:http://acm.hdu.edu.cn/discuss/problem/post/reply.php?postid=19818&messageid=1&deep=0

於是借鑒了大神的思路,因為%7,故可用v[7][7]來記錄 f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.這個狀態。若出現相同的狀態,則證明出現了迴圈節。

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1005

代碼如下:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cctype>#include<algorithm>#include<string>#define N 100using namespace std;int v[7][7]; int f[N]={0,1,1};int main(){    int A,B,n;    while(scanf("%d%d%d",&A,&B,&n),A+B+n)    {        int x=1,y=1,k=3;        memset(v,0,sizeof(v));        while(!v[x][y])        {            v[x][y]=k;//記錄這種狀態出現的位置。            f[k]=(A*y+B*x)%7;            x=y;            y=f[k];            k++;        }        int s=v[x][y];        //因為迴圈可能不是從1,1開始,所以這裡很重要。        if(n<k) printf("%d\n",f[n]);         else printf("%d\n",f[(n-s)%(k-s)+s]);//k-s即周期T。    }    return 0;}


HDU 1005 Number Sequence (迴圈節)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.