题目
https://www.luogu.org/problem/show?pid=2402
题解
洛谷全站首次AC竟然给了我这个蒟蒻。。。
folyd处理出最短路。
拆点左边x右边y,S向x连c=s,w=0的边,y向t连c=p,w=0的边,然后对于每一对点(i,j),连xi->yj,c=inf,w=dist[i][j]。跑最小费用最大流即可。
代码
//floyd+最大流+二分
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxn 1000000
#define inf ((long long)1<<60)
#define ll long long
using namespace std;
ll N, M, S, T, head[maxn], to[maxn], c[maxn], dist[300][300], w[maxn], next[maxn],
d[maxn], Exit, tot=1, mid, num[maxn], last[maxn], cows;
void adde(ll a, ll b, ll cc, ll ww)
{to[++tot]=b;c[tot]=cc;w[tot]=ww;next[tot]=head[a];head[a]=tot;}
void adde2(ll a, ll b, ll cc, ll ww){adde(a,b,cc,ww);adde(b,a,0,-ww);;}
ll ISAP(ll pos, ll in)
{
ll t, flow=0;
if(pos==T)return in;
for(ll &p=last[pos];p;p=next[p])
if(c[p] and w[p]<=mid and d[to[p]]+1==d[pos])
{
flow+= t=ISAP(to[p],min(in-flow,c[p]));
c[p]-=t, c[p xor 1]+=t;
if(Exit or in==flow)return flow;
}
Exit=--num[d[pos]]==0;
++num[++d[pos]];
last[pos]=head[pos];
return flow;
}
void build()
{
ll x, y, z, s, p, i, j, k;
scanf("%lld%lld",&N,&M);
S=2*N+1, T=S+1;
for(i=1;i<=N;i++)
scanf("%lld%lld",&s,&p),adde2(S,i,s,0),adde2(N+i,T,p,0), cows+=s;
for(i=1;i<=N;i++)for(j=1;j<=N;j++)dist[i][j]=inf;
for(i=1;i<=N;i++)dist[i][i]=0;
for(i=1;i<=M;i++)
{
scanf("%lld%lld%lld",&x,&y,&z);
dist[x][y]=dist[y][x]=min(dist[x][y],z);
}
for(k=1;k<=N;k++)
for(i=1;i<=N;i++)
for(j=1;j<=N;j++)
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
for(i=1;i<=N;i++)for(j=1;j<=N;j++)adde2(i,N+j,inf,dist[i][j]);
}
int main()
{
ll l, r, i, flow;
build();
l=1, r=inf, mid=(l+r)>>1;
while(l<r)
{
for(i=2;i<=tot;i+=2)c[i]+=c[i xor 1], c[i xor 1]=0;
for(i=1;i<=T;i++)d[i]=0,last[i]=head[i],num[i]=0;
for(flow=Exit=0;!Exit;flow+=ISAP(S,inf));
if(flow==cows)r=mid;else l=mid+1;
mid=(l+r)>>1;
}
printf("%lld",r==inf?-1:r);
return 0;
}