POJ - 2914 Minimum Cut(全局最小割-Stoer_Wagner)
Posted Frozen_Guardian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ - 2914 Minimum Cut(全局最小割-Stoer_Wagner)相关的知识,希望对你有一定的参考价值。
题目链接:点击查看
题目大意:给出一张无向图,要求将其分为两个集合,使得最小割最小
题目分析:算法学习自:https://blog.csdn.net/dingdi3021/article/details/101960508
全局最小割,用类最大生成树实现的,时间复杂度 O ( n 3 ) O(n^3) O(n3)
代码:
// Problem: Minimum Cut
// Contest: Virtual Judge - POJ
// URL: https://vjudge.net/problem/POJ-2914
// Memory Limit: 65 MB
// Time Limit: 10000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// #pragma GCC optimize(2)
// #pragma GCC optimize("Ofast","inline","-ffast-math")
// #pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<list>
#define lowbit(x) x&-x
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
template<typename T>
inline void read(T &x)
{
T f=1;x=0;
char ch=getchar();
while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
x*=f;
}
template<typename T>
inline void write(T x)
{
if(x<0){x=~(x-1);putchar('-');}
if(x>9)write(x/10);
putchar(x%10+'0');
}
const int inf=0x3f3f3f3f;
const int N=510;
int maze[N][N];
int v[N],wg[N],vis[N];
int SW(int n) {
int res = -1;
for(int i = 0; i < n; ++i) v[i] = i; //点标号的马甲,一开始都是自己。
while(n > 1){
memset(vis,0,sizeof(vis)); //标记数组
memset(wg,0,sizeof(wg)); //权和数组
int pre = 0; //起点为0号点
vis[pre] = 1; //标记起点,虽无实际用处,仅为提醒自己
for(int i = 1; i < n; ++i){
int p = -1;
for(int j = 1; j < n; ++j) if(!vis[v[j]]){ //寻找下个拓展点
wg[v[j]] += maze[v[pre]][v[j]]; //下个点的权和加上边权
if(p == -1 || wg[v[j]] > wg[v[p]]) p = j; //寻找wg值最大的点
}
vis[v[p]] = 1; //标记下个点已经遍历
if(i == n - 1){ //最后个点,需要合并
if(res == -1) res = wg[v[p]];
else res = min(res,wg[v[p]]); //更新res,取最小割
for(int j = 0; j < n; ++j){
maze[v[pre]][v[j]] += maze[v[p]][v[j]];
maze[v[j]][v[pre]] += maze[v[j]][v[p]];
}
v[p] = v[--n];
}
pre = p;
}
}
return res;
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int n,m;
while(scanf("%d%d",&n,&m)!=EOF) {
memset(maze,0,sizeof(maze));
while(m--) {
int u,v,w;
read(u),read(v),read(w);
maze[u][v]+=w;
maze[v][u]+=w;
}
printf("%d\\n",SW(n));
}
return 0;
}
以上是关于POJ - 2914 Minimum Cut(全局最小割-Stoer_Wagner)的主要内容,如果未能解决你的问题,请参考以下文章
POJ 2914 - Minimum Cut - 全局最小割,Stoer-Wagner算法