標籤: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版+考慮周期+噁心水題!)