【洛谷4542】 [ZJOI2011]营救皮卡丘(最小费用最大流)
传送门
Solution
这是一道神仙题!
考虑这个东西是个啥。
emmm,如果两个点要到达,一定不能经过比他们大的。
所以Floyd搞定两点距离然后费用流跑一遍就是答案了!
代码实现
/*
mail: mleautomaton@foxmail.com
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi()
{
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=500010,Inf=1e9+10;
int front[N],cnt,s,t,n,m,fa[N],from[N],k,g[2010][2010];
struct node
{
int to,nxt,w,c;
}e[1500010];
queue<int>Q;
int dis[N],vis[N];
void Add(int u,int v,int w,int c)
{
e[cnt]=(node){v,front[u],w,c};front[u]=cnt++;
e[cnt]=(node){u,front[v],0,-c};front[v]=cnt++;
}
bool SPFA()
{
memset(dis,63,sizeof(dis));
Q.push(s);dis[s]=0;
while(!Q.empty())
{
int u=Q.front();Q.pop();vis[u]=0;
for(re int i=front[u];i!=-1;i=e[i].nxt)
{
int v=e[i].to;
if(e[i].w && dis[v]>dis[u]+e[i].c)
{
dis[v]=dis[u]+e[i].c;fa[v]=u,from[v]=i;
if(!vis[v])Q.push(v),vis[v]=1;
}
}
}
return dis[t]!=dis[t+1];
}
int McMf()
{
int cost=0;
while(SPFA())
{
int di=Inf;
for(re int i=t;i!=s;i=fa[i])di=min(di,e[from[i]].w);
cost+=di*dis[t];
for(re int i=t;i!=s;i=fa[i])
e[from[i]].w-=di,e[from[i]^1].w+=di;
}
return cost;
}
int main()
{
n=gi();m=gi();k=gi();
s=2*n+2,t=s+1;
memset(front,-1,sizeof(front));
memset(g,63,sizeof(g));
for(int i=1;i<=m;i++)
{
int u=gi(),v=gi(),w=gi();
g[u][v]=g[v][u]=min(g[u][v],w);
}
for(int k=0;k<=n;k++)
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++)
if(k<=i || k<=j)g[i][j]=min(g[i][j],g[i][k]+g[k][j]);
for(int i=0;i<n;i++)
for(int j=i+1;j<=n;j++)
if(g[i][j]!=g[n+1][n+1])
Add(i,j+n+1,1,g[i][j]);
Add(s,0,k,0);
for(int i=1;i<=n;i++)
{
Add(s,i,1,0);
Add(i+n+1,t,1,0);
}
printf("%d\n",McMf());
return 0;
}