首页 > 代码库 > CodeForces 707C Pythagorean Triples

CodeForces 707C Pythagorean Triples

数学,构造。

这题比较有意思,一开始没发现结论写了一个最坏复杂度为$O({10^9})$暴力居然能$AC$,正因为如此,我才发现了规律。

一开始是这么想的:

先假设$n$为直角边,设斜边长度为$c$,另一条直角边长度为$b$,因此有${c^2} - {b^2} = {n^2}$。

左边因式分解得到:$(c + b)(c - b) = {n^2}$。我们记$A = c + b$,$B=c-b$。那么:$c = \frac{{A + B}}{2}$,$b = \frac{{A - B}}{2}$。

因此,如果我们能找到${n^2}$的两个因子$A$和$B$,使得$A×B={n^2}$,并且使得$c$和$b$都是不为$0$的整数,那么就找到了在$n$作为直角边的情况下的答案。

如果上述条件下没有找到解,那么就设$n$作为斜边,设两个直角边分别为$a$和$b$,然后暴力枚举$a$,判断${n^2} - {a^2}$是否为平方数,如果是,那么就找到解了。

这样的方法看似会超时,实际上居然能$AC$......然后我把后半部分$n$作为斜边的删了,也照样能$AC$。

然后我就开始思考$n$作为直角边时候有什么规律在....后来发现了。

我们再来观察$n$作为直角边时候的答案:$c = \frac{{A + B}}{2}$,$b = \frac{{A - B}}{2}$。

如果${n^2}$是奇数,那么我们假设$B=1$,$A={n^2}$,这样构造就能保证$c$和$b$都是整数啦。

如果${n^2}$是偶数,那么我们假设$B=2$,$A = \frac{{{n^2}}}{2}$,这样构造也能保证$c$和$b$都是整数。

也就是说一开始写的暴力方法,在枚举到$B=2$的时候就找到解了,因此能过......

#pragma comment(linker, "/STACK:1024000000,1024000000")#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<vector>#include<map>#include<set>#include<queue>#include<stack>#include<iostream>using namespace std;typedef long long LL;const double pi=acos(-1.0),eps=1e-8;void File(){    freopen("D:\\in.txt","r",stdin);    freopen("D:\\out.txt","w",stdout);}LL n,ans1,ans2;int main(){    scanf("%lld",&n);    if(n==1||n==2) printf("-1\n");    else    {        if(n*n%2==1) ans1=(n*n+1)/2, ans2=(n*n-1)/2;        else ans1=(n*n/2+2)/2, ans2=((n*n/2-2))/2;        printf("%lld %lld\n",ans1,ans2);    }    return 0;}

 

CodeForces 707C Pythagorean Triples