HDU-1005 Number Sequence(錯誤驗證集)

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

1 1 49
以下是前18項 可以手算驗證 從第17項開始循環,循環的mod是16
 1    1    2    3    5    1    6    0    6    6    5    4    2    6    1    0    1    1

答案應該是1
1

以下是我WA的代碼 在1 1 49 時輸出1,答案是正確的

#include<iostream>
#include<vector>
// 1 1 49
// loopbegin  1  loopMod  16
using namespace std;
int A,B,N;
// all fn are between 0-6
//how many  can form a loop  
//it must be a loop 
int loopbegin;
int loopMod;

int calculate()
{
    int fn[100000];
    fn[0]=0;
    fn[1]=1;
    fn[2]=1;
    if(N<=2){return 1;}
    int current_ind=3;
    bool findLoop=false;
    A%=7;
    B%=7;
    if(0)
    {
        cout<<"A  "<<A<<"  B  "<<B<<endl;
    }
    while(1)
    {
        if(current_ind>=3)
        {
           fn[current_ind]=(A*fn[current_ind-1]+B*fn[current_ind-2])%7; 
           
        }
        //check if it is loop now
        for(int i=1;i<current_ind-2;i++)
        {
            if(fn[i]==fn[current_ind-1]&&fn[i+1]==fn[current_ind])
            {
                //find the loop
                findLoop=true;
                loopbegin=i;
                loopMod=current_ind-1-i;
                break;
            }
        }
        if(findLoop||current_ind>=N)
        {
            break;
        }
        current_ind++;
        
        //I guess it must be in a loop 
    }
    int finalAns=0;
    int end_position=N;
    if(findLoop)
    {
        if(N<=loopbegin)
        {
            finalAns=fn[N];
        }
        else
        {
            int equal=(N-loopbegin)%loopMod+loopbegin;
            if(equal==0){equal=loopMod;}
            end_position=loopbegin+loopMod+1;
            fn[N]=fn[equal];
            finalAns=fn[equal];
        }
    }
    else
    {
        finalAns=fn[N];
//        return fn[N];
    }
    return finalAns;
}
int main()
{
    while(cin>>A>>B>>N)
    {
        if(A==0&&B==0&&N==0)
        {
            break;
        }else
        {
            int ans=calculate();
            cout<<ans<<endl;
        }
    }
    return 0;
}

以下是AC的代碼,1 1 17時輸出1,在1 1 49 時輸出0,答案是錯誤的

#include <iostream>
using namespace std;
int arr[50];
int main()
{
    int n,a,b;
    arr[1]=arr[2]=1;
    while(cin>>a>>b>>n)
    {
        if(a==0&&b==0&&n==0)
            break;
        int minn=n<50?n:50;//一個小小的優化
        for(int i=3; i<=minn; i++)
        {
            arr[i]=(a*arr[i-1]+b*arr[i-2])%7;
        }
        cout<<arr[n%49]<<endl;
 
    }
    return 0;
}

提供一個matlab代碼驗證

a(1)=1;
a(2)=1;
for i=3:49
    a(i)=mod(a(i-1)+a(i-2),7);
end
a49=a(49)

%最終a49是1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章