hdu 1005

Number Sequence

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


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
 
說明:本題不能直接用遞歸解,因爲題目中顯示:1 <= A, B <= 1000, 1 <= n <= 100,000,000,如果直接遞歸則會溢棧出錯。由於n值很大利用循環遞歸雖然不會超時,但用時太長。仔細審題便會發現本題有規律可循,f(1)=1,f(2)=1,如果出現連續的兩個1,則說明數列出現循環,可以提前結束循環,找出f(n)!
#代碼(1)#直接遞歸,出錯!

//////////////Runtime Error////////////////

#include<stdio.h>
int fun(int x,int y,int z)
{
 int term;
 if(z==1 || z==2)
  term=1;
 else
  term=(fun(x,y,z-1)*x+fun(x,y,z-2)*y) % 7;
 return term;
}
int main()
{
 int a,b,n,result;
 while(scanf("%d%d%d",&a,&b,&n))
 {
  if(a==0 && b==0 && n==0)
   break;
  result=fun(a,b,n);
  printf("%d\n",result);
 }
 return 0;
}

#代碼(2)#循環遞歸,超時!

///////////////Time Limit Exceeded///////////

#include<stdio.h>
int main()
{
 int a,b,n,f1,f2,f3,i;
 while(scanf("%d%d%d",&a,&b,&n))
 {
  if(a==0 && b==0 && n==0)
   break;
     f1=1;f2=1;
  for(i=3;i<=n;i++)
  {
   f3=(f2*a+f1*b)%7;
   f1=f2;
   f2=f3;
  }
  printf("%d\n",f3);
 }
 return 0;
}

#代碼(3)#正解
 
/////////////////////////AC//////////////////////////

#include <stdio.h>
int main()
{
 int a,b,n,i,shuzu[10000];
 while(scanf("%d%d%d",&a,&b,&n),a || b || n)
 {
  shuzu[1]=1;
  shuzu[2]=1;
  for(i=3;i<10000;i++)
  {
   shuzu[i]=(a*shuzu[i-1]+b*shuzu[i-2])%7;
   if(shuzu[i]==1 && shuzu[i-1]==1)         //如果出現連續的兩個1,則結束循環。
    break;
  }
  n=n%(i-2);                //因爲連續出現的兩個1是下次循環的初值,故不應計入本次循環次數,故要減去2  

  shuzu[0]=shuzu[i-2];          //本來n =0時,應將值計入shuzu[i-2],但是由於輸出方便,把shuzu[i-2]的值放入shuzu[0],即當n時i-2的整數倍時,輸出shuzu[0].
  printf("%d\n",shuzu[n]);
 }
 return 0;
}
  

 


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