Cube Number
2000 ms 65536 KiBAccepted/Submissions: 3/38 (7.89%)
Description
In mathematics, a cube number is an integer that is the cube of an integer. In other words, it is the product of some integer with itself twice. For example, 27 is a cube number, since it can be written as 3 * 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 cube number.
Input
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).
Output
For each test case, you should output the answer of each case.
Sample
Input
1
5
1 2 3 4 9
Output
2
求n个数中两两相乘等于立方数的情况有多少种。
首先看示例,1 2 3 4 9,能配对的有(3,9),(2,4),分析每一对数的特点,容易发现9可以分解成3*3,再去*3就是3的立方27,而4可以分解成2*2,再去*2就是2的立方8,延伸一下,就是将所有数都分解质因数,如果找到搭配的,并且其质因数个数和是3的倍数的话,就可以配对。
然后,问题变成了找到质因数以后怎么去找匹配数的个数,再来观察一组数,18和12,18可以分解成3,3,2,12可以分解成2,2,3。找18需要匹配的数,首先18有两个2,还需要一个,18有一个3,还需要两个,因为是分解的质因数,所以不会存在a*b==c*d的情况,所以可以直接计算18匹配所需要的数就是12,然后再记录它对总数的贡献,也就是18。12的方法类似,这样就可以找到18,而18提前计算,所以不会存在重复查找的情况。
注意输入long long类型的数据会超时,需要int输入。
代码实现:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e6+5;
bool vis[maxn];
int ans[maxn],prim[maxn],cnt=0;
void init()
{
int i,j,k;
vis[2]=0;vis[1]=0;
for(i=2;i*i<maxn;i++)
{
if(!vis[i])
{
prim[cnt++]=i;
for(j=i*i;j<=maxn;j+=i)
vis[j]=1;
}
}
}
int main()
{
int i,j,k,t,n;
init();
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(ans,0,sizeof(ans));
ll sum=0;
int x;
for(i=0;i<n;i++)
{
ll a=1,b=1; //a记录x中剩余质因数积,b记录与x剩余质因数互补的质因数积
int flag=0;
scanf("%d",&x);
for(j=0;prim[j]<=x&&j<cnt;j++)
{
ll temp=prim[j]*prim[j]*prim[j];
while(x%temp==0)
{
x/=temp;
}
if(x%(prim[j]*prim[j])==0)
{
x=x/(prim[j]*prim[j]);
a=a*prim[j]*prim[j];
b=b*prim[j];
}
else if(x%prim[j]==0)
{
x=x/(prim[j]);
a=a*prim[j];
b=b*prim[j]*prim[j];
}
if(b>maxn)
flag=1;
}
if(!flag)
{
b=b*x*x;
if(b<maxn)
sum+=ans[b];
}
a=a*x;
ans[a]++;
}
printf("%lld\n",sum);
}
}