穿越隧道

AC代码
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int h[N],e[N],ne[N],idx;
int v,m,k;
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int fa[N];
int find(int x){
if(x != fa[x]){
fa[x] = find(fa[x]);
}
return fa[x];
}
int color[N];
map<int,int> mp;
bool st[N];
int q[N*10];
bool bfs(int u){
int hh = 0, tt = 0;
q[0] = u;
st[u] = true;
while(hh <= tt){
int t = q[hh++];
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(color[t] == color[j]){
return false;
}
if(!st[j]){
q[++tt] = j;
st[j] = true;
}
}
}
return true;
}
int main(){
cin >> v >> m >> k;
for(int i = 1; i <= v; i++){
fa[i] = i;
}
memset(h,-1,sizeof(h));
while(m--){
int a,b;
cin >> a >> b;
add(a,b),add(b,a);
fa[a] = b;
}
int n;
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= v; j++){
cin >> color[j];
mp[color[j]]++;
}
if(mp.size() != k){
puts("No");
}
else{
int flag = 1;
for(int j = 1; j <= v; j++){
if(fa[j] == j && flag){
memset(st,0,sizeof(st));
if(!bfs(j)){
flag = 0;
break;
}
}
else{
continue;
}
}
if(!flag){
puts("No");
}
else{
puts("Yes");
}
}
mp.clear();
}
return 0;
}
23分
UPD:破案了,颜色的数量一定要等于k,其余都是No,(缺失的两分);
bfs判断相邻的两个结点颜色是否相同,若相同,则No;
并查集来判断v个点中,有多少个联通块。
对每个连通块进行bfs.
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int h[N],e[N],ne[N],idx;
int v,m,k;
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int fa[N];
int find(int x){
if(x != fa[x]){
fa[x] = find(fa[x]);
}
return fa[x];
}
int color[N];
map<int,int> mp;
bool st[N];
int q[N*10];
bool bfs(int u){
int hh = 0, tt = 0;
q[0] = u;
st[u] = true;
while(hh <= tt){
int t = q[hh++];
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(color[t] == color[j]){
return false;
}
if(!st[j]){
q[++tt] = j;
st[j] = true;
}
}
}
return true;
}
int main(){
cin >> v >> m >> k;
for(int i = 1; i <= v; i++){
fa[i] = i;
}
memset(h,-1,sizeof(h));
while(m--){
int a,b;
cin >> a >> b;
add(a,b),add(b,a);
fa[a] = b;
}
int n;
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= v; j++){
cin >> color[j];
mp[color[j]]++;
}
if(mp.size() > k){
puts("No");
}
else{
int flag = 1;
for(int j = 1; j <= v; j++){
if(fa[j] == j && flag){
memset(st,0,sizeof(st));
if(!bfs(j)){
flag = 0;
break;
}
}
else{
continue;
}
}
if(!flag){
puts("No");
}
else{
puts("Yes");
}
}
mp.clear();
}
return 0;
}