【数据结构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;
		}
	}
}
相关推荐
糖炒栗子03261 小时前
【笔记】高分卫星影像 TIF 切片处理
笔记
Nice_Fold2 小时前
Kubernetes DaemonSet、StatefulSet与Service(自用笔记)
笔记·容器·kubernetes
_深海凉_3 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
旖-旎3 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰3 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx4 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer4 小时前
【无标题】
开发语言·c++·算法
AGV算法笔记4 小时前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉
ZhiqianXia4 小时前
《The Design of Design》阅读笔记
前端·笔记·microsoft
祁白_5 小时前
nmap工具笔记整理
笔记·web安全·测试