最大流,模板很重要,容易超时
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#define MAXN 100005
#define MAXE 1100000
#define INF 0x7fffffff
using namespace std;
struct Edge
{
int to, from, next, cap;
}edge[MAXE];
int head[MAXN],cnt,n,m,src,des;
int dep[MAXN], gap[MAXN]; //dep[des] = 0初始化为0,代表汇点des的深度为0,gap[0] = 1代表深度为0的点有1个,即汇点
void init(){
memset(head,-1,sizeof(head));
cnt=0;
}
void addedge(int cu, int cv, int cw)
{
edge[cnt].from = cu;
edge[cnt].to = cv;
edge[cnt].cap = cw;
edge[cnt].next = head[cu];
head[cu] = cnt++;
edge[cnt].from = cv;
edge[cnt].to = cu;
edge[cnt].cap = 0;
edge[cnt].next = head[cv];
head[cv] = cnt++;
}
int que[MAXN];
void BFS()
{
memset(dep, -1, sizeof(dep));
memset(gap, 0, sizeof(gap));
gap[0] = 1;
int L = 0, R = 0;
dep[des] = 0;
que[R++] = des;
int u, v;
while (L != R)
{
u = que[L++];
L = L%MAXN;
for (int i=head[u]; i!=-1; i=edge[i].next)
{
v = edge[i].to;
if (edge[i ^1].cap == 0 || dep[v] != -1)
continue;
que[R++] = v;
R = R % MAXN;
++gap[dep[v] = dep[u] + 1];
}
}
}
int cur[MAXN],stack[MAXN];
int Sap()
{
int res = 0;
BFS();
int top = 0;
memcpy(cur, head, sizeof(head));
int u = src, i;
while (dep[src] < n)
{
if (u == des)
{
int temp = INF, inser = n;
for (i=0; i!=top; ++i){
if (temp > edge[stack[i]].cap){
temp = edge[stack[i]].cap;
inser = i;
}
}
for (i=0; i!=top; ++i)
{
edge[stack[i]].cap -= temp;
edge[stack[i]^1].cap += temp;
}
res += temp;
top = inser;
u = edge[stack[top]].from;
}
for (i = cur[u]; i != -1; i = edge[i].next)
if (edge[i].cap != 0 && dep[u] == dep[edge[i].to] + 1) break;
if (i != -1)
{
cur[u] = i;
stack[top++] = i;
u = edge[i].to;
}
else
{
if (--gap[dep[u]] == 0)
break;
int minn = n;
for (i = head[u]; i != -1; i = edge[i].next)
{
if (edge[i].cap == 0)
continue;
if (minn > dep[edge[i].to])
{
minn = dep[edge[i].to];
cur[u] = i;
}
}
++gap[dep[u] = minn + 1];
if (u != src)
u = edge[stack[--top]].from;
}
}
return res;
}
int main()
{
int T,x,y,L,R,i,ans,cap;
scanf("%d",&T);
while(T--){
init();
scanf("%d%d",&n,&m);
L=INF;R=-INF;
for(i=1;i<=n;i++){
scanf("%d%d",&x,&y);
if(x<L){
L=x;
src=i;
}
if(x>R){
R=x;
des=i;
}
}
while(m--){
scanf("%d%d%d",&x,&y,&cap);
addedge(x,y,cap);
addedge(y,x,cap);
}
ans=Sap();
printf("%d\n",ans);
}
return 0;
}