这道题建图并不难,就是个很明显的最大流。
一开始用了SAP(邻接表)算法,果断TLE。。然后就换了一个更高效的模板:SAP+bfs+栈优化,就过了。记录下来又算是一个最大流的模板吧2333
附上AC代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAX=100005;
struct Edge
{
int to, next, cap, flow;
}edge[MAX*4];//注意开4倍!!!
int tot,head[MAX];
int gap[MAX],dep[MAX],cur[MAX];
void add(int u,int v,int w)
{
edge[tot].to=v;edge[tot].cap=w;edge[tot].flow=0;
edge[tot].next=head[u]; head[u]=tot++;
edge[tot].to=u;edge[tot].cap=0;edge[tot].flow=0;
edge[tot].next=head[v];head[v]=tot++;
}
int q[MAX];
void bfs(int st,int en)
{
memset(gap,0,sizeof(gap));
memset(dep,-1,sizeof(dep));
gap[0]=1;
int fro=0,rear=0;
dep[en]=0;
q[rear++]=en;
while(fro!=rear)
{
int u=q[fro++];
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[MAX];
int sap(int st,int en,int n)
{
bfs(st,en);
memcpy(cur,head,sizeof(head));
int u=st;
int top=0;
int maxflow=0;
while(dep[st]<n)
{
if(u==en)
{
int mindis=INF;
int inser;
for(int i=0;i<top;i++)
if(mindis>edge[s[i]].cap-edge[s[i]].flow)
{
mindis=edge[s[i]].cap-edge[s[i]].flow;
inser=i;
}
for(int i=0;i<top;i++)
{
edge[s[i]].flow+=mindis;
edge[s[i]^1].flow-=mindis;
}
maxflow+=mindis;
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;
}
else
{
int mindis=n;
for(int i=head[u];i!=-1;i=edge[i].next)
if(edge[i].cap-edge[i].flow&&dep[edge[i].to]<mindis)
{
mindis=dep[edge[i].to];
cur[u]=i;
}
gap[dep[u]]--;
if(gap[dep[u]]==0)
break;
dep[u]=mindis+1;
gap[dep[u]]++;
if(u!=st)
u=edge[s[--top]^1].to;
}
}
return maxflow;
}
int n,m;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
int x,y;
int mi=INF,ma=-INF;
int s=-1,t=-1;
for(int i=0;i<n;i++)
{
scanf("%d%d",&x,&y);
if(mi>x)
mi=x,s=i+1;
if(ma<x)
ma=x,t=i+1;
}
tot=0;
memset(head,-1,sizeof(head));
//memset(edge,0,sizeof(edge));
int u,v,w;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);//注意无向图!!
}
printf("%d\n",sap(s,t,n));
}
return 0;
}