http://acm.hdu.edu.cn/showproblem.php?pid=4280
模板题裸的最大流,n和m较大,时间卡的紧,要用堆栈加bfs优化
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=100000+10;
const int inf=0x3f3f3f3f;
int n,m;
struct point{
int x,y;
}p[maxn];
struct Edge{
int to,next,cap,flow;
}edge[maxn<<1];
int to1;
int head[maxn],gap[maxn],dep[maxn],cur[maxn];
void init(){
to1=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int w,int rw=0){
edge[to1].to=v;
edge[to1].cap=w;
edge[to1].next=head[u];
edge[to1].flow=0;
head[u]=to1++;
edge[to1].to=u;
edge[to1].cap=rw;
edge[to1].next=head[v];
edge[to1].flow=0;
head[v]=to1++;
}
int Q[maxn];
void bfs(int s,int t){
memset(dep,-1,sizeof(dep));
memset(gap,0,sizeof(gap));
gap[0]=1;
int front=0,rear=0;
dep[t]=0;
Q[rear++]=t;
while(front!=rear){
int u=Q[front++];
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(dep[v]!=-1)continue;
Q[rear++]=v;
dep[v]=dep[u]+1;
gap[dep[v]]++;
}
}
}
int S[maxn];
int sap(int s,int t,int N){
bfs(s,t);
memcpy(cur,head,sizeof(head));
int top=0;
int u=s;
int ans=0;
while(dep[s]<N){
if(u==t){
int Min=inf;
int inser;
for(int i=0;i<top;i++){
if(Min>edge[S[i]].cap-edge[S[i]].flow){
Min=edge[S[i]].cap-edge[S[i]].flow;
inser=i;
}
}
for(int i=0;i<top;i++){
edge[S[i]].flow+=Min;
edge[S[i]^1].flow-=Min;
}
ans+=Min;
top=inser;
u=edge[S[top]^1].to;
continue;
}
bool flag=false;
int v;
for(int i=cur[u];i!=-1;i=edge[i].next){
v=edge[i].to;
if(edge[i].cap-edge[i].flow&&dep[v]+1==dep[u]){
flag=true;
cur[u]=i;
break;
}
}
if(flag){
S[top++]=cur[u];
u=v;
continue;
}
int Min=N;
for(int i=head[u];i!=-1;i=edge[i].next){
if(edge[i].cap-edge[i].flow&&dep[edge[i].to]<Min){
Min=dep[edge[i].to];
cur[u]=i;
}
}
gap[dep[u]]--;
if(!gap[dep[u]])return ans;
dep[u]=Min+1;
gap[dep[u]]++;
if(u!=s)u=edge[S[--top]^1].to;
}
return ans;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
init();
int left=100001,right=-100001,l,r;
for(int i=0;i<n;i++){
scanf("%d%d",&p[i].x,&p[i].y);
if(left>p[i].x){
left=p[i].x;l=i;
}
if(right<p[i].x){
right=p[i].x;r=i;
}
}
for(int i=0;i<m;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
u--,v--;
addedge(u,v,w,w);
}
int s=l,t=r;
int ans=sap(s,t,n);
printf("%d\n",ans);
}
return 0;
}