题解:P17070 [ICPC 2017 Shenyang R] Heron and His Triangle
ACcepted917
·
·
题解
题解:[ICPC 2017 Shenyang R] Heron and His Triangle
题目大意
给定 n,找到最小的 t \ge n,使得边长为 t-1,t,t+1 的三角形面积为整数。若无解输出 -1。
### 分析
纯数学题。
设三角形三边长为 $t-1,t,t+1$,半周长 $p = \dfrac{3t}{2}$。
由[海伦公式](https://baike.baidu.com/item/%E6%B5%B7%E4%BC%A6%E5%85%AC%E5%BC%8F/106956),面积 $S$ 满足
$$
\begin{aligned}
S &= \sqrt{p(p-(t-1))(p-t)(p-(t+1))}\\
&= \sqrt{\frac{3t}{2} \cdot \left(\frac{t}{2}+1\right) \cdot \frac{t}{2} \cdot \left(\frac{t}{2}-1\right)} \\
&= \frac{t}{4}\sqrt{3(t^2-4)}.
\end{aligned}
$$
$S$ 为整数当且仅当 $\sqrt{3(t^2-4)}$ 为整数,且整个表达式结果为整数。
进一步,令 $t=2x$($x \in \mathbb{N}^+$),则
$$
S = x\sqrt{3(x^2-1)}.
$$
记 $y = \sqrt{3(x^2-1)}$,要求 $y$ 为正整数。两边平方得
$$
y^2 = 3(x^2-1) \quad\Rightarrow\quad x^2 - 3\left(\frac{y}{3}\right)^2 = 1.
$$
因为 $y^2$ 是 $3$ 的倍数,故 $y$ 必为 $3$ 的倍数,设 $y = 3z$,则
$$
x^2 - 3z^2 = 1.
$$
这是一个标准的 Pell 方程。其最小正整数解为 $(x,z) = (2,1)$,对应 $t = 2x = 4$,面积 $S = 3xz = 6$。
Pell 方程 $x^2 - 3z^2 = 1$ 的所有正整数解可由基本解 $(2,1)$ 迭代得到:
$$
\begin{cases}
x_{k+1} = 2x_k + 3z_k, \\
z_{k+1} = x_k + 2z_k.
\end{cases}
$$
由此可推出 $t$ 的递推关系:
$$\begin{aligned}
t_{k+1} &= 2x_{k+1} = 4x_k + 6z_k \\ &= 4t_k - 2x_{k-1}\\ & = 4t_k - t_{k-1}.\end{aligned}
$$
验证前几项:$t_1 = 4$,$t_2 = 14$,$t_3 = 4 \times 14 - 4 = 52$,均正确。
于是我们可以递推生成所有合法的 $t$ 值,直到超过数据上限 $10^{30}$。对于每个询问,在序列中二分查找第一个 $\ge n$ 的 $t$ 即可。
重现赛时那个递推关系是我试出来的,后来才知道 Pell 方程。
### 实现细节
- 因为 $n$ 高达 $10^{30}$,$t$ 的值也会超过 `long long` 范围。代码中使用了 GCC 的 128 位整数 `__int128`,读入和输出时需自行转换。
- 当序列末尾超过 $10^{30}$ 时停止递推(可以适当多生成一两个)。
- 多组数据 $T$ 可达 $30000$,预处理后在序列上二分,单次查询 $O(\log \text{len})$,总复杂度可以接受。
## 代码
```cpp
#include<bits/stdc++.h>
#ifdef __unix__
#define gc getchar_unlocked
#else
#define gc _getchar_nolock
#endif
using namespace std;
typedef long long ll;
const int N=1e5+5;
#define int __int128
inline int read(){
register int x=0,f=1;char c=gc();
while(!isdigit(c)){if(c=='-')f=-1;c=gc();}
while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=gc();
return x*f;
}
string int128tos(int x){
if(x==0)return "0";
string s;
while(x>0){
s+=(char)('0'+(x%10));
x/=10;
}
reverse(s.begin(),s.end());
return s;
}
int t1=4,t2=14;
vector<int>seq;
int stoint128(string s){
int res=0;
for(char c:s)res=res*10+(c-'0');
return res;
}
int t,n;
signed T;
signed main(){
seq.push_back(t1);
seq.push_back(t2);
int lim=stoint128("1000000000000000000000000000000");
while(seq.back()<=lim){
t=4*t2-t1;
seq.push_back(t);
t1=t2;
t2=t;
}
cin>>T;
while(T--){
n=read();
auto it=lower_bound(seq.begin(),seq.end(),n);
if(it!=seq.end())cout<<int128tos(*it)<<'\n';
else cout<<"-1\n";
}
return 0;
}
``````
哦,忘说了,我们导出的 $t$ 数列是无穷递增的,所以理论上不会输出 `-1`。