SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square.
Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.
SaMer wishes to create more cases from the test case he already has. His test case has an array AA of nn integers, and he needs to find the number of contiguous subarrays of AA that have an answer to the problem equal to kk for each integer kk between 11 and nn (inclusive).
The first line of input contains a single integer nn (1≤n≤50001≤n≤5000), the size of the array.
The second line contains nn integers a1a1,a2a2,……,anan (−108≤ai≤108−108≤ai≤108), the values of the array.
Output nn space-separated integers, the kk-th integer should be the number of contiguous subarrays of AA that have an answer to the problem equal to kk.
2 5 5
3 0
5 5 -4 2 1 8
5 5 3 2 0
1 0
1
题意:
已知有这么一道题:给你n个数字,你要将这n个数字打乱后分成k组,使得对于同一个组中的任意一对数字满足两个数相乘一定是个完全平方数,求出最小的k
而这道题的意思是:给你n个数字,这n个数字一共有(1+n)*n/2个连续子序列,对于连续每个子序列你都要求出上面的那个k,最后统计k=1的子序列有多少个,k=2的子序列有多少个……k=n的子序列有多少个
思路:
对于x(x!=0),如果存在一个y满足x是y²的倍数,那么将x变为x/y²不会影响答案
这样的话对于每个a[i],暴力所有平方数,如果整除就除掉,最后得到的a[i]必定满足 a[i] = ∏pj,其中pj各不相同且都为质数
结论:这样处理完之后,满足任意两个数相乘都为平方数的组内所有数字必定都相同,换句话说,只有相同的两个数相乘才能是个完全平方数,否则一定不是
这样这题就简单了:给你n个数字,这n个数字一共有(1+n)*n/2个连续子序列,对于每个连续子序列有多少个互不相同的数字,那么k就为多少
离散化或者map(map会超时……)暴力统计一下就ok了,复杂度O(n²)或O(n²logn)
当然要特判0!0乘任意一个数字都是0,所以0可以加入任何一个组中
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int cnt, a[5005], p[5005], ans[5005];
int main(void)
{
int n, i, j, now, id;
scanf("%d", &n);
for(i=1;i<=n;i++)
scanf("%d", &a[i]);
for(i=1;i<=n;i++)
{
if(a[i]==0)
continue;
for(j=2;j<=10000;j++)
{
while(a[i]%(j*j)==0)
a[i] /= j*j;
}
}
for(i=1;i<=n;i++)
p[i] = a[i];
sort(p+1, p+n+1);
cnt = unique(p+1, p+n+1)-(p+1);
for(i=1;i<=n;i++)
a[i] = lower_bound(p+1, p+cnt+1, a[i])-p;
id = lower_bound(p+1, p+cnt+1, 0)-p;
if(p[id])
id = -1000;
now = 0;
for(i=1;i<=n;i++)
{
now = 0;
memset(p, 0, sizeof(p));
for(j=i;j<=n;j++)
{
if(a[j]!=id && p[a[j]]==0)
now++;
p[a[j]] = 1;
ans[max(now, 1)]++;
}
}
for(i=1;i<=n;i++)
printf("%d ", ans[i]);
puts("");
return 0;
}