Zhou xingxing is the successor of one style of kung fu called “Karate Kid”.he is falling love with a beautiful judo student,after being humiliated by her boyfriend,a Taekwando master from Japan,Zhou is going to fight with his rival in love.The way they fight is to destroy the wooden plank between some wooden pegs,in order to cut these wooden pegs into two disconnected parts,and destroy each piece of plank need consume different energy.However Zhou xingxing is beginner after all,so he is turn to you for help,please calculate the minimum energy he need to destroy the wooden plank.
Input
The input consists of multiple test cases.
Each test case starts with two integers n (0 < n <= 100) and m in one line, where n、m are the number of wooden pegs and wooden plank.
Following are m lines, each line contains three integers s, e and q (0 <= s, e < n,q > 0), meaning that there need q energy to destroy the wooden plank between s and e.
Output
There is only one line for each test case, which contains the minimum energy they need to complete this fight.
Sample Input
2 1
0 1 50
3 2
0 1 50
1 2 10
Sample Output
50
10
问题模型就是在一个无向图论里,且没有源汇点之分,若要去掉一些边把这个图变成两个连通分量,花费为边的权值,求最小花费,这个是有专门的算法来解决这个问题的叫Stoer_Wange算法,时间复杂度n^3
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxv = 500;
const int inf = 0x3f3f3f3f;
int v[maxv], d[maxv];
int G[maxv][maxv];
bool vis[maxv];
int Stoer_Wanger(int n) {
int res = inf;
for (int i = 1; i <= n; i++) v[i] = i;
while (n > 1) {
int k = 1, pre = 1;
memset(vis,0,sizeof(vis));
memset(d,0,sizeof(d));
for (int i = 2; i <= n; i++) {
k = -1;
for (int j = 2; j <= n; j++) {
if ( !vis[ v[j] ] ) {
d[ v[j] ] += G[ v[pre] ][ v[j] ];
if (k == -1 || d[ v[k] ] < d[ v[j] ] ) {
k = j;
}
}
}
vis[ v[k] ] = true;
if (i == n) {
res = min(res, d[ v[k] ]);
for (int j = 1; j <= n; j++) {
G[ v[pre] ][ v[j] ] += G[ v[j] ][ v[k] ];
G[ v[j] ][ v[pre] ] += G[ v[j] ][ v[k] ];
}
v[ k ] = v[ n-- ];
}
pre = k;
}
}
return res;
}
int main()
{
int n,m;
int x,y,c;
while(scanf("%d%d",&n,&m)==2)
{
memset(G,0,sizeof(G));
while(m--)
{
scanf("%d%d%d",&x,&y,&c);
x++,y++;
G[x][y]+=c;
G[y][x]+=c;
}
printf("%d\n",Stoer_Wanger(n));
}
return 0;
}
本文介绍了一个有趣的场景:周星驰作为功夫电影的主角如何利用Stoer-Wagner算法来找到切断一组木桩所需的最小能量。这是一种在无向图中寻找最小切割的经典算法。
1473

被折叠的 条评论
为什么被折叠?



