题解:P11701 [ROIR 2025] 平方差

· · 题解

0x00 题意简述

给定 (d,l,r),使得对于 (x,y)(x,y \in \Nu ),l \le y^2 < x^2 \le r,且 x^2 - y^2 = d。

0x01 分析

注意到 d = x^2 - y^2,因式分解得 d = (x+y) \times (x-y)。所以我们枚举 d 的每个因数,对于每个因数 i:

\begin{cases} x+y=d \div i \\ x - y = i \end{cases}

依据:

\because i \le d \div i$ 且 $x,y \in \Nu \therefore x-y \le x+y \therefore x+y=d \div i,x-y=i

此时只要验证 x,y \in \Nu 和 l \le y^2 < x^2 \le r 即可。

0x02 代码

#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
inline void read(int &z){
    int x=0,w=1;
    char ch=0;
    while(ch<'0'||ch>'9'){
        if(ch=='-')w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=x*10+ch-'0';
        ch=getchar();
    }
    z=x*w;
}
int d,l,r;
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>d>>l>>r;
    int ans=0;
    for(int i=1;i*i<=d;i++){
        if(d%i==0){//每个因数
            int x=i,y=d/i;
            if((x+y)%2)continue;//x,y属于自然数
            int xx=x+y>>1;
            int yy=y-xx;
            if(l<=yy*yy&&xx*xx<=r)ans++;//边界条件
        }
    }
    cout<<ans;
    return 0;
}

0x03 时间复杂度

显然,枚举每个因数的复杂度为 \Theta (\sqrt d),单次操作为 \Theta (1),总复杂度 \Theta (\sqrt d)。