HDU6222 Heron and His Triangle【大數+遞推式】

Heron and His Triangle

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 4076 Accepted Submission(s): 1642

Problem Description
A triangle is a Heron’s triangle if it satisfies that the side lengths of it are consecutive integers t−1, t, t+ 1 and thatits area is an integer. Now, for given n you need to find a Heron’s triangle associated with the smallest t bigger
than or equal to n.

Input
The input contains multiple test cases. The first line of a multiple input is an integer T (1 ≤ T ≤ 30000) followedby T lines. Each line contains an integer N (1 ≤ N ≤ 10^30).

Output
For each test case, output the smallest t in a line. If the Heron’s triangle required does not exist, output -1.

Sample Input
4
1
2
3
4

Sample Output
4
4
4
4

Source
2017ACM/ICPC亞洲區瀋陽站-重現賽(感謝東北大學)

問題鏈接HDU6222 Heron and His Triangle
問題簡述:給定一個整數 N(1≤𝑁≤1030),求最小的整數 t,滿足 t≥N,使得邊長爲t−1,t,t+1 的三角形面積爲整數。
問題分析
    可以通過離線打表,得到序列:2 4 14 52 194 724 2702 10084 37634。使用這個序列可以得到遞推式f[n]=4*f[n-1]-f[n-2]。需要注意的是,這是一個大數問題,可以用Java語言程序來實現。也許使用128位整數計算就可以了。
    另外一種解法是推導出佩爾方程來解決,但是需要使用128位整數來計算。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的Java語言程序如下:

/* HDU6222 Heron and His Triangle */

import java.util.*;
import java.math.*;

public class Main{
    public static void main(String[] args){
        BigInteger a = BigInteger.valueOf(4);
        BigInteger b = BigInteger.valueOf(14);

	/* 打表 */
        List<BigInteger> list = new ArrayList <>();
        list.add(a);
        list.add(b);
        BigInteger tmp;
        while(b.compareTo(BigInteger.TEN.pow(30)) <= 0) {
            BigInteger c = BigInteger.valueOf(4);
            tmp = b;
            b = c.multiply(b).subtract(a);
            list.add(b);
            a = tmp;
        }

        Scanner cin = new Scanner(System.in);
        int t = cin.nextInt();
        while(t-- > 0) {
            BigInteger n = cin.nextBigInteger();
            for(BigInteger x:list){
                if(n.compareTo(x) <= 0) {
                    System.out.println(x);
                    break;
                }
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章