题目链接
真没读懂题面的WA on test3,且WA了好几次…… 才发现,原来不是求“M - N + 1”这样一个东西,而是求我们假如要把一条边e加入到这棵MST最小生成树上去的时候,我们需要减去几条边?并且求的是这样的H(e)的和!!求和!!而不是就求一次。那么,看到点、边很小的时候,我们就可以去想了。我们是不是可以把所有边比它小的去跑一个最小割,让它们不联通,我们是不是就可以把"u -- v"放进去了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 107, maxE = 1e3 + 7;
int N, M, head[maxN], cur[maxN], cnt;
struct Eddge
{
int nex, to, flow;
Eddge(int a=-1, int b=0, int c=0):nex(a), to(b), flow(c) {}
}edge[maxE];
inline void addEddge(int u, int v, int w)
{
edge[cnt] = Eddge(head[u], v, w);
head[u] = cnt++;
}
inline void _add(int u, int v, int w) { addEddge(u, v, w); addEddge(v, u, w); }
struct node
{
int u, v, w;
}a[505];
inline bool cmp(node e1, node e2) { return e1.w < e2.w; }
int st, ed;
int deep[maxN];
queue<int> Q;
inline bool bfs()
{
for(int i=1; i<=N; i++) deep[i] = 0;
deep[st] = 1;
while(!Q.empty()) Q.pop();
Q.push(st);
while(!Q.empty())
{
int u = Q.front(); Q.pop();
for(int i=head[u], v, f; ~i; i=edge[i].nex)
{
v = edge[i].to; f = edge[i].flow;
if(f && !deep[v])
{
Q.push(v);
deep[v] = deep[u] + 1;
}
}
}
return deep[ed];
}
inline int dfs(int u, int dist)
{
if(u == ed) return dist;
for(int i=head[u], v, f; ~i; i=edge[i].nex)
{
v = edge[i].to; f = edge[i].flow;
if(f && deep[v] == deep[u] + 1)
{
int di = dfs(v, min(dist, f));
if(di)
{
edge[i].flow -= di;
edge[i^1].flow += di;
return di;
}
}
}
return 0;
}
inline int Dinic()
{
int ans = 0, tmp;
while(bfs())
{
for(int i=1; i<=N; i++) cur[i] = head[i];
while((tmp = dfs(st, INF))) ans += tmp;
}
return ans;
}
inline void init()
{
for(int i=1; i<=N; i++) head[i] = -1;
cnt = 0;
}
int main()
{
scanf("%d%d", &N, &M);
for(int i=1; i<=M; i++) scanf("%d%d%d", &a[i].u, &a[i].v, &a[i].w);
sort(a + 1, a + M + 1, cmp);
ll ans = 0;
for(int i=2; i<=M; i++)
{
init();
for(int j=1; j<i; j++)
{
if(a[i].w == a[j].w) break;
_add(a[j].u, a[j].v, 1);
}
st = a[i].u; ed = a[i].v;
ans += Dinic();
}
printf("%lld\n", ans);
return 0;
}