2017百度之星资格赛 1002 度度熊的王国战略(并查集 or 无向图最小割)

本文介绍使用并查集解决无向图最小割问题的方法,并对比Stoer-Wagner算法,通过实例代码展示了如何利用并查集进行点权和记录及连通性判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击打开链接

题意很容易理解,基本上这个题意就是让你去考虑无向图的最小割,无奈只会用模版,还没想好怎么用堆或者斐波那契堆优化Stoer-Wagner算法,TLE......而且百度把这题的时间放宽到了2000ms,这样还超时,不会优化真尴尬......SW算法用堆优化一般适用于稀疏图,如果是稠密图,优化还可能更费时,看此题的数据,点的个数取值为3 * 10^3,边的个数为10^5,应该是稀疏图的测试超了时。

而用了并查集 + 记录点的权和,用并查集判断是否是连通图,如果不连通,直接输出0,如果连通,输出最小权和,即把权和最小的点分割出来,竟然对了......一开始也想了并查集,写了一点感觉不靠谱才换的SW,没想到此题这么坑。不过有时间还是得学会优化SW算法。

// 度度熊的王国战略2.cpp  运行/限制:140ms/2000ms
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int n, m, fa[3005], sum[3005];
int get(int x) {
	return fa[x] = fa[x] == x ? x : get(fa[x]);
}
void merge(int x, int y) {
	int a = get(x);
	int b = get(y);
	if (a != b) {
		fa[b] = a;
	}
}
void init() {
	for (int i = 1; i <= n; i++) {
		fa[i] = i;
	}
}
int main(){
	int a, b, c, cnt;
	while (scanf("%d%d", &n, &m) != EOF) {
		init();
		cnt = n - 1;
		memset(sum, 0, sizeof(sum));
		for (int i = 0; i < m; i++) {
			scanf("%d%d%d", &a, &b, &c);
			if (a == b) continue;
			sum[a] += c;
			sum[b] += c;
			int x = get(a);
			int y = get(b);
			if (x != y) {
				merge(x, y);
				cnt--;
			}
		}
		if (cnt) {
			printf("0\n");
		}
		else{
			sort(sum + 1, sum + n + 1);
			printf("%d\n", sum[1]);
		}
	}
    return 0;
}

// 度度熊的王国战略.cpp Time Limit Exceeded
#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define INF 0X3f3f3f3f
int vis[3005];
int wet[3005];
int combine[3005];
int map[3005][3005];
int S, T, minCut, N, M;
void Search() {
	int i, j, Max, tmp;
	memset(vis, 0, sizeof(vis));
	memset(wet, 0, sizeof(wet));
	S = T = -1;
	for (i = 1; i <= N; i++) {
		Max = -INF;
		for (j = 1; j <= N; j++) {
			if (!combine[j] && !vis[j] && wet[j] > Max) {
				tmp = j;
				Max = wet[j];
			}
		}
		if (T == tmp) return;
		S = T; T = tmp;
		minCut = Max;
		vis[tmp] = 1;
		for (j = 1; j <= N; j++) {
			if (!combine[j] && !vis[j]) {
				wet[j] += map[tmp][j];
			}
		}
	}
}
int Stoer_Wagner() {
	int i, j;
	memset(combine, 0, sizeof(combine));
	int ans = INF;
	for (i = 1; i < N; i++) {
		Search();
		if (minCut < ans) ans = minCut;
		if (ans == 0) return 0;
		combine[T] = 1;
		for (j = 1; j <= N; j++) {
			if (!combine[j]) {
				map[S][j] += map[T][j];
				map[j][S] += map[j][T];
			}
		}
	}
	return ans;
}
int main() {
	int a, b, c;
	while (scanf("%d%d", &N, &M) != EOF) {
		memset(map, 0, sizeof(map));
		while (M--) {
			scanf("%d%d%d", &a, &b, &c);
			map[a][b] += c;
			map[b][a] += c;
		}
		printf("%d\n", Stoer_Wagner());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值