1. 程式人生 > >【ACM】杭電OJ 1005 Number Sequence (for java)

【ACM】杭電OJ 1005 Number Sequence (for java)

最開始的程式碼是這樣的,沒說我超時,直接報錯~~

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	
	public static int num(int A,int B,int n) {
			int[] ans = new int[n + 1];
			ans[1] = 1;
			ans[2] = 1;
			for(int i = 3; i <= n; i++) {
				ans[i] = (A * ans[i - 1]  + B * ans[i - 2]) % 7;
			}
			return ans[n];
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		
		while (scanner.hasNext()) {
			int A = scanner.nextInt();
			int B = scanner.nextInt();
			int n = scanner.nextInt();
			if (A == 0 && B == 0 && n == 0) {
				break;
			}
			
			int res = num(A,B,n);		
			System.out.println(res);

		}
	}	
}

後來通過參考別人的程式碼發現是有規律的,最後是對7取餘數,所以,f(n-1),f(n-2)最多各有七種情況(0、1、2、3、4、5、6),所以f(n)最多有7*7=49種情況,所以從一開始到49可能不盡相同,但是從50開始則開始迴圈,f(50)=f(50%49)=f(1)。這是解決超時和記憶體不夠的辦法。 

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	
	public static int num(int A,int B,int n) {
			int[] ans = new int[n + 1];
			ans[1] = 1;
			ans[2] = 1;
			for(int i = 3; i <= n; i++) {
				ans[i] = (A * ans[i - 1]  + B * ans[i - 2]) % 7;
			}
			return ans[n];
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		
		while (scanner.hasNext()) {
			int A = scanner.nextInt();
			int B = scanner.nextInt();
			int n = scanner.nextInt();
			if (A == 0 && B == 0 && n == 0) {
				break;
			}
			
			int res = num(A,B,n);		
			System.out.println(res);

		}
	}	
}

參考資料:

https://blog.csdn.net/CSDN___CSDN/article/details/82933844