L2-013 红色警报【并查集】

                                                     L2-013 红色警报 

                      https://pintia.cn/problem-sets/994805046380707840/problems/994805063963230208

 

 

 

题目

战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的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.

分析

并查集的使用。

C++程序

#include
#include

using namespace std;

const int N=510;

int pre[N];
bool flag[N];

//初始化 
void init(int n)
{
	for(int i=0;i<=n;i++)
	  pre[i]=i;
}

//查找函数,查找x的祖先结点 
int find(int x)
{
	int r=x;
	while(r!=pre[r]) r=pre[r];
	//路径压缩 
	while(x!=r)
	{
		int i=pre[x];
		pre[x]=r;
		x=i;
	}
	return r;
}

//将x和y结点连接在一起 
void join(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy) pre[fx]=fy;
}

//计算连通度 
int degree(int n)
{
	int cnt=0;
	for(int i=0;iv; 

int main()
{
	int n,m,k;
	scanf("%d%d",&n,&m);
	init(n);
	for(int i=0;icount)//如果连通度变大了 
		{
			printf("Red Alert: City %d is lost!\n",v[i]);
			count=count2;
		}
		else//如果连通度没变 
		  printf("City %d is lost.\n",v[i]);
		if(count!=count2) count=count2;
		if(--num<=0) printf("Game Over.\n");//如果删除的结点到达了总数 
	}
	return 0;
}

 

你可能感兴趣的:(数据结构)