L2-013. 红色警报
战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的k个区域,而失去一个城市并不改变其他城市之间的连通性,则不要发出警报。
输入格式:
输入在第一行给出两个整数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. Game Over.
分析:题意问我们,如果把一个国家的某一个城市攻占了,会不会改变整个国家的连通性。我们首先想到的是图的连通性,要判断图的连通性,我们首先肯定要构建邻接矩阵arr[520][520],然后根据图的深度优先搜索统计图的连通分量cnt,把与被攻占的城市相连的所有道路都标记为0,然后再统计城市被攻占后的图的连通分量tempcnt.如果tempcnt > cnt + 1,图的连通性就发生改变。因为一个城市被攻占了,也就说明这个城市被孤立了。如果tempcnt <= cnt + 1,就说明连通性没有被改变。
没有被攻占时的邻接矩阵:cnt = 2
1号城市被攻占后:tempcnt = 3
0号城市被攻占后:tempcnt = 5;
当3和4被攻占后,tempcnt = 5,连通性不变。
看了柳神的博客https://blog.csdn.net/liuchuo/article/details/52302443,自己理解写下分析,并自己再敲了一遍。其实这道题还可以用并查集来做。
AC代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool visit[520]; //标记是否被访问过
int arr[520][520]; //用来表示邻接矩阵
int n,m,k;
void dfs(int key){ //图的深度优先搜索
visit[key] = true;
for(int i = 0; i < n; i++){
if(visit[i] == false && arr[key][i] == 1)
dfs(i);
}
}
int connect_cnt(){
int cnt = 0;
memset(visit,false,sizeof(visit));
for(int i = 0; i < n; i++){
if(visit[i] == false){
dfs(i);
cnt++;
}
}
return cnt;
}
int main()
{
int i,j,x,y;
while(cin >> n >> m){
for(i = 0; i < m; i++){
cin >> x >> y;
arr[x][y] = 1;
arr[y][x] = 1;
}
int cnt = connect_cnt();
int city;
cin >> k;
for(i = 0; i < k; i++){
cin >> city;
for(j = 0; j < n; j++){ //把被孤立城市的道路在矩阵中清0
if(arr[city][j] == 1){
arr[city][j] = 0;
arr[j][city] = 0;
}
}
int tempcnt = connect_cnt();
if(tempcnt > cnt + 1){
printf("Red Alert: City %d is lost!\n", city);
}else{
printf("City %d is lost.\n", city);
}
cnt = tempcnt; //传递上一次的连通分量的值
}
if(k==n)
cout<<"Game Over."<<endl;
}
return 0;
}