Array K-Coloring:
题目大意:(文末有原题)
给出n个整数,用k种颜色给这n个整数着色,要求:
1. 每个整数都有一种颜色;
2. 每种颜色至少要涂一个整数;
3. 每种颜色不能为相同的整数着色;
判断能否为每一个整数都着色;
思路:
首先判断是否能够实现;
不能实现的条件:
存在有x个相同整数,并且x > k;(因为k个颜色,每个颜色不能涂相同的整数,如果x>k,代表会有x-k个该整数没法着色)
如果能实现就进行下列操作:
因为要每个颜色至少要涂一个整数,则先遍历,让每个颜色都先涂一个整数,并且保存已经涂过的整数的值;
之后从第一个(i = 0)颜色开始遍历,每一次再对剩下还没着色的数遍历,如果这个颜色之前没有涂过这个整数,就用这一种颜色涂它,否则跳过;
直到所有的数都被着色;
代码:
#include <iostream> #include <cstring> #include <vector> #include <map> using namespace std; const int maxn = 1e4 + 10; int a[maxn], ans[maxn]; int main() { int n, k, sum = 0, max = -100; cin >> n >> k; map<int, int> m; vector<int> vis[maxn]; memset(ans, 0, sizeof(ans)); for(int i = 0; i < n; i++) { cin >> a[i]; m[a[i]]++; //用来统计一个整数的数量 if(m[a[i]] > max) { max = m[a[i]]; } } if(max > k) cout << "NO" << endl; }else { cout << "YES" << endl; for(int i = 0; i < k; i++) { vis[i].push_back(a[i]); //用来记录用颜色i涂过的整数 ans[i] = i + 1; } for(int j = 0; j < k; j++) { if(j >= k) j -= k; for(int i = k; i < n; i++) { if(!ans[i]) { int d = 0; for(int l = 0; l < vis[j].size(); l++) { if(a[i] == vis[j][l]) { d = 1; break; } } if(d) continue; ans[i] = j + 1; vis[j].push_back(a[i]); sum++; } } if(sum + k >= n) break; } for(int i = 0; i < n; i++) { if(i == n - 1) cout << ans[i] << endl; else cout << ans[i] << " "; } } return 0; }
原题:
题目:
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.
输入:
The first line of the input contains two integers n and k (1≤k≤n≤5000 ) — the length of the array aa and the number of colors, respectively.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤5000) — elements of the array a .
输出:
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.
样例:
Input:
4 2
1 2 2 3Output:
YES
1 1 2 2
Input:5 2
3 2 1 2 3Output:
YES
2 1 1 2 1Input:
5 2
2 1 1 2 1Output:
NO
本文探讨了Array K-Coloring问题,旨在通过k种颜色对n个整数进行着色,确保每种颜色至少使用一次且同一颜色不重复用于相同数值。文章详细阐述了解决方案的思路与步骤,包括条件判断、颜色分配策略及代码实现。
1327

被折叠的 条评论
为什么被折叠?



