[模板]洛谷P3381 最小费用最大流(dinic)

#include<bits/stdc++.h>
#define ll long long
#define PB push_back
#define endl '\n'
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ull unsigned long long
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) (x & (-x))
#define rep(i, a, b) for(int i = a ; i <= b ; ++ i)
#define per(i, a, b) for(int i = b ; i >= a ; -- i)
#define clr(a, b) memset(a, b, sizeof(a))
#define in insert
#define random(x) (rand()%x)
#define PII(x, y) make_pair(x, y)
#define fi first
#define se second
#define pi acos(-1)
using namespace std;
const int maxn = 2e6 + 1000;
const ll mod = 998244353;
const int M = 50000 + 10;
const int N = 5000 + 10;
int n, m, s, t, cnt;
int head[N], vis[N], inq[N], cur[N];
ll dis[N];
ll maxflow, cost;
struct node{
    int to, next;
    ll cost, flow;
}edge[M<<1];
void add(int u, int v, int cost, int flow){
    edge[cnt].to = v;
    edge[cnt].cost = cost;
    edge[cnt].flow = flow;
    edge[cnt].next = head[u];
    head[u] = cnt ++;
}
bool spfa(){
    rep(i, 1, n) dis[i] = 1e18, inq[i] = 0, cur[i] = head[i];
    queue<int> que; dis[s] = 0;
    inq[s] = 1; que.push(s);
    while(!que.empty()){
        int u = que.front();
        que.pop();
        inq[u] = 0;
        for(int i = head[u] ; ~ i ; i = edge[i].next){
            int v = edge[i].to;
            if(dis[v] > dis[u] + edge[i].cost && edge[i].flow){
                dis[v] = dis[u] + edge[i].cost;
                if(!inq[v]){
                    inq[v] = 1;
                    que.push(v);
                }
            }
        }
    }
    return dis[t] == 1e18 ? 0 : 1;
}
ll dfs(int u, ll flow){
    if(u == t){
        vis[t] = 1;
        maxflow += flow;
        return flow;
    }
    ll used = 0;
    vis[u] = 1;
    for(int i = cur[u] ; ~ i ; i = edge[i].next){
        int v = edge[i].to;
        cur[u] = i;
        if((v == t || !vis[v]) && edge[i].flow && dis[v] == dis[u] + edge[i].cost){
            ll minflow = dfs(v, min(flow - used, edge[i].flow));
            if(minflow){
                cost += minflow * edge[i].cost;
                edge[i].flow -= minflow;
                edge[i^1].flow += minflow;
                used += minflow;
            }
            if(used == flow) break;
        }
    }
    return used;
}
void dinic(){
    while(spfa()){
        vis[t] = 1;
        while(vis[t]){
            clr(vis, 0);
            dfs(s, 1e18);
        }
    }
}
signed main(){
    ll u, v, w, z; int q;
    scanf("%d %d %d %d", &n, &m, &s, &t);
    clr(head, -1); clr(vis, 0);
    maxflow = cost = 0;
    //s = 1; t = n;
    cnt = 0;
    while(m --){
        scanf("%lld %lld %lld %lld", &u, &v, &w, &z);
        add(u, v, z, w);
        add(v, u, -z, 0);
    }
    dinic();
    cout << maxflow << ' ' << cost << endl;
    return 0;
}
View Code

 

posted @ 2020-07-13 18:00  Ketchum  阅读(3)  评论(0编辑  收藏