Advanced Lab 6-3.1 Red Alert (25 points)

Solution: Whenever a city is captured, delete all neighbors of the city, and lost[city]==true to indicate that the city has been occupied, calculate the number of connected components in the ListComponents() function Skip this city when. Therefore, if the number of connected components after city deletion is greater than the number of connected components before deletion, it means that the city is a hub, otherwise it is a normal city.

Error-prone points: 1. Every time the ListComponents() function is executed, the vis[] array must be reset to false. 2. When K==N, output Game Over at the end!

Supplement: There are two ways to count the number of connected sets in an undirected graph: 1. Use union search set. 2. Graph traversal. My solution is the DFS of the graph

Here is the code:

#include<stdio.h>
#define MAXV 505
#define INF 65535
#include<algorithm>
using namespace std;
int n,G[MAXV][MAXV];
bool lost[MAXV]= {false};
bool vis[MAXV] = { false };
void DFS(int v)
{
	int w;
	vis[v] = true;
	for(w=0; w<n; w++)
		if(vis[w]==false&&G[v][w]==1)
			DFS(w);
}
int ListComponents()
{
	int v; int count = 0;
	for(v=0; v<n; v++)
	{
		if(vis[v]==false&&lost[v]==false) //对于被占领的城市直接跳过
		{
			count++;
			DFS(v);
		}
	}
	return count;
}
int main()
{
	int i,j; int v;
	int N,M,K; int v1,v2;
	scanf("%d %d",&N,&M);
	n = N;
	for(i=0; i<n; i++)
		for(j=0; j<n; j++)
			G[i][j] = INF;
	for(i=0; i<M; i++)
	{
		scanf("%d %d",&v1,&v2);
		G[v1][v2] = 1;
		G[v2][v1] = 1;
	}
	scanf("%d",&K);
	int city;int start,end;
	for(i=0; i<K; i++)
	{
		scanf("%d",&city);
		lost[city] = true;
		fill(vis,vis+n,false);
		start = ListComponents(); 
		for(v=0; v<n; v++)//切断city与其他城市的联系
		{
			if(G[city][v]!=INF)
			{
				G[city][v] = INF;
				G[v][city] = INF;
			}
		}
		fill(vis,vis+n,false);
		end = ListComponents(); 
		if(start == end)
			printf("City %d is lost.\n",city);
		else if(start < end)
			printf("Red Alert: City %d is lost!\n",city);
	}
	if(K==N)	
	{printf("Game Over.\n");}
	return 0;
}






 

Guess you like

Origin blog.csdn.net/yiwaite/article/details/100185224