L2-013 红色警报 (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.

分析
每次删去一个点,可以用一个数组记录标记被删去的点,每删去一个点,对所有不包含被删去点的边求一次并查集,检查有几个集合,如果比之前多则说明有国家被分裂了,注意已经被消灭的城市不会算入一个集合。

代码

#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e4 + 10;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
typedef pair<int, int> PII;
int fa[maxn], book[maxn];
PII e[maxn];
int f(int x) { return fa[x] == x ? x : fa[x] = f(fa[x]); }
int cal(int m, int n) {
    for (int i = 0; i < n; i++) fa[i] = i;
    for (int i = 0; i < m; i++) {
        if (book[e[i].first] != 1 && book[e[i].second] != 1) {
            int x = f(e[i].first), y = f(e[i].second);
            fa[x] = y;
        }
    }
    int res = 0;
    for (int i = 0; i < n; i++) {
        if (fa[i] == i && book[i] != 1) res++;
    }
    return res;
}

int main(int argc, char const *argv[]) {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < m; i++) cin >> e[i].first >> e[i].second;
    int k;
    cin >> k;
    int now, past = cal(m, n);
    for (int i = 1; i <= k; i++) {
        int x;
        cin >> x;
        book[x] = 1;
        now = cal(m, n);
        if (now > past) {
            printf("Red Alert: City %d is lost!\n", x);
        } else {
            printf("City %d is lost.\n", x);
        }
        past = now;
        if (n - i == 0) puts("Game Over.");
    }
    return 0;
}

暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇