HDU-1005-Number Sequence(Java版+考慮周期+噁心水題!)

來源:互聯網
上載者:User

標籤:hdu   java   重複持續時間   爆炸   噁心水題   

Number SequenceTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 122527    Accepted Submission(s): 29758


Problem DescriptionA 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).
 
InputThe 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.
 
OutputFor each test case, print the value of f(n) on a single line.
 
Sample Input
1 1 31 2 100 0 0
 
Sample Output
25
 
AuthorCHEN, Shunbao 
SourceZJCPC2004 
RecommendJGShining   |   We have carefully selected several similar problems for you:  1008 1021 1019 1003 1009 

有時候會懷疑出這種題目的作者是不是腦子有問題?只有20%的通過率,12萬多的acmer提交只有3萬不到的通過率!你想題目一定是很難吧,其實不是,題目是很坑!(1 <= A, B <= 1000, 1 <= n <= 100,000,000)裡面n的取值範圍是一個億,如果直接遞迴來代入的話!肯定堆疊溢位.....(因為我試過!)最後在網上查了一下思路:因為f(n)的結果是模7的,那麼f(n)的結果只可能在{0,1,2,3,4,5,6,}中,這樣f(n)與f(n-1)的結果只可能是7*7 = 49種,合理利用周期性,便可以大大提高程式已耗用時間。
不想說了,這題多說一句話都make me sick!!感謝金永慶博友的解答!http://blog.csdn.net/jinyongqing/article/details/21537175

import java.io.*;import java.util.*;public class Main{      public static void main(String[] args)     {          Scanner input = new Scanner(System.in);          int a, b;          int n;          while (input.hasNext())         {              a = input.nextInt();              b = input.nextInt();              n = input.nextInt();              if (a == 0 & b == 0 & n == 0)                  System.exit(0);              int f[] = new int[50];              for (int i = 1; i < 50; i++)             {                  if (i == 1 || i == 2)                 {                      f[i] = 1;                  } else                 {                      f[i] = (a * f[i - 1] + b * f[i - 2]) % 7;                  }              }              System.out.println(f[n % 49]);          }      }    }  




 

HDU-1005-Number Sequence(Java版+考慮周期+噁心水題!)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.