CodeForces - 1102B(Array K-Coloring(给数字涂颜色))

B. Array K-Coloring
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a consisting of n integer numbers.
You have to color this array in k colors in such a way that:
Each element of the array should be colored in some color;
For each i from 1 to k there should be at least one element colored in the i-th color in the array;
For each i from 1 to k all elements colored in the i-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,…cn, where 1≤ci≤k and ci is the color of the i-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 n and k (1≤k≤n≤5000) — the length of the array a and the number of colors, respectively.
【CodeForces - 1102B(Array K-Coloring(给数字涂颜色))】The second line of the input contains n integers a1,a2,…,an (1≤ai≤5000) — elements of the array a.
Output
If there is no answer, print “NO”. Otherwise print “YES” and any coloring (i.e. numbers c1,c2,…cn, where 1≤ci≤k and ci is the color of the i-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
Examples
inputCopy
4 2
1 2 2 3
outputCopy
YES
1 1 2 2
inputCopy
5 2
3 2 1 2 3
outputCopy
YES
2 1 1 2 1
inputCopy
5 2
2 1 1 2 1
outputCopy
NO
Note
In the first example the answer 2 1 2 1 is also acceptable.
In the second example the answer 1 1 1 2 2 is also acceptable.
There exist other acceptable answers for both examples.
题意:给n个数字、k种颜色,要求你给每个数字涂色,但是每种颜色中数字不能相同,并且颜色都要用完,当满足条件时,就输出YES以及涂的颜色,否则输出NO
思路:
1、题目要求每种颜色的数字不能相同,那么我们就可以先判断,如果一个数字出现的次数已经大于颜色的种类,那么必然不能满足条件
2、然后我们再满足条件颜色都要用完这个条件,只要n>k那么上面这个条件就可以满足
3、我们可能需要一个二维数组来记录每种颜色中的数字都有哪些,通过这个数组,我们就可以让接下来n-k个数字完成涂色
代码如下

#include #include #include #include #include #define MAX_SIZE 5010 using namespace std; //a用来存储数字,sum记录数字出现次数,ans记录每个数字所涂的颜色 int a[MAX_SIZE],sum[MAX_SIZE],ans[MAX_SIZE]; bool vis[MAX_SIZE][MAX_SIZE]; //这里使用bool的数组为了节省空间int main() { int i,j,k,n,temp; scanf("%d %d",&n,&k); for(i = 0; i < n; i++) scanf("%d",&a[i]); //判断一个数字出现的次数 for(i = 0; i < n; i++) sum[a[i]]++; for(i = 0; i <= 5000; i++) { if(sum[i] > k) { printf("NO\n"); return 0; } } //判断数字个数和颜色种类 if(k > n) { printf("NO\n"); return 0; }int pos = 1; for(i = 0; i < n; i++) { //先将每种颜色都使用 if(pos <= k) { ans[i] = pos; vis[pos][a[i]] = 1; pos++; } else { //之后寻找那种颜色没有数字a[i],那么就将数字a[i]涂为j的颜色 for(j = 1; j <= k; j++) { if(vis[j][a[i]] == 0) { ans[i] = j; vis[j][a[i]] = 1; break; } } } } printf("YES\n"); for(i = 0; i < n; i++) printf("%d ",ans[i]); return 0; }

    推荐阅读