http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=3258
Square Number
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
In mathematics, a square number is an integer that is the square of an integer. In other words, it is the product of some integer with itself. For example, 9 is a square number, since it can be written as 3 * 3.
Given an array of distinct integers (a1, a2, ..., an), you need to find the number of pairs (ai, aj) that satisfy (ai * aj) is a square number.
输入
The first line of the input contains an integer T (1 ≤ T ≤ 20) which means the number of test cases.
Then T lines follow, each line starts with a number N (1 ≤ N ≤ 100000), then N integers followed (all the integers are between 1 and 1000000).
输出
For each test case, you should output the answer of each case.
示例输入
1 5 1 2 3 4 12
示例输出
2
题意:输入一组数,查找其中任意两个(不重复)乘积为平方数的个数。(例题答案:1*4;3*12).
理解:预处理素数,但是需要注意的是题目范围是1e6,意味着素数只需要1000以内的(否则会超时),原因很简单,如果一个数的最小质因数都大于1000,那么这个数就超过题目的范围了。所以预处理只要处理1~1000的素数就可以了。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int p[200];
bool prime[1005];
int k=0;
void isprime()
{
int i,j;
memset(prime,true,sizeof(prime));
for(i=2;i<=1000;i++)
{
if(prime[i])
{
p[k++]=i;
for(j=i*i;j<=1000;j+=i)
{
prime[j]=false;
}
}
}
}
int test(int n)
{
int flag=1;
for(int i=0;i<k;i++)
{
while(!(n%(p[i]*p[i])))
{
n/=p[i]*p[i];
}
}
return n;
}
int main()
{
int t,shu;
long long ans;
isprime();
scanf("%d",&t);
while(t--)
{
int n;
ans=0;
map<int,int> m1;
map<int,int>::iterator i_it;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&shu);
int x=test(shu);
// ans-=1LL*m1[x]*(m1[x]-1)/2;
m1[x]++;
// ans+=1LL*m1[x]*(m1[x]-1)/2;
}
for(i_it=m1.begin();i_it!=m1.end();i_it++)
ans+=1LL*i_it->second*(i_it->second-1)/2;
printf("%lld\n",ans);
}
return 0;
}