您的位置:首页 > 产品设计 > UI/UE

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: