题目链接:点击查看
题目大意:给出一个正整数 n ,求满足条件 ( i , j , k ) 的三元组的数量,其中需要满足:
- sqrt( i ) + sqrt ( j ) = sqrt( k )
- i * j <= n
n 的范围是 4e7
题目分析:比赛的时候只想到了nsqrt(n)的枚举方案,还是怪我太弱了,其实先要对原式进行化简,两边同时平方得到:
这样一来只需要枚举 i * j就好了,满足 i * j 为完全平方数,且 i 和 j 都是正整数,可以两层循环解决,外面一层枚举每个完全平方数,时间复杂度为 sqrt( n ),内部的循环枚举每个完全平方数的因子个数,时间复杂度同为 sqrt( n ),套起来就是O(n)了,因为(i,j,k)和(j,i,k)为两种答案,所以每次遇到可以整除的因子时贡献累加 2 ,最后别忘了特判一下 i == j 的情况就好了
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=2e5+100;
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
//#endif
// ios::sync_with_stdio(false);
int n;
scanf("%d",&n);
int ans=0;
for(int i=1;i*i<=n;i++)//枚举完全平方数
{
for(int j=1;j*j<i*i;j++)//枚举完全平方数的因子
if((i*i)%j==0)
ans+=2;
ans++;
}
printf("%d\n",ans);
return 0;
}