Ladder match practice --7-37 Red Alert (25 points) (disjoint-set)

topic:

Here Insert Picture Description

analysis:

The use of disjoint-set problem is solved by determining the removal of one of the city connectivity before and after the draw if an alert
before and after each capture a city, find the root of the number ans, captured the city, marking the city, then the city of unlabeled disjoint-set to do it again, a root node is determined at this time a total cnt, if cnt is equal to ANS, described at this time so that no damage city connectivity change occurs, if cnt <ans description, at this ruined city is an isolated city, it will not alarm, in cnt> ans description destroyed the original connectivity, we need to sound the alarm.

Code:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int MAXN = 505;
int root[MAXN],n,m,k,ans;
bool vis[MAXN];

struct node
{
    int x,y;
}no[5005];

int getr(int x)
{
    if(root[x] == x) return x;
    else return root[x] = getr(root[x]);
}

void Union(int x,int y)
{
    int xx = getr(x);
    int yy = getr(y);
    if(xx != yy)
        root[xx] = yy;
}

int main()
{
    int city;
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;++i)
        root[i] = i;
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",&no[i].x,&no[i].y);
        Union(no[i].x,no[i].y);
    }
    for(int i=0;i<n;++i)
        if(root[i]==i) ans++;
    scanf("%d",&k);
    while(k--)
    {
        int cnt = 0;
        scanf("%d",&city);
        vis[city] = true;
        for(int i=0;i<n;++i)
            root[i] = i;
        for(int i=1;i<=m;++i)
            if(!vis[no[i].x] && !vis[no[i].y])
                Union(no[i].x,no[i].y);
        for(int i=0;i<n;++i)
            if(!vis[i]&&root[i]==i) cnt++;
        if(cnt <= ans)
            printf("City %d is lost.\n",city);
        else
            printf("Red Alert: City %d is lost!\n",city);
        ans = cnt;
        if(ans == 0)
        {
            printf("Game Over.\n");
            return 0;
        }
    }
    return 0;
}

Published 61 original articles · won praise 7 · views 3614

Guess you like

Origin blog.csdn.net/weixin_42469716/article/details/105275157