Minimum Cut POJ - 2914(无向图最小割)

Minimum Cut POJ - 2914

Given an undirected graph, in which two vertices can be connected by multiple edges, what is the size of the minimum cut of the graph? i.e. how many edges must be removed at least to disconnect the graph into two subgraphs?

Input
Input contains multiple test cases. Each test case starts with two integers N and M (2 ≤ N ≤ 500, 0 ≤ M ≤ N × (N − 1) ⁄ 2) in one line, where N is the number of vertices. Following are M lines, each line contains M integers A, B and C (0 ≤ A, B < N, A ≠ B, C > 0), meaning that there C edges connecting vertices A and B.

Output
There is only one line for each test case, which contains the size of the minimum cut of the graph. If the graph is disconnected, print 0.
Sample Input
3 3
0 1 1
1 2 1
2 0 1
4 3
0 1 1
1 2 1
2 3 1
8 14
0 1 1
0 2 1
0 3 1
1 2 1
1 3 1
2 3 1
4 5 1
4 6 1
4 7 1
5 6 1
5 7 1
6 7 1
4 0 1
7 3
Sample Output
2
1
2
题意:
求无向图最小割

题解:
使用Stoer-Wagner算法
1.min=MAXINT,固定一个顶点P
2.从点P用“类似”prim的s算法扩展出“最大生成树”,记录最后扩展的顶点和最后扩展的边
3.计算最后扩展到的顶点的切割值(即与此顶点相连的所有边权和),若比min小更新min
4.合并最后扩展的那条边的两个端点为一个顶点(当然他们的边也要合并,这个好理解吧?)
5.转到2,合并N-1次后结束
6.min即为所求,输出min
 prim本身复杂度是O(n ^ 2),合并n-1次,算法复杂度即为O(n ^ 3),如果在prim中加堆优化,复杂度会降为O((n ^ 2)logn)
 
代码详解:https://www.hankcs.com/program/algorithm/poj-2914-minimum-cut.html

#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAX_N = 505;
const int INF = 0x3f3f3f3f;
int G[MAX_N][MAX_N];
int v[MAX_N];
int w[MAX_N];
bool visited[MAX_N];

int stoer_wagner(int n) {
	int min_cut = INF;
	for (int i = 0; i < n; i++)	{
		v[i] = i;
	}
	while (n > 1) {
		int pre = 0;
		memset(visited, 0, sizeof(visited));
		memset(w, 0, sizeof(w));
		for (int i = 1; i < n; i++)	{
			int k = -1;
			for (int j = 1; j < n; j++)	{
				if (!visited[v[j]]) {
					w[v[j]] += G[v[pre]][v[j]];
					if (k == -1 || w[v[k]] < w[v[j]]) {
						k = j;
					}
				}
			}

			visited[v[k]] = true;
			if (i == n - 1)	{
				const int s = v[pre], t = v[k];
				min_cut = min(min_cut, w[t]);
				for (int j = 0; j < n; j++)	{
					G[s][v[j]] += G[v[j]][t];
					G[v[j]][s] += G[v[j]][t];
				}
				v[k] = v[--n];
			}
			pre = k;
		}
	}
	return min_cut;
}

int main(){
	int n, m;
	while (scanf("%d%d", &n, &m) != EOF) {
		memset(G, 0, sizeof(G));
		while (m--)	{
			int u, v, w;
			scanf("%d%d%d", &u, &v, &w);
			G[u][v] += w;
			G[v][u] += w;
		}
		printf("%d\n", stoer_wagner(n));
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值