Codeforces Beta Round #92 (Div. 1 Only) A. Prime Permutation 暴力
A. Prime Permutation
题目连接:
http://www.codeforces.com/contest/123/problem/A
Description
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 sp = sp × 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".
Sample Input
abc
Sample Output
YES
abc
Hint
题意
给你一个字符串,然后n是这个字符串的长度。
你可以重排,然后要求满足s[p] = s[ip],p是一个小于等于n的素数。
问你行不行。
题解:
这道题唯一的问题就是,2和3这种素数,他们的公因数是6,他们俩所需要的字母就应该是一样的
数据范围看了一下,才1000,所以直接暴力就好了
其实数据范围是100000也可以做,直接拿个并查集,把一些公因数存在的数直接缩在一起就好了
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1200;
vector<int> p;
int n;
string s;
int vis[maxn];
int ans[maxn];
int num[30];
int getpri()
{
for(int i=2;i<=n;i++)
{
if(vis[i])continue;
p.push_back(i);
for(int j=i;j<=n;j+=i)
vis[j]=1;
}
}
int main()
{
cin>>s;
n=s.size();
getpri();
for(int i=0;i<s.size();i++)
num[s[i]-'a']++;
for(int i=0;i<=n;i++)
ans[i]=-1;
for(int i=0;i<p.size();i++)
{
int k = -1,t = -1;
for(int j=1;j<=n;j++)
if(j%p[i]==0&&ans[j]!=-1)t=ans[j];
if(t==-1)
{
for(int j=0;j<26;j++)
if(num[j]>k)k=num[j],t=j;
}
for(int j=p[i];j<=n;j+=p[i])
{
if(ans[j]!=-1)continue;
if(num[t]==0)return puts("NO"),0;
ans[j]=t;
num[t]--;
}
}
for(int i=0;i<26;i++)
if(num[i]>0)ans[1]=i;
cout<<"YES"<<endl;
for(int i=1;i<=n;i++)
printf("%c",ans[i]+'a');
printf("\n");
}