您的位置:首页 > 编程语言 > C语言/C++

山东省第六届ACM大学生程序设计竞赛-Square Number(完全平方数)

2016-05-23 17:18 471 查看

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


提示

 

来源

 

示例程序

题目意思:

有一些数据,两个为一组,两两相乘为完全平方数的有多少组?

解题思路:

一个完全平方数可以分解成偶数个素数相乘。

由↑这个思路,我们可以先打一个素数表,然后遍历素数表。

设一个数m为使得m与这个数相乘是一个完全平方数的数,算出这个数能被素数prm[j]整除的次数,如果是奇数次就乘到m上;把遍历最后剩下的数也乘到m上去。

这个素数表很重要哇,选不好效率高的素数表就要TLE啦~
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 1000010
int a[MAXN],vis[MAXN];
long long ans;
bool is[MAXN];//用来求素数
int prm[MAXN];//用来保存素数
int totleprm=0;//记录素数总个数

void getprm()//打素数表
{
int i,j,m;
memset(is,0,sizeof(is));
is[1]=1;
m=sqrt(MAXN);
for(i=2; i<=m; i++)
if(!is[i])
for(j=i*i; j<MAXN; j+=i)
is[j] = 1;
for(i=2; i<MAXN; i++)
if(!is[i])
prm[totleprm++]=i;
}

int main()
{
int t;
getprm();//素数打表
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
int n,i,j;
ans=0;
cin>>n;
for(i=0; i<n; i++)
{
cin>>a[i];//输入数据
int m=1;//保存应当再乘的数
for(j=0; j<totleprm; j++)//遍历素数表
{
int acnt=0;//保存数a[i]能被素数prm[j]整除的次数
while(a[i]%prm[j] == 0)
{
a[i]/= prm[j];
++acnt;
}
if(acnt%2) m*=prm[j];//如果整除的次数为奇数,就把这个素数乘上
if(!is[a[i]]||a[i]==1)//a[i]==1这句不加会超时……
{
m*=a[i];//如果除到最后是个素数,把剩的这个数也乘上
break;
}
}
ans+=vis[m];
++vis[m];//记录应当再乘的数的出现次数,观察在其整个数据序列中出现的次数
}
cout<<ans<<endl;
}
return 0;
}
/*
1 5 1 2 3 4 12
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息