HDU 1005 Number Sequence

Number Sequence

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



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
 題解:我看這道題的時候,第一眼就看見n的範圍很大,所以,常規的遞歸肯定會超時,所以這是一道規律題……因爲結果跟A B有關,所以x[i]的值肯定跟x[i-1]和x[i-2]有關,我猜測1 ,1 一定是這段循環體的開頭,所以我就用for循環找,直到從新找到1,1這個循環體的開頭,進而求出循環體的長度,然後n對長度取餘,進而求解,但是提交之後wrong了……
後來,我寫了一段代碼,模擬了當A,B任意取值時,x[i]的記過。發現了一段特殊的循環體“0”,當A,B的值都是7的倍數時,x[i]的值從第三項起都是0,我把這個特殊的循環體給特意寫出來就直接過了……



#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<string>
#include<math.h>
#include<map>
#include<queue>
#include<stack>
#define INF 0x3f3f3f3f
#define ll long long
#define f(i,a,b) for(int i=a;i<b;i++)
#define sf(a)  scanf("%d",&a)
#define sff(a,b)  scanf("%d%d",&a,&b)
#define sfff(a,b,c)  scanf("%d%d%d",&a,&b,&c)
#define pf(a) printf("%d\n",a)
#define p printf("\n")
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
#define mod 1000000
int x[10000];
int main()
{
    int a,b,n,c=1;
    while(~sfff(a,b,n)&&(a,b,n))
    {
        if(a%7==0&&b%7==0)
        {
            if(n>2)pf(0);
            if(n<=2)pf(1);
            continue;
        }
        x[1]=1,x[2]=1;
        f(i,3,10000)
        {
            x[i]=(a*x[i-1]+x[i-2]*b)%7;
            if(x[i]==1)
            {
                if(x[i-1]==1)
                {
                    c=i-2;
                    break;
                }
            }
        }
        int dd=n%c;
        if(dd)pf(x[dd]);
        else pf(x[c]);
    }
}


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