BZOJ 2561 最小生成树 | 网络流 最小割

链接

BZOJ 2561

题解

用Kruskal算法的思路来考虑,边(u, v, L)可能出现在最小生成树上,就是说对于所有边权小于L的边,u和v不能连通,即求最小割;
对于最大生成树的情况也一样。容易看出两个子问题是各自独立的,把两个最小割相加即可。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
#define enter putchar('\n')
#define space putchar(' ')
template <class T>
void read(T &x){
    char c;
    bool op = 0;
    while(c = getchar(), c > '9' || c < '0')
	if(c == '-') op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
	x = x * 10 + c - '0';
    if(op) x = -x;
}
template <class T>
void write(T x){
    if(x < 0) putchar('-'), x = -x;
    if(x >= 10) write(x / 10);
    putchar('0' + x % 10);
}

const int N = 20010, M = 1000005, INF = 0x3f3f3f3f;
int n, m, L, src, des, st, ed, ans, U[M], V[M], W[M];
int ecnt = 1, adj[N], cur[N], dis[N], nxt[M], go[M], cap[M];

void add(int u, int  v, int _cap){
    go[++ecnt] = v;
    nxt[ecnt] = adj[u];
    adj[u] = ecnt;
    cap[ecnt] = _cap;
}
bool bfs(){
    static int que[N], qr;
    for(int i = 1; i <= des; i++)
	dis[i] = -1, cur[i] = adj[i];
    que[qr = 1] = src, dis[src] = 0;
    for(int ql = 1; ql <= qr; ql++){
	int u = que[ql];
	for(int e = adj[u], v; e; e = nxt[e])
	    if(cap[e] && dis[v = go[e]] == -1){
		dis[v] = dis[u] + 1, que[++qr] = v;
		if(v == des) return 1;
	    }
    }
    return 0;
}
int dfs(int u, int flow){
    if(u == des) return flow;
    int ret = 0, delta;
    for(int &e = cur[u], v; e; e = nxt[e])
	if(cap[e] && dis[v = go[e]] == dis[u] + 1){
	    delta = dfs(v, min(cap[e], flow - ret));
	    cap[e] -= delta;
	    cap[e ^ 1] += delta;
	    ret += delta;
	    if(ret == flow) return ret;
	}
    dis[u] = -1;
    return ret;
}
int maxflow(){
    int ret = 0;
    while(bfs()) ret += dfs(src, INF);
    return ret;
}
void init(){
    ecnt = 1;
    for(int i = 1; i <= des; i++)
	adj[i] = 0;
}

int main(){

    read(n), read(m), src = n + 1, des = src + 1;
    for(int i = 1; i <= m; i++)
	read(U[i]), read(V[i]), read(W[i]);
    read(st), read(ed), read(L);
    add(src, st, INF), add(st, src, 0);
    add(ed, des, INF), add(des, ed, 0);
    for(int i = 1; i <= m; i++)
	if(W[i] < L)
	    add(U[i], V[i], 1), add(V[i], U[i], 1);
    ans += maxflow();
    init();
    add(src, st, INF), add(st, src, 0);
    add(ed, des, INF), add(des, ed, 0);
    for(int i = 1; i <= m; i++)
	if(W[i] > L)
	    add(U[i], V[i], 1), add(V[i], U[i], 1);
    ans += maxflow();
    write(ans), enter;

    return 0;
}
posted @ 2017-12-28 08:24  胡小兔  阅读(363)  评论(0编辑  收藏  举报