题目来源:http://poj.org/problem?id=1459
模板题,然而搞得我整个人都不好了,被m<=n*n迷惑了,邻接表只开了20010大小,结果爆了,卡了我40分钟。。。数组一定一定大小要开大一些。。。
顿时想到了陈立杰的一句话:考场上千万不能错傻逼题,别人都AC你错了你就死了。。。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <queue>
#include <iostream>
using namespace std;
const int N=120,M=30000,inf=0x3fffffff;
int head[N],d[N],ver[M],e[M],next[M];
int tot=1,s,t,n,np,nc,m,maxflow;
void add (int u,int v,int w) {
ver[++tot]=v;e[tot]=w;next[tot]=head[u];head[u]=tot;
ver[++tot]=u;e[tot]=0;next[tot]=head[v];head[v]=tot;
}
bool bfs () {
queue<int> q;
memset(d,0,sizeof(d));
q.push(s); d[s]=1;
while (!q.empty()) {
int x=q.front(); q.pop();
for (int i=head[x];i;i=next[i])
if (e[i]&&!d[ver[i]]) {
q.push(ver[i]);
d[ver[i]]=d[x]+1;
if (ver[i]==t) return 1;
}
}
return 0;
}
int dinic (int x,int f) {
int rest=f;
if (x==t) return f;
for (int i=head[x];i&&rest;i=next[i])
if (e[i]&&d[ver[i]]==d[x]+1) {
int now=dinic(ver[i],min(e[i],rest));
if (!now) d[ver[i]]=0;//
e[i]-=now;
e[i^1]+=now;
rest-=now;
}
return f-rest;
}
int read () {
int x=0;
char ch=getchar();
while (ch<'0'||ch>'9') {
ch=getchar();
if (ch==EOF) return x;
}
while (ch>='0'&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
if (ch==EOF) return x;
}
return x;
}
int main () {
int u,v,w,tmp;
while (scanf("%d%d%d%d",&n,&np,&nc,&m)!=EOF) {
s=n+1,t=n+2;
maxflow=0,tot=1;
memset(head,0,sizeof(head));
for (int i=1;i<=m;i++) {
u=read();v=read();w=read();
add(u,v,w);
}
for (int i=1;i<=np;i++) {
u=read();w=read();
add(s,u,w);
}
for (int i=1;i<=nc;i++) {
u=read();w=read();
add(u,t,w);
}
while (bfs())
while (tmp=dinic(s,inf)) maxflow+=tmp;
printf("%d\n",maxflow);
}
}