简答题
偏难
#7491
红色警报 战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来…
红色警报
战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的k个区域,而失去一个城市并不改变其他城市之间的连通性,则不要发出警报。
时间限制:5000
内存限制:65536
输入
输入在第一行给出两个整数 N(0 < N <=500)和 M(<=5000),分别为城市个数(于是默认城市从 0 到 N-1 编号)和连接两城市的通路条数。随后 M 行,每行给出一条通路所连接的两个城市的编号,其间以 1 个空格分隔。在城市信息之后给出被攻占的信息,即一个正整数 K 和随后的 K 个被攻占的城市的编号。 注意:输入保证给出的被攻占的城市编号都是合法的且无重复,但并不保证给出的通路没有重复。
输出
对每个被攻占的城市,如果它会改变整个国家的连通性,则输出“Red Alert: City k is lost!”,其中k是该城市的编号;否则只输出“City k is lost.”即可。如果该国失去了最后一个城市,则增加一行输出“Game Over.”。
样例输入
5 4 0 1 1 3 3 0 0 4 5 1 2 0 4 3
样例输出
City 1 is lost. City 2 is lost. Red Alert: City 0 is lost! City 4 is lost. City 3 is lost.
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">//参考代码1
#include<cstdio>
#include<cstring>
using namespace std;
int pre[505];
bool del[505];
struct node{
int x,y;
}p[5005];
int find(int x){
return x==pre[x]?x:pre[x]=find(pre[x]);
}
void merge(int x,int y){
int fx = find(x);
int fy = find(y);
if(fx!=fy)
pre[fx] = fy;
}
int main(){
int n,m,k,x;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
pre[i]=i;
for(int i=1;i<=m;i++){
scanf("%d%d",&p[i].x,&p[i].y);
merge(p[i].x,p[i].y);
}
int ans=0;
for(int i=0;i<n;i++){
if(i==pre[i]) ans++;
}
scanf("%d",&k);
while(k--){
scanf("%d",&x);
del[x]=true;
for(int i=0;i<n;i++)
pre[i]=i;
for(int i=1;i<=m;i++){
if(!del[p[i].x]&&!del[p[i].y])
merge(p[i].x,p[i].y);
}
int cnt=0;
for(int i=0;i<n;i++)
{
if(pre[i]==i&&!del[i])
cnt++;
}
if(cnt>ans)
printf("Red Alert: City %d is lost!\n",x);
else
printf("City %d is lost.\n",x);
ans=cnt;
if(ans==0)
printf("Game Over.\n");
}
return 0;
}</pre><pre class="brush:cpp;toolbar:false">//参考代码2
#include<bits/stdc++.h>
using namespace std;
#define N 510
#define M 5010
int n ,m ,k ,vis[N] ,p[N];
struct node {
int x;
int y;
}g[M];
int find(int x) {
if (x != p[x]) p[x] = find(p[x]);
return p[x];
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++)
p[i] = i;
for (int i = 0; i < m; i++) {
cin >> g[i].x >> g[i].y;
if (find(g[i].x) != find(g[i].y))
p[find(g[i].x)] = find(g[i].y);
}
int cnt1 = 0;
for (int i = 0; i < n; i++) {
if (p[i] == i)
cnt1 ++;
}
cin >> k;
for (int j = 0; j < k; j++) {
int x ,cnt2 = 0;
cin >> x;
vis[x] = 1;
for (int i =0 ; i < n; i++)
p[i] = i;
for (int i = 0; i < m; i++) {
if (vis[g[i].x] == 1 ||vis[g[i].y] == 1)
continue;
if (find(g[i].x) != find(g[i].y))
p[find(g[i].x)] = find(g[i].y);
}
for (int i = 0; i < n; i++) {
if (p[i] == i)
cnt2++;
}
if (cnt2 - cnt1 > 1)
printf ("Red Alert: City %d is lost!\n" ,x);
else
printf ("City %d is lost.\n" ,x);
cnt1 = cnt2;
}
if (k >= n) cout << "Game Over.\n";
return 0;
}</pre>
这道题暂未补解析。