Ahead
11.1.2018
例题
Poj 1459
洛谷 3376
属于网络流的模板 EK算法 dinic算法 sap,isap 算法 hlpp算法
代码 (dinic)
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
inline int read()
{
int x=0;
char c=getchar();
while(c<'0' || c>'9') c=getchar();
while(c<='9' && c>='0')
{
x=(x<<3)+(x<<1)+c-'0';
c=getchar();
}
return x;
}
const int N = 1e5+100 ,inf = 0x3f3f3f3f;
int k,n,m,s=11000,t=11001,node;
int to[N<<1],nxt[N<<1],last[N],len=1,w[N];
inline void ins(int x,int y,int c)
{
to[++len]=y,nxt[len]=last[x],w[len]=c,last[x]=len;
}
int dep[N];
bool bfs()
{
memset(dep,0,sizeof(dep));
queue <int> q;
q.push(s);
dep[s]=1;
while(!q.empty())
{
int x=q.front();
q.pop();
for(int k=last[x]; k; k=nxt[k])
{
int y=to[k];
if(w[k] && !dep[y])
{
dep[y]=dep[x]+1;
if(y==t) return true;
q.push(y);
}
}
}
return false;
}
int dfs(int x,int fl)
{
if(x==t) return fl;
int res=fl;
for(int k=last[x]; k; k=nxt[k])
{
int y=to[k];
if(w[k] && dep[y]==dep[x]+1)
{
int tmp=dfs(y,min(w[k],res));
w[k]-=tmp;
res-=tmp;
w[k^1]+=tmp;
if(res==0) break;
}
}
if(res==fl) dep[x]=0;
return fl-res;
}
inline int dinic()
{
int maxflow=0;
while(bfs())
{
int tmp=dfs(s,inf);
while(tmp!=0)
{
maxflow+=tmp;
tmp=dfs(s,inf);
}
}
return maxflow;
}
inline void _clear()
{
len=1;
memset(last,0,sizeof(last));
}
int main()
{
int x,y,z;
while(scanf("%d%d%d%d",&node,&n,&m,&k)!=EOF)
{
_clear();
for(int i=1; i<=k; ++i)
{
x=read(),y=read(),z=read();
ins(x,y,z);
ins(y,x,0);
}
for(int i=1; i<=n; ++i)
{
x=read(),z=read();
ins(s,x,z);
ins(x,s,0);
}
for(int i=1; i<=m; ++i)
{
x=read(),z=read();
ins(x,t,z);
ins(t,x,0);
}
printf("%d\n",dinic());
}
return 0;
}