并查集和dfs都可以,注意时当苏搜有程序都失去时才输出”Game Over.“。
#include <bits/stdc++.h>
using namespace std;
int n, m, cnt;
int maps[510][510];
bool vis2[510], vis[510];
void dfs(int u) {
for(int i = 0; i<n; ++i) {
if(!vis2[i]&&maps[u][i]&&!vis[i]) {
vis[i] = 1;
dfs(i);
}
}
}
int main() {
scanf("%d%d", &n, &m);
int u, v;
memset(maps, 0, sizeof(maps));
for(int i = 0; i<m; ++i) {
scanf("%d%d", &u, &v);
maps[u][v] = maps[v][u] = 1;
}
memset(vis2, 0, sizeof(vis2));
int nn;
scanf("%d", &nn);
for(int ii = 1; ii<=nn; ++ii) {
scanf("%d", &u);
cnt = 0;
memset(vis, 0, sizeof(vis));
for(int i = 0; i<n; ++i)
if(!vis2[i]&&!vis[i]) {
vis[i] = 1;
dfs(i);
cnt--;
}
// printf("cnt = %d ", cnt);
memset(vis, 0, sizeof(vis));
vis2[u] = 1;
for(int i = 0; i<n; ++i)
if(!vis2[i]&&!vis[i]) {
vis[i] =1;
dfs(i);
cnt++;
}
// printf("%d \n", cnt);
if(cnt>=1)printf("Red Alert: City %d is lost!\n", u);
else printf("City %d is lost.\n", u);
}
if(nn==n)printf("Game Over.\n");
return 0;
}