Array K-Coloring
You are given an array aa consisting of nn integer numbers.
You have to color this array in kk colors in such a way that:
- Each element of the array should be colored in some color;
- For each ii from 11 to kk there should be at least one element colored in the ii-th color in the array;
- For each ii from 11 to kk all elements colored in the ii-th color should be distinct.
Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c1,c2,…cnc1,c2,…cn, where 1≤ci≤k1≤ci≤k and cici is the color of the ii-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
Input
The first line of the input contains two integers nn and kk (1≤k≤n≤50001≤k≤n≤5000) — the length of the array aa and the number of colors, respectively.
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤50001≤ai≤5000) — elements of the array aa.
Output
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c1,c2,…cnc1,c2,…cn, where 1≤ci≤k1≤ci≤k and cici is the color of the ii-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
4 2 1 2 2 3
YES 1 1 2 2
5 2 3 2 1 2 3
YES 2 1 1 2 1
5 2 2 1 1 2 1
NO
Note
In the first example the answer 2 1 2 12 1 2 1 is also acceptable.
In the second example the answer 1 1 1 2 21 1 1 2 2 is also acceptable.
There exist other acceptable answers for both examples.
思路:必须k种颜色每种都得用至少一次(这需要优先考虑),然后每种颜色所上的元素必须不同(也就是相同元素不能涂一样的颜色,这就需要标记元素出现的最大次数了,如果最大次数大于k,则一定不符合题意。
代码:
#include<cstdio> #include<iostream> #include<cstring> using namespace std; bool vis1[5050][5050]; //二维数组标记该元素(一维)是否使用过该种颜色(二维) bool vis2[5050]; //标记该颜色是否被使用过 int cnt[5050]; //计算相同元素出现的个数 int main() { int n,k; while(cin>>n>>k) { memset(vis1,0,sizeof(vis1)); memset(vis2,0,sizeof(vis2)); memset(cnt,0,sizeof(cnt)); int a[5050],ans[5050]; //a为输入元素,ans为输出颜色(这里的两个数组后面都为其赋值了,所以不用初始化) int flag=0; for(int i=1;i<=n;i++) { cin>>a[i]; cnt[a[i]]++; if(cnt[a[i]]>k) //如果相同元素的个数超过所给颜色种类数,必定NO(题目要求) flag=1; } if(flag) { cout<<"NO"<<endl; continue; } int use=0; //标记使用过的颜色数 for(int i=1;i<=n;i++) { for(int j=1;j<=k;j++) { if(!vis1[a[i]][j]&&!vis2[j]&&use<k) { vis1[a[i]][j]=1; vis2[j]=1; ans[i]=j; use++; break; } if(use==k&&!vis1[a[i]][j]) { vis1[a[i]][j]=1; ans[i]=j; break; } } } cout<<"YES"<<endl; for(int i=1;i<=n;i++) { if(i==n) cout<<ans[i]<<endl; else cout<<ans[i]<<" "; } } return 0; }