HDOJ Number Sequence(java)
2014-05-25 13:27
204 查看
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 98960 Accepted Submission(s): 23770
[align=left]Problem Description[/align]
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).
[align=left]Input[/align]
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.
[align=left]Output[/align]
For each test case, print the value of f(n) on a single line.
[align=left]Sample Input[/align]
1 1 3 1 2 10 0 0 0
[align=left]Sample Output[/align]
2 5 AC代码:利用递推公式去求解肯定会超时,解决本问题的关键之处在于问题是对于7求余,使得所得的解空间一定在0-6范围内,又f[1],f[2]值给出,找出其循环的位置就可(借鉴了下大牛的代码) [code] import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean[][] flag = new boolean[7][7]; //统计出现首次循环的标志 Vector<Integer> v = new Vector<Integer>(); while(in.hasNext()){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); v.clear(); if(a==0 && b==0 && n==0) break; for(int i=0; i<7; i++){ for(int j=0; j<7; j++){ flag[i][j] = false; } } v.add(1); v.add(1); flag[1][1] = true; int count = 1,f; //count记录重复元素之前所包含的元素个数 while(true){ f = (a*v.get(count)%7 + b*v.get(count - 1)%7)%7; v.add(f); ++count; if(flag[v.get(count)][v.get(count-1)] == true) //出现相邻重复元素时跳出循环,否则将对应的位置设置为true break; else flag[v.get(count)][v.get(count-1)] = true; } count = count-1; if(n <= count) System.out.println(v.get(n-1)); else{ int j; for(j=0 ;; j++){ if(v.get(j) == v.get(count) && v.get(j+1) == v.get(count+1)) //获得首次出现循环元素的下标j break; } n = (n - j)%(count - j); if(n == 0) n = count - j; n += j; System.out.println(v.get(n-1)); } } } }
[/code]
相关文章推荐
- (HDOJ 1005)Number Sequence
- hdoj 1711 KMP Number Sequence
- HDU 1711 HDOJ 1711 Number Sequence ACM 1711 IN HDU
- oracle number sequence 和 java.util.Long范围关系oracle sequence的取值范围是
- HDOJ(1005) Number Sequence
- 杭电OJ(HDOJ)1005题:Number Sequence(规律递推)
- hdoj 1711 Number Sequence
- hdoj 1711 KMP Number Sequence
- hdoj1005--Number Sequence
- HDOJ 1005 Number Sequence规律题
- Number Sequence ----HDOJ 1711
- ACM—Number Sequence(HDOJ1005)
- PKU ACM-1019题 java Number Sequence
- 【HDOJ】1005 -> Number Sequence
- HDOJ1005:Number Sequence 快速数组幂
- HDOJ&nbsp;&nbsp;1005&nbsp;&nbsp;&nbsp;Number&nbsp;Sequence
- java.lang.NumberFormatException
- java.lang.UnsupportedClassVersionError: Bad version number in .class file 解决方法
- 异常备忘:java.lang.UnsupportedClassVersionError: Bad version number in .class file
- java.lang.UnsupportedClassVersionError: Bad version number in .class file