Codeforces 1102B Array K-Coloring 思维

题意:给出n个元素的数组和k个颜色,要求将所有元素都涂色,且相同元素的颜色不同,且要使用所有颜色。

思路,将所有元素的位置使用vector保存,对所有元素一种接着一,种从1开始到k循环着色。着色完按照顺序输出即可。

AC代码:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>pos[5005];
int col[5005];//各个元素着色
int main()
{
	ios::sync_with_stdio(0);
	int n, m, tmp;
	cin >> n >> m;
	bool flag = false;
	for (int i = 0; i < n; ++i)
	{
		cin >> tmp;
		pos[tmp].push_back(i);
		if (pos[tmp].size() > m)
			flag = true;//相同元素多于k个,k种颜色已经不可能着色
	}
	if (flag)
		return cout << "NO" << endl, 0;
	cout << "YES" << endl;
	int i = 0, j = 1, k = 0;
        //i遍历数组,j是颜色,k是从1开始每一种元素的位置的vector数组的下标
	while (i < n)
	{
		for (int l = 0; i < n&&l < pos[k].size(); ++l, ++i, ++j)
		{
			col[pos[k][l]] = j;
			if (j == m)
				j = 0;//j++之后就会是1,这个是坑
		}
		++k;
	}
	for (int i = 0; i < n; ++i)
	{
		cout << col[i];
		if (i < n - 1)
			cout << " ";
		else
			cout << endl;
	}
	return 0;
}
​

猜你喜欢

转载自blog.csdn.net/Aya_Uchida/article/details/86767154