【ACM】HDU 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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值