这题是参考别人的。当时自己建图怎么也建不起来。到现在还是在诡异为什么要这样建图。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAXN = 20005;
const int MAXEDGE = 1e6 + 5;
const int INF = 0x3f3f3f3f;
int n, m;
struct Edge
{
int to, cap, flow, next;
}edge[MAXEDGE];
struct Dinic
{
int pp, s, t;
int head[MAXN], cur[MAXN];
bool vis[MAXN];
int d[MAXN];
Dinic(int ss, int tt)
{
s = ss, t = tt;
pp = 0;
memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int c)
{
edge[pp] = (Edge){v, c, 0, head[u]};
head[u] = pp++;
edge[pp] = (Edge){u, 0, 0,head[v]};
head[v] = pp++;
}
int getMaxFlow()
{
int res = 0;
while(bfs())
{
for(int i = 0;i <= n+2; i++)
cur[i] = head[i];
res += dfs(s, INF);
}
return res;
}
bool bfs()
{
memset(vis, false, sizeof(vis));
d[s] = 0;
vis[s] = true;
queue <int> q;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
int next = head[u];
while(next != -1)
{
Edge &e = edge[next];
if(!vis[e.to] && e.cap > e.flow)
{
d[e.to] = d[u] + 1;
vis[e.to] = true;
q.push(e.to);
}
next = e.next;
}
}
return vis[t];
}
int dfs(int u, int a)
{
if(u == t || a == 0) return a;
int &next = cur[u];
int flow = 0, f;
while(next != -1)
{
Edge &e = edge[next];
if(d[e.to] == d[u] + 1 && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0)
{
e.flow += f;
edge[next^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
next = e.next;
}
//cout<<"flow = "<<flow<<endl;
return flow;
}
};
int main()
{
while(scanf("%d%d", &n ,&m) != EOF)
{
int c1, c2;
int s = 0, t = n + 1;
Dinic dinic(s, t);
for(int i = 0;i < n; i++)
{
scanf("%d%d", &c1, &c2);
dinic.addEdge(s, i+1, c1);
dinic.addEdge(i+1, t, c2);
}
int u, v, c;
for(int i = 0;i < m; i++)
{
scanf("%d%d%d", &u, &v, &c);
dinic.addEdge(u, v, c);
dinic.addEdge(v, u, c);
}
cout<<dinic.getMaxFlow()<<endl;
}
return 0;
}