用并查集做,真是牛逼!!
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m;
typedef struct
{
int v, u;
} Edge;
Edge edge[N * 10];
int father[N];
int find(int x)
{
int a = x;
while (x != father[x])
{
x = father[x];
}
while (a != x)
{
int tmp = father[a];
father[a] = x;
a = tmp;
}
return x;
}
void Union(int a, int b)
{
int fa = find(a);
int fb = find(b);
if (fa != fb)
{
father[fa] = fb;
}
}
bool vis[N];
int main(void)
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
father[i] = i;
}
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d %d", &a, &b);
edge[i] = {a, b};
Union(a, b);
}
int oricnt = 0;
for (int i = 0; i < n; i++)
{
if (father[i] == i)
{
oricnt++;
}
}
int k;
cin >> k;
while (k--)
{
int x;
cin >> x;
int nowcnt = 0;
for (int i = 0; i < n; i++)
{
father[i] = i;
}
vis[x] = true;
for (int i = 0; i < m; i++)
{
if (!vis[edge[i].u] && !vis[edge[i].v])
{
Union(edge[i].u, edge[i].v);
}
}
for (int i = 0; i < n; i++)
{
if (father[i] == i)
{
nowcnt++;
}
}
if (oricnt == nowcnt || nowcnt - 1 == oricnt)
{
printf("City %d is lost.\n", x);
}
else
{
printf("Red Alert: City %d is lost!\n", x);
}
oricnt = nowcnt;
}
int flag = true;
for(int i = 0; i < n; i++){
if(!vis[i])flag = false;
}
if(flag){
cout << "Game Over." << endl;
}
return 0;
}