7-7 红色警报 (25分)
战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的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.
题目大意:
先给一个无向图,然后给几个点,表示要攻占的地方,如果攻占之后影响了城市的连通性,则有红色警报,反之则没有。最后一个城市被攻占之后要输出“Game Over.”。
解题思路:
攻占前后记录两次连通块的数量,如果攻占后数量大于攻占前数量,说明城市被攻占影响了图的连通性。
代码:
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
//#include <tr1/unordered_map>
#include <bits/stdc++.h>
#include <cmath>
//#include <unordered_map>
using namespace std;
#define sfd(i) scanf("%d", &i)
#define sfl(i) scanf("%I64d", &i)
#define sfs(i) scanf("%s", (i))
#define prd(i) printf("%d\n", i)
#define prl(i) printf("%I64d\n", i)
#define sff(i) scanf("%lf", &i)
#define ll long long
#define ull unsigned long long
#define uint unsigned int
#define mst(x, y) memset(x, y, sizeof(x))
#define INF 0x3f3f3f3f
#define eps 1e-10
// const int maxn = 3e5;
#define PI acos(-1.0)
#define lowbit(x) ((x) & (-x))
#define fl() printf("flag\n")
#define MOD(x) ((x % mod) + mod) % mod
#define endl '\n'
#define pb push_back
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define FAST_IO \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
//-----------------------------------------------
int N, M;
int map[505][505] = {0};
int book[505] = {0};
int gongzhan[505] = {0};
void dfs(int city) {
book[city] = 1;
for (int i = 0; i < N; i++) {
if (!book[i] && map[city][i] == 1 && !gongzhan[city]) {
book[i] = 1;
dfs(i);
}
}
}
int num() {
int count = 0;
for (int i = 0; i < N; i++) {
if (book[i] == 0 && gongzhan[i] == 0) {
dfs(i);
count++;
}
}
return count;
}
int main() {
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
map[a][b] = map[b][a] = 1;
}
int K;
cin >> K;
for (int i = 0; i < K; i++) {
int city;
cin >> city;
for (int i = 0; i < N; i++) {
book[i] = 0;
}
int pre = num();
gongzhan[city] = 1;
for (int i = 0; i < N; i++) {
book[i] = 0;
}
int after = num();
if (after > pre) {
printf("Red Alert: City %d is lost!\n", city);
} else {
printf("City %d is lost.\n", city);
}
// game over结束标志
int flag = 0;
for (int j = 0; j < N; j++) {
if (gongzhan[j] == 0) {
flag = 1;
}
}
if (flag == 0) {
cout << "Game Over." << endl;
break;
}
}
}