【数据结构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;
		}
	}
}
相关推荐
专注仿真2 小时前
ACM算法
算法·深度优先
code斗3 小时前
Java数据结构:堆详解
java·开发语言·数据结构
顺顺 尼4 小时前
linux 进程信号(上)
linux·c++·算法
罗西的思考4 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(5)--- GRPO
人工智能·算法·机器学习
richard_yuu5 小时前
动态规划:强化学习的「数学基础」,从 MDP 到值迭代
深度学习·神经网络·算法·yolo·机器学习·动态规划
mmmmath_35 小时前
LeetCode.225.用队列实现栈
算法
Elaine3365 小时前
数据结构与算法-程序
数据结构·python·算法·计算机基础·编程基础
2601_965742225 小时前
布局GEO AI本地营销,我重点看这几个细节
大数据·人工智能·算法·ai·新媒体运营
EatFan5 小时前
AI Agent 上生产前先加三道闸门:审批、限权、可回放的工程实践
人工智能·python·算法·多智能体·ai agent·mcp·harness
思茂信息5 小时前
CST软件BCI仿真模型及仿真案例
开发语言·单片机·嵌入式硬件·算法·emc