原题
贴个博客吧
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 510
#define M 10010
#define inf 0x3f3f3f3f
typedef long long ll;
using namespace std;
struct hhh
{
int to,next;
ll w;
}edge[2*M];
int Q,n,m,s,t,p,ss,tt,sum,q[N],x,y,cnt=1,head[N],dis[N],cur[N],tot,u[M],v[M];
ll extra[N],w[M],mx;
ll read()
{
ll ans=0,fu=1;
char j=getchar();
for (;j<'0' || j>'9';j=getchar()) if (j=='-') fu=-1;
for (;j>='0' && j<='9';j=getchar()) ans*=10,ans+=j-'0';
return ans*fu;
}
void add(int u,int v,ll w)
{
edge[cnt].to=v;edge[cnt].next=head[u];edge[cnt].w=w;head[u]=cnt++;
edge[cnt].to=u;edge[cnt].next=head[v];edge[cnt].w=0;head[v]=cnt++;
}
void ADD(int u,int v,ll b,ll c)
{
extra[u]-=b;extra[v]+=b;
add(u,v,c-b);
}
bool bfs(int S,int T)
{
int r;
for (int i=0;i<=n+m+3;i++)
cur[i]=head[i],dis[i]=-1;
dis[S]=1;
q[r=1]=S;
for (int l=1;l<=r;l++)
{
int u=q[l];
for (int i=head[u],v;i;i=edge[i].next)
if (edge[i].w>0 && dis[v=edge[i].to]==-1)
{
dis[v]=dis[u]+1;
q[++r]=v;
if (v==T) return 1;
}
}
return 0;
}
ll dfs(int u,ll flow,int T)
{
if (u==T) return flow;
ll ret=0,delta;
for (int &i=cur[u],v;i;i=edge[i].next)
if (edge[i].w>0 && dis[v=edge[i].to]==dis[u]+1)
{
delta=dfs(v,min(edge[i].w,flow-ret),T);
if (delta)
{
edge[i].w-=delta;
edge[i^1].w+=delta;
ret+=delta;
if (ret==flow) break;
}
}
return ret;
}
ll dinic(int S,int T)
{
ll ans=0;
while (bfs(S,T))
ans+=dfs(S,inf,T);
return ans;
}
ll buildGraph(ll x,ll y)
{
cnt=2;
sum=0;
memset(head,0,sizeof(head));
memset(extra,0,sizeof(extra));
for (int i=1;i<=m;i++)
ADD(u[i],v[i],x,min(w[i],y));
for (int i=1;i<=n;i++)
{
if (extra[i]>0) add(ss,i,extra[i]),sum+=extra[i];
if (extra[i]<0) add(i,tt,-extra[i]);
}
add(t,s,inf);
ll tmp=dinic(ss,tt);
if (tmp!=sum) return -1;
printf("!%d!\n",tmp);
///*
for (int i=head[ss];i;i=edge[i].next)
edge[i].w=edge[i^1].w=0;
for (int i=head[tt];i;i=edge[i].next)
edge[i].w=edge[i^1].w=0;
edge[cnt-1].w=edge[cnt-2].w=0;
//*/
return tmp+dinic(s,t);
}
int main()
{
Q=read();
int l,r;
while (Q--)
{
scanf("%d%d%d%d%d",&n,&m,&s,&t,&p);
s++;t++;n++;
ss=0;tt=n+1;
if (m==0)
{
printf("0 0\n");
continue;
}
for (int i=1;i<=m;i++)
u[i]=read()+1,v[i]=read()+1,w[i]=read(),mx=max(mx,w[i]);
ll mxflow=buildGraph(0,inf);
l=0;r=mx;
while (l!=r)// max min
{
int mid=(l+r)>>1;
if (buildGraph(0,mid)==mxflow) r=mid;
else l=mid+1;
}
printf("mxflow: %lld\n",mxflow);
printf("%lld ",(ll)l*p);
l=0;r=mx;
while (l!=r)//min max
{
int mid=(l+r+1)>>1;
printf("::%d %d %d\n",l,mid,r);
int ans=buildGraph(mid,inf);
printf("%d\n",ans);
if (ans==mxflow) l=mid;
else r=mid-1;
}
printf("%lld\n",(ll)r*p);
}
return 0;
}