hdu1105

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 153645    Accepted Submission(s): 37479


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
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:  1008 1004 1021 1019 1002

解題思路:由於題目給出的數據1 <= n <= 100,000,000,數據太大,若按照題目意思進行遞歸,定會超時,所以只能尋找規律。
解題心得:在比賽的時候,就想着這題目一點規律也沒有,也不好證明,就一直在糾結,這種題目就不應該出現在acm中,簡直折磨人。到後面自己心平氣和的坐下來,慢慢的思考這個問題時,發現自己還是太急躁了,我可以用遞歸的那種方法寫出程序,再打印出結果,也不用自己算,慢慢的找規律。還是要少一點抱怨,多用一點腦子。
用於尋找規律的代碼
#include <iostream>
#include<cstdio>
using namespace std;
int a,b,n,c[100000005];
int main()
{
    while(scanf("%d%d%d",&a,&b,&n)&&a!=0&&b!=0&&n!=0)
    {
        c[1]=1;
        c[2]=1;
        printf("1 1 ");
        for(int i=3;i<=n;i++)
        {
            c[i]=(a*c[i-1])%7+(b*c[i-2])%7;
            printf("%d ",c[i]);
        }
        printf("\n");
    }
    return 0;
}
各種測試數據的結果:

ac代碼:
#include <iostream>
#include<cstdio>
using namespace std;
int a,b,n,i,c[10000];
int main()
{
    c[1]=1;
    c[2]=1;
    while(scanf("%d%d%d",&a,&b,&n)&&a&&b&&n)
    {
        for(i=3;i<10000;i++)
        {
            c[i]=(a*c[i-1]+b*c[i-2])%7;
            if(c[i]==1&&c[i-1]==1)
                break;
        }
        n=n%(i-2);
        c[0]=c[i-2];
        printf("%d\n",c[n]);
    }
    return 0;
}


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