[SDOI2009]晨跑

拆点跑费用流,套模板

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(410), __(2e5 + 10), INF(2147483647);

IL ll Read(){
    RG char c = getchar(); RG ll x = 0, z = 1;
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

int n, m, fst[_], nxt[__], to[__], cnt, w[__], cost[__], S, T, max_flow, min_cost, dis[_], pv[_], pe[_], vis[_];
queue <int> Q;

IL void Add(RG int u, RG int v, RG int f, RG int co){
    cost[cnt] = co; w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
    cost[cnt] = -co; w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
}

IL bool Bfs(){
    Fill(dis, 127); dis[S] = 0; vis[S] = 1; Q.push(S);
    while(!Q.empty()){
        RG int u = Q.front(); Q.pop();
        for(RG int e = fst[u]; e != -1; e = nxt[e])
            if(w[e] && dis[to[e]] > dis[u] + cost[e]){
                dis[to[e]] = dis[u] + cost[e];
                pe[to[e]] = e; pv[to[e]] = u;
                if(!vis[to[e]]) vis[to[e]] = 1, Q.push(to[e]);
            }
        vis[u] = 0;
    }
    if(dis[T] >= dis[T + 1]) return 0;
    RG int ret = INF;
    for(RG int u = T; u != S; u = pv[u]) ret = min(ret, w[pe[u]]);
    min_cost += ret * dis[T]; max_flow += ret;
    for(RG int u = T; u != S; u = pv[u]) w[pe[u]] -= ret, w[pe[u] ^ 1] += ret;
    return 1;
}

int main(RG int argc, RG char* argv[]){
    Fill(fst, -1); n = Read(); m = Read(); S = 1; T = n;
    Add(S, S + n, INF, 0); Add(T, T + n, INF, 0); T += n;
    for(RG int i = 2; i < n; i++) Add(i, i + n, 1, 0);
    for(RG int i = 1, a, b, c; i <= m; i++) a = Read(), b = Read(), c = Read(), Add(a + n, b, 1, c);
    while(Bfs()); printf("%d %d\n", max_flow, min_cost);
    return 0;
}
posted @ 2017-12-29 19:22  Cyhlnj  阅读(93)  评论(0编辑  收藏  举报