HDU 1005 Number Sequence【序列號】

Number Sequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 169920 Accepted Submission(s): 41910
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

Author
CHEN, Shunbao

Source
ZJCPC2004*

意思就是有個公式,f(1)=1 , f(2)=1 , f(n)=(A x f(n-1)+B x f(n-2)) mod 7。A,B將會在每個測試數據中輸入。

跟斐波那契數列一個思路,就是慢慢往上推嘛。
於是我就用遞歸法寫了一個。


int f(int n){
    if(n==1||n==2)
        return 1;
    return (A*f(n-1)+B*f(n-2))%7;
}

於是,Memory Limit Exceeded。
嗯,那我用迭代(循環)。

 int a,b,c;
        a=1;b=1;
        if(n==1||n==2)
            printf("1\n");
        else{
            for(int i=2;i<n;++i){
                c=(A*b+B*a)%7;
                a=b;
                b=c;
            }

嗯,Time Limit Exceeded。

好吧,我還是too young。我上網搜了一下題解,他們是這麼說的:

1.n的數值很大,這類數值很大的問題一般都有規律,找出循環節(週期)是關鍵;
2.找規律,這道題是從 f(1) = 1 和 f(2) = 1 開始,然後依次模7,可知 f(n) 只有7種情況,所以兩數相鄰只有7*7=49種;
3.所以從 f(1) 到 f(49) 必會出現相鄰兩個 f(m-1) = 1 , f(m) = 1,所以 f(n) 爲周期函數,49爲其一個週期
需要注意的地方:
做題的時候不要盲目的上手去做,先要仔細分析題目,先動腦再動手

先動腦在動手這句話說對了,,,,我不該那麼傻的。
不過我也不知道爲啥49個一個週期,嗚嗚。不過代碼經過修改反正是過去了。

AC 代碼:

#include<cstdio>
int A,B;
int main(){
    int n;
    while(~scanf("%d %d %d",&A,&B,&n)&&A&&B&&n){
        int a,b,c;
        a=1;b=1;
        n%=49;
        if(n==1||n==2)
            printf("1\n");
        else{
            for(int i=2;i<n;++i){
                c=(A*b+B*a)%7;
                a=b;
                b=c;
            }
            printf("%d\n",c);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章