CF1927F Microcycle

环的权值为边权最小值,可以想到从大到小遍历权值,如果一条边加入后出现了环说明这条边的边权就是整个环的权值。

类似 Kruskal,我们把边权从大到小排序,然后用并查集维护连通情况,算出最小的权值。然后跑 dfs 找环输出方案。时间复杂度 O(mlogm+n)

#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 7;

int read() {
    char c = getchar();
    int x = 0, p = 1;
    while ((c < '0' || c > '9') && c != '-') c = getchar();
    if (c == '-') p = -1, c = getchar();
    while (c >= '0' && c <= '9')
        x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    return x * p;
}

int n, m;
vector <int> to[N];

struct Edge {
	int u, v, w;
	bool operator < (const Edge p) const {
		return w > p.w;
	}
} t[N];

struct DSU {
	int fa[N];
	void init() {
		for (int i = 1; i <= n; i ++) fa[i] = i;
	}
	int find(int x) {
		return x == fa[x] ? x : (fa[x] = find(fa[x]));
	}
	void merge(int i, int j) {
		int x = find(i), y = find(j);
		fa[x] = y;
	}
} D;

bool vis[N];
stack <int> st;
bool flg;

void dfs(int u, int p, int res) {
	vis[u] = 1; st.push(u);
	if (u == p) {
		flg = 1; cout << res << ' ' << (int) st.size() << '\n';
		while (!st.empty()) {
			cout << st.top() << ' ';
			st.pop();
		}
		cout << '\n';
		return ;
	}
	for (int v : to[u]) {
		if (!vis[v]) {
			dfs(v, p, res);
			if (flg) return ;
		}
	}
	st.pop();
}

void solve() {
	n = read(), m = read();
	for (int i = 1; i <= n; i ++)
		to[i].clear();
	for (int i = 1; i <= m; i ++)
		t[i].u = read(), t[i].v = read(), t[i].w = read();
	sort(t + 1, t + m + 1); D.init();
	long long ans = 2e18; flg = 0;
	for (int i = 1; i <= m; i ++) {
		int u = t[i].u, v = t[i].v, w = t[i].w;
		if (D.find(u) != D.find(v)) {
			D.merge(u, v);
		} else {
			ans = i;
		}
	}
	fill(vis + 1, vis + n + 1, 0);
	for (int i = 1; i < ans; i ++) {
		to[t[i].u].push_back(t[i].v);
		to[t[i].v].push_back(t[i].u);
	}
	dfs(t[ans].u, t[ans].v, t[ans].w);
}

signed main() {
	int t = read();
	while (t --) solve();
	return 0;
}

作者:DE_aemmprty

出处:https://www.cnblogs.com/aemmprty/p/18090519

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   DE_aemmprty  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示