【数据结构OJ】【图论】红色警报

题目描述

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

IO模式

本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。

输入样例:

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.

直接套用计算连通分量的函数,如果增加了就是出现问题了,不要忘记在这个城市被攻陷后它本身就是一个独立的节点,不应该被计算在里面,所以connect函数要-1

cpp 复制代码
#include <iostream>
#include <vector>
using namespace std;
void dfs(int node, int n, int **matrix, vector<bool> &visited) {
	visited[node] = true;

	for (int i = 0; i < n; i++) {
		if (matrix[node][i] == 1 && !visited[i]) {
			dfs(i, n, matrix, visited);
		}
	}
}
int connect(int **a, int n) {
	int ans = 0;
	vector<bool> visited(n, false);
	for (int i = 0; i < n; i++) {

		if (!visited[i]) {
			dfs(i, n, a, visited);
			ans++;
		}
	}
	return ans;
}
int main() {
	int n, m;
	cin >> n >> m;
	int **a = new int *[n];

	for (int i = 0; i < n; i++) {
		a[i] = new int[n];
	}

	for (int i = 0; i < n; i++) {

		for (int j = 0; j < n; j++) {
			a[i][j] = 0;
		}
	}
	int tag1, tag2;

	for (int i = 0; i < m; i++) {
		cin >> tag1 >> tag2;
		a[tag1][tag2] = 1;
		a[tag2][tag1] = 1;
	}
	int t;
	int captured;
	cin >> t;
	int c = connect(a, n);
	for (int i = 0; i < t; i++) {
		cin >> captured;

		for (int k = 0; k < n; k++) {
			a[captured][k] = 0;
			a[k][captured] = 0;
		}

		if ((connect(a, n) - 1 ) > c) {
			c = connect(a, n);
			cout << "Red Alert: " << "City " << captured << " is lost!" << endl;

		} else {
			cout << "City " << captured << " is lost." << endl;
		}

		if (i == t - 1) {
			cout << "Game Over." << endl;
		}
	}
}
相关推荐
kebidaixu11 分钟前
两轮BMS 短路保护策略详解
算法
zwenqiyu28 分钟前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
z小猫不吃鱼30 分钟前
03 Optimal Brain Surgeon 详解:Hessian 剪枝为什么有效?
算法·机器学习·剪枝
硕风和炜1 小时前
【LeetCode: 1301. 最大得分的路径数目 + DP】
java·算法·leetcode·动态规划·dp·记忆化搜索
用户99045017780091 小时前
做了一个AI诊断,参考倪海厦中医理论,科学养生
算法
努力中的编程者1 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
东华万里1 小时前
第32篇 数据结构入门 单链表的增删查改实现
数据结构·链表
weixin_400005602 小时前
RL-frenet-trajectory-planning-in-CARLA
人工智能·深度学习·算法·机器学习·自动驾驶
Keven_112 小时前
AcWing算法提高课思路速查:动态规划
算法·动态规划
剑挑星河月2 小时前
94.二叉树的中序遍历
java·算法·leetcode