hdu6222(递推规律+java大数)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/dl962454/article/details/78447789

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亚洲区沈阳站-重现赛(感谢东北大学)

题意:让你找这样的一个三角形,三条边为t,t-1,t+1,并且面积为整数,最后满足t大于等于n。

思路:暴力打表找规律。

暴力打表代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(scanf("%d", &n) != EOF)
    {
        for(int i = 4; i <= 10000; i++)
        {
            int p = (3 * i) / 2;
            int area = p * (p - i - 1) * (p - i + 1) * (p - i);
            bool flag = false;
            for(int j = 1; j <= sqrt(area) + 1; j++)
            {
                if(j * j == area && i >= n)
                {
                    flag = true;
                    printf("%d\n", i);
                    break;
                }
            }
            if(flag) break;
        }
    }
    return 0;

三角形面积公式:formula    其中P为三角形的半周长。(海伦公式)

打个表之后发现这样一些数字4,14,52,194,724,2702....然后得出递推式子,F[n]=4*F[n-1]-F[n-2];由于n非常的大,所以矩阵快幂维护也不行。最后考虑这样的数字几乎增长比较快,那么范围内这样的数字就会比较少,不想用高精度的可以考虑用java大数了,用个list将所有n范围内的结果保存一下,最后直接查询就可以了。

代码:

import java.util.*;
import java.math.*;
public class Main{
    public static void main(String[] args){
        BigInteger x=BigInteger.valueOf(4);
        BigInteger y=BigInteger.valueOf(14);
        List<BigInteger> list=new ArrayList <>();
        list.add(x);
        list.add(y);
        BigInteger t;
        while(y.compareTo(BigInteger.TEN.pow(30))<=0){
            BigInteger num2=BigInteger.valueOf(4);
            t=y;
            y=num2.multiply(y).subtract(x);
            list.add(y);
            x=t;
        }
        Scanner cin=new Scanner(System.in);
        int T=cin.nextInt();
        while(T-->0){
            BigInteger n=cin.nextBigInteger();
            for(BigInteger xx:list){
                if(n.compareTo(xx)<=0) {
                    System.out.println(xx);
                    break;
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/dl962454/article/details/78447789