Codeforces Round #480 (Div. 2): D. Perfect Groups(思维题)

本文介绍了一种算法,用于解决将整数数组按特定条件(任意两数乘积为完全平方数)分组的问题,并统计不同分组数量的连续子序列数目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

time limit per test  1 second
memory limit per test  256 megabytes
input  standard input
output  standard output

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).

Input

The first line of input contains a single integer nn (1n50001≤n≤5000), the size of the array.

The second line contains nn integers a1a1,a2a2,,anan (108ai108−108≤ai≤108), the values of the array.

Output

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.

Examples
input
2
5 5
output
3 0
input
5
5 -4 2 1 8
output
5 5 3 2 0
input
1
0
output
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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值