算法训练营|图论第6天 108.冗余连接 109.冗余连接2

题目:108.冗余连接

题目链接:

108. 冗余连接 (kamacoder.com)

代码:

cpp 复制代码
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
vector<int>father;
int find(int u) {
	if (father[u] == u) {
		return u;
	}
	else {
		return father[u] = find(father[u]);
	}
}
void join(int u, int v) {
	u = find(u);
	v = find(v);
	if (u == v) return;
	father[v] = u;
}
bool isSame(int u, int v) {
	u = find(u);
	v = find(v);
	return u == v;
}
int main() {
	int n;
	cin >> n;
	father = vector<int>(n + 1);
	for (int i = 0; i <= n; i++) father[i] = i;
	for (int i = 0; i < n; i++) {
		int s, t;
		cin >> s >> t;
		if (isSame(s, t)) {
			cout << s << ' ' << t << endl;
		}
		else {
			join(s, t);
		}
	}

}

题目:109.冗余连接2

题目链接:

109. 冗余连接II (kamacoder.com)

代码:

cpp 复制代码
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int n;
vector<int>father;
void init() {
	for (int i = 0; i <= n; i++) {
		father[i] = i;
	}
}
int find(int u) {
	if (u == father[u]) return u;
	else {
		return father[u] = find(father[u]);
	}
}
void join(int u, int v) {
	u = find(u);
	v = find(v);
	if (u == v) return;
	father[v] = u;
}
bool isSame(int u, int v) {
	u = find(u);
	v = find(v);
	return u == v;
}
bool isTree(const vector<vector<int>>& edges, int deleteEdge) {
	init(); // 初始化并查集
	for (int i = 0; i < n; i++) {
		if (i == deleteEdge) continue;
		if (isSame(edges[i][0], edges[i][1])) { // 构成有向环了,一定不是树
			return false;
		}
		join(edges[i][0], edges[i][1]);
	}
	return true;
}
void getRemoveEdge(vector<vector<int>>& edges) {
	init();
	for (int i = 0; i < n; i++) {
		if (isSame(edges[i][0], edges[i][1])) {
			cout << edges[i][0] << " " << edges[i][1] << endl;
		}
		else {
			join(edges[i][0], edges[i][1]);
		}
	}
}

int main() {
	cin >> n;
	father = vector<int>(n + 1, 0);
	int s, t;
	vector<vector<int>>edges;
	vector<int>inDegree(n + 1, 0);//记录入度
	for (int i = 0; i < n; i++) {
		cin >> s >> t;
		edges.push_back({ s,t });
		inDegree[t]++;
	}
	vector<int>vec;//记录入度为2的边
	for (int i = n - 1; i >= 0; i--) {
		if (inDegree[edges[i][1]] == 2) {
			vec.push_back(i);
		}
	}
	if (vec.size() > 0) {
		//非环形
		if (isTree(edges, vec[0])) {
			cout << edges[vec[0]][0] << " " << edges[vec[0]][1];
			return 0;
		}
		else {
			cout << edges[vec[1]][0] << " " << edges[vec[1]][1];
			return 0;
		}
	}
	getRemoveEdge(edges);
}
相关推荐
老师我太想进步了20266 小时前
【数据结构-15】实现链式结构二叉树
c语言·数据结构
liulilittle6 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
xiangxueCode8 小时前
数据结构:容器适配器之优先级队列
数据结构·优先级队列
鱼很腾apoc9 小时前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习
郝学胜-神的一滴9 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu1 天前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗1 天前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
路灯中转站1 天前
数据结构C语言版(什么是数据类型)
数据结构