例题: LOJ115:https://loj.ac/problem/115
Dinic实现。。。。。sap不会写。。/(ㄒoㄒ)/~~
模板自用:
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <cmath> #include <algorithm> #define mem(a,b) memset(a,b,sizeof(a)) using namespace std; const int maxn = 100102, INF = 0x7fffffff; int d[maxn], head[maxn], in[maxn], low[maxn], id[maxn]; int n, m, s, t, ans_flow, ans; struct node{ int u, v, c, f, next; }Node[2*maxn]; void add(int u, int v, int c, int f,int i) { Node[i].u = u; Node[i].v = v; Node[i].c = c; Node[i].f = f; Node[i].next = head[u]; head[u] = i; } int bfs() { queue<int> Q; mem(d,0); Q.push(s); d[s] = 1; while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(!d[e.v] && e.c > e.f) { d[e.v] = d[e.u] + 1; Q.push(e.v); } } } return d[t] != 0; } int dfs(int u, int cap) { if(u == t) return cap; for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(d[e.v] == d[u] + 1 && e.c > e.f) { int V = dfs(e.v, min(cap, e.c - e.f)); if(V > 0) { Node[i].f += V; Node[i^1].f -= V; return V; } } } return 0; } int Dinic() { int sum_flow = 0; while(bfs()){ while(int l = dfs(0,INF)) sum_flow += l; } return sum_flow; } int main() { while(cin>> n >> m) { ans = 0; mem(head,-1); ans_flow = 0; int cnt = 0; mem(in,0); s = 0; t = n+1; for(int i=0; i<m; i++) { int u, v, b, d; cin>> u >> v >> b >> d; id[i] = cnt; add(u,v,d-b,0,cnt++); add(v,u,0,0,cnt++); in[v] += b; in[u] -= b; low[i] = b; } for(int i=1; i<=n; i++) { if(in[i] > 0) { ans_flow += in[i]; add(s,i,in[i],0,cnt++); add(i,s,0,0,cnt++); } else { add(i,t,-in[i],0,cnt++); add(t,i,0,0,cnt++); } } int sum_flow = Dinic(); if(sum_flow == ans_flow){ cout<< "YES" <<endl; for(int i=0; i<m; i++) cout<< low[i] + Node[id[i]^1].c - Node[id[i]^1].f <<endl; } else cout<< "NO" <<endl; } return 0; }