PAT甲级 1154 Vertex Coloring
参考代码by:柳婼
https://blog.csdn.net/liuchuo/article/details/84973030
A proper vertex coloring is a labeling of the graph’s vertices with colors such that no two vertices sharing the same edge have the same color. A coloring using at most k colors is called a (proper) k-coloring.
Now you are supposed to tell if a given coloring is a proper k-coloring.
Sample Input:
10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
4
0 1 0 1 4 1 0 1 3 0
0 1 0 1 4 1 0 1 0 0
8 1 0 1 4 1 0 5 3 0
1 2 3 4 5 6 7 8 8 9
Sample Output:
4-coloring
No
6-coloring
No
题意:根据输入输出看,其实k-coloring 的k指的是最后那4行染色方案中,每种方案所含的颜色数目,比如方案1含4种(0/1/3/4)、方案2含3种(0/1/4)、方案3含6种(0/1/3/4/5/8)、方案4含9种(1/2/3/4/5/6/7/8/9)。
*而满足k-coloring的条件是:*由10个点彼此连线构成的11条边87、68、45……每条边的两个端点颜色均不相同。
*比如方案1:*87对应颜色是31、68对应30、45对应14……(注意点的编号从0开始,10个点是0123456789)没有重复颜色的点,即满足k-coloring,输出该方案含有的k(也就是4)种颜色。
*比如方案2:*98对应的是00,不满足颜色不同,输出NO
而方案4刚开始的87就对应颜色88,也是NO
接下来是柳神的代码,我只是写了个自己方便理解的注释
#include <iostream>
#include <vector>
#include <set>
using namespace std;
struct node {int t1, t2;};
int main() {
int n, m, k;
//题目给的大写K就是为了搞心态的,让人误以为和k-coloring的k有关,其实无关
cin >> n >> m;
vector<node> v(m);
//由于vector动态数组不用定义大小,而下面的array[i]就必须满足题上的10的4次方条件了
for (int i = 0; i < m; i++)
scanf("%d %d", &v[i].t1, &v[i].t2);//
cin >> k;
while (k--) {
int a[10009] = {0};//array数组是要初始化的,vector不用
bool flag = true;
set<int> se;//set集合特点是不含相同元素,正好适合从颜色方案中筛选颜色种类
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
//记录下颜色方案中所有的颜色,i=0对应了题目中点N从0开始计数
se.insert(a[i]);
}
for (int i = 0; i < m; i++) {
if (a[v[i].t1] == a[v[i].t2]) {
//判断边的两点颜色是否相同
flag = false;
break;
//break只能跳出一层循环,即从判断颜色的for循环跳出到while的大循环
}
}
if (flag) //跳出后立马检测flag的值
printf("%d-coloring\n", se.size());
else
printf("No\n");
}
return 0;
}
感悟:
- pat好多题目中最离谱的变量往往是解题的key point ,比如本题的大K看起来很奇怪,但恰恰是while大循环的临界值,感觉是姥姥的友情提示。
- 布尔变量在输出结果类型迥异的时候很好用,比如本题一会输出统计值k,一会又直接输出NO
- 出现多输入值筛选输入元素的种类时,比如本题从10个染色点找用了几种颜色,用set集合的不含相同元素的特性很好解决。
- 边循环边输出的思路虽然不是单一出口,但很容易理解,写起来也更顺畅。