L2-013 红色警报

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.

并查集,每次攻占城市后都重新建立并查集

#include <cstring>
#include <iostream>
using namespace std;
static const auto io_sync_off = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

// 思路是每次攻占一个城市后重新建立并查集,孤立的条件是一个点的根节点是自己
const int maxn = 505;
int f[maxn];                     //父亲节点
bool lost[maxn];                 //记录是否被占领
pair<int, int> point[maxn * 10]; //记录道路信息

void init(int n)
{
    for (int i = 0; i < n; ++i)
        f[i] = i;
}

int find(int x)
{
    return f[x] == x ? x : f[x] = find(f[x]);
}

void merge(int x, int y)
{
    f[find(y)] = find(x);
}

int main()
{
    int n, m;
    cin >> n >> m;
    init(n);
    memset(lost, false, sizeof(lost));
    for (int i = 0; i < m; ++i)
    {
        cin >> point[i].first >> point[i].second;
        merge(point[i].first, point[i].second); //合并结点
    }

    int pre = 0; //初始状态下的孤立点和主城市点(根节点),样例数据中的2和0
    for (int i = 0; i < n; ++i)
        if (f[i] == i)
            ++pre;

    int k, city; //询问数,被攻占的城市号
    cin >> k;
    for (int t = 0; t < k; ++t)
    {
        cin >> city;
        lost[city] = true;
        init(n);                    //有一座城市被攻占,重新建立并查集
        for (int i = 0; i < m; ++i) //两个城市都没被占领的情况下,压缩
            if (!lost[point[i].first] && !lost[point[i].second])
                merge(point[i].first, point[i].second);

        int now = 0;      //占领一座城市后的孤立点或主城市结点(根节点)的个数
        for (int i = 0; i < n; ++i)
            if (!lost[i] && f[i] == i) ++now;    //同样要求不能被占领
        
        //不会改变连通性的两种情况:1:孤立点被占领;2:叶节点城市被占领。
        //比如第一次2号城市被占领,1号城市被占领
        if (now + 1 == pre || now == pre)                   
            cout << "City " << city << " is lost." << endl; 
        else
            cout << "Red Alert: City " << city << " is lost!" << endl;
        pre = now; //更新数量
    }

    if (k == n)
        cout << "Game Over." << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/88990039