codeforces 124C Prime Permutation(并查集+思维)

题目:
You are given a string s, consisting of small Latin letters. Let’s denote the length of the string as |s|. The characters in the string are numbered starting from 1.Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled s p = s p × i. If the answer is positive, find one way to rearrange the characters.
Input
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
Output
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line “YES” (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string “NO”.

标题

题意就是要让素数位置以及它的倍数上的字母都是一样的。比如2,4,6,8,10……这样子,然后我们把字符串中的最大字母的数量还有它是哪个字母算出来,然后再遍历一遍字符串,如果不是最大数量的字母,我们就把它存到vector中,随时备用。

然后呢,我们要把有相同素因子的素数都用并查集并在一起;比如这里的6就就是由2和3两个素因子合成的,所以导致2和3的倍数都应该在一组中,应该用相同的字母来表示。

如下图

在这里插入图片描述

具体代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;
int fa[maxn];
int vis[maxn];
int g[maxn];
int get(int x)//路径压缩
{
	return fa[x]==x?x:(fa[x]=get(fa[x]));
}
void add(int x,int y)//合并
{
	int i=get(x);
	int j=get(y);
	if(i==j)return;
	fa[i]=j;
}
bool f(int x)//判断是否素数
{
	for(int i=2;i<=sqrt(x);i++)
	{
		if(x%i==0)return false;
	}
	return true;
}
int main()
{
	vector<int>v;
	char s[maxn];
	int a[30];
	memset(a,0,sizeof a);
	scanf("%s",s);
	int len=strlen(s);
	for(int i=0;i<len;i++)a[s[i]-'a'+1]++;//把每个字母的数量算出来
	int maxx=0;
    int pa=0;
	int ans=0;
	for(int i=1;i<=26;i++)//找到数量最多的字母以及是哪个字母
	{
		if(a[i]>maxx)
		{
			maxx=a[i];
			pa=i;
		}
	}
	for(int i=1;i<=len;i++)fa[i]=i;
	for(int i=0;i<len;i++)
	{
		if(s[i]-'a'+1!=pa)v.push_back(s[i]-'a'+1);
		//不是所需要的字母的话,就放到vector中备用
	}
	for(int i=2;i<=len;i++)
	{
		if(f(i))
		{
			for(int j=i;j<=len;j+=i)
				add(i,j);
		}//把有相同素因子的位置都并在一起
	}
	for(int i=2;i<=len;i++)
	{
		if(get(i)==fa[2])
		{
			g[i]++;//表示i这个位置是组中的一员
			ans++;//计算出有多少个并在一起的数字
		}
	}
	if(ans>maxx)puts("NO");
	//如果一组中的数量大于求得的最大字母的数量,
	//就无法让这些位置上有相同字母,直接输出NO;
	else
	{	
		int j=0;
		puts("YES");
		for(int i=0;i<len;i++)
		{
			if(g[i+1])//如果是族中的一员,就用最大数量的字母表示
				printf("%c",pa+96);
			else //否则就用vector存下空闲的字母来填这个空 
			{	
				if(j>=v.size())
					printf("%c",pa+96);
				else 
					printf("%c",v[j++]+96);
			}	
		}	
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值