P17070 [ICPC 2017 Shenyang R] Heron and His Triangle

· · 题解

也是把队友带飞到了第 21 名。

设 a=t-1,b=t,c=t+1。

根据海伦公式:

p=\frac{a+b+c}{2}=\frac{3t}{2} \begin{aligned} S&=\sqrt{p(p-a)(p-b)(p-c)}\\ &=\sqrt{\frac{3t}{2}\cdot\frac{t}{2}\cdot(\frac{t}{2}-1)\cdot(\frac{t}{2}+1)}\\ &=\sqrt{3\cdot(\frac{t}{2})^2\cdot\big((\frac{t}{2})^2-1\big)} \end{aligned}

题目要求 S 为整数,则根号下部分必须为完全平方数。(\frac{t}{2})^2 是平方数,则只需要 3\cdot\big((\frac{t}{2})^2-1\big) 为平方数。

设 x^2=(\frac{t}{2})^2,3 \times y^2=(\frac{t}{2})^2-1。则得到方程:

x^2-3\times y^2=1

发现这是一个 d=3 的 Pell 方程。其递推公式为:

x_n=x_{n-1} \cdot x_1 + y_{n-1} \cdot y_1 \cdot d y_n=x_{n-1} \cdot y_1 + y_{n-1} \cdot x_1

可先求得特解 x_1=2,y_1=1。然后根据该式计算即可。注意需要使用 __int128。

#include <bits/stdc++.h>
using namespace std;

int t;
__int128 x[114], y[114], d = 3;

__int128 read() {
    __int128 x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
void write(__int128 x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

signed main(){
    scanf("%d", &t);
    x[1] = 2, y[1] = 1;
    for(int i = 2; i <= 100; ++ i){
        x[i] = x[i - 1] * x[1] + y[i - 1] * y[1] * d;
        y[i] = x[i - 1] * y[1] + y[i - 1] * x[1];
    }
    while(t --){
        __int128 n = read();
        for(int i = 1; i <= 100; ++ i)
            if(x[i] * 2 >= n){
                write(x[i] * 2);
                putchar('\n');
                break;
            }
    }

    return 0;
}