Description
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 1
Sample Output
2 1 2
//
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 551;
const int MAXV = 0x3F3F3F3F;
int n,m,v[MAXN],mat[MAXN][MAXN],dis[MAXN];
bool vis[MAXN];
int res;
int Stoer_Wagner(int n) {
int res = MAXV;
for (int i = 0;i < n;i++)
v[i] = i;
while (n > 1) {
int maxp = 1,prev = 0;
for (int i = 1;i < n;i++) {//初始化到已圈集合的割大小
dis[v[i]] = mat[v[0]][v[i]];
if (dis[v[i]] > dis[v[maxp]])
maxp = i;
}
memset(vis,0,sizeof(vis));
vis[v[0]] = true;
for (int i = 1;i < n;i++) {
if (i == n - 1) { //只剩最后一个没加入集合的点,更新最小割
res = min(res,dis[v[maxp]]);
for (int j = 0; j < n; j++) { //合并最后一个点以及推出它的集合中的点
mat[v[prev]][v[j]] += mat[v[j]][v[maxp]];
mat[v[j]][v[prev]] = mat[v[prev]][v[j]];
}
v[maxp] = v[--n];//缩点后的图
}
vis[v[maxp]] = true;
prev = maxp;
maxp = -1;
for (int j = 1;j < n;j++)
if (!vis[v[j]]) { //将上次求的maxp加入集合,合并与它相邻的边到割集
dis[v[j]] += mat[v[prev]][v[j]];
if (maxp == -1 || dis[v[maxp]] < dis[v[j]])
maxp = j;
}
}
}
return res;
}
int main()
{
int m;
while (scanf("%d%d", &n,&m) != EOF)
{
memset(mat,0,sizeof (mat));
int x,y,z;
int i,j;
while(m--)
{
int u,v,w;scanf("%d%d%d",&u,&v,&w);
mat[u][v]+=w,mat[v][u]+=w;//+=
}
printf("%d\n",Stoer_Wagner(n));
}
}