Time Limit: 10000MS | Memory Limit: 65536K | |
Total Submissions: 3610 | Accepted: 1340 | |
Case Time Limit: 5000MS |
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
Source
#include<cstdio>
#include<cstring>
#define NN 510 //Maximum number of vertices in the graph
#define MAXW 250010// Maximum edge weight
int g[NN][NN],belongs[NN],w[NN],na[NN];
bool vis[NN];
int minCut(int n)
{
for(int i=0;i<n;i++) belongs[i]=i;
int best=0x7fffffff;
while(n>1)//若|V|!=1则继续
{
vis[belongs[0]]=true;
for(int i=1;i<n;i++)
{
vis[belongs[i]]=false;
na[i-1]=i;
w[i]=g[belongs[0]][belongs[i]];
}//设最小割cut=INF,任选一个点s到集合A中,定义W(A, p)为A中的所有点到A外一点p的权总和.
int prev=belongs[0];
for(int i=1;i<n;i++)
{
int zj=-1;
for(int j=1;j<n;j++)
if(!vis[belongs[j]]&&(zj<0 || w[j]>w[zj])) zj=j;
//选出A外一点p, 且W(A,p)最大的作为新的s, 若A!=G(V), 则继续
vis[belongs[zj]] = true;
if(i==n-1)
{
if(best>w[zj]) best=w[zj];
for(int i=0;i<n;i++)
g[belongs[i]][prev]=g[prev][belongs[i]]+=g[belongs[zj]][belongs[i]];
//新建顶点u, 边权w(u, v)=w(s, v)+w(t, v), 删除顶点s和t, 以及与它们相连的边
belongs[zj]=belongs[--n];
break;
}
prev=belongs[zj];
//对刚才选定的s, 更新W(A,p)(该值递增).
for(int j=1;j<n;j++) if(!vis[belongs[j]]) w[j]+=g[belongs[zj]][belongs[j]];
}
}
return best;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(g,0,sizeof(g));
for(int i=0;i<m;i++)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
g[y][x]+=c;
g[x][y]+=c;
}
printf("%d/n",minCut(n));
}
return 0;
}