题目大意: 求环形均摊纸牌最少移动步数。
题解
裸的最小费用流,让移动带有费用 1 1 1 即可,也就是相邻的点之间建一条边,流量无限,费用为 1 1 1。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 110
#define inf 999999999
int n,S,T,a[maxn],tot=0;
struct edge{int x,y,z,cost,next;};
edge e[maxn*maxn<<1];
int first[maxn],len=1;
void buildroad(int x,int y,int z,int cost)
{
e[++len]=(edge){x,y,z,cost,first[x]};
first[x]=len;
}
int q[maxn],st,ed,f[maxn],fa[maxn];
bool v[maxn];
bool SPFA()
{
memset(f,63,sizeof(f));
memset(fa,0,sizeof(fa));
st=1;ed=2;q[st]=S;v[S]=true;f[S]=0;
while(st!=ed)
{
int x=q[st++];st=st>T?1:st;v[x]=false;
for(int i=first[x];i;i=e[i].next)
{
int y=e[i].y;
if(e[i].z&&f[y]>f[x]+e[i].cost)
{
f[y]=f[x]+e[i].cost;fa[y]=i;
if(!v[y])v[q[ed++]=y]=true,ed=ed>T?1:ed;
}
}
}
return fa[T];
}
int main()
{
scanf("%d",&n);S=n+1,T=S+1;
for(int i=1;i<=n;i++)scanf("%d",&a[i]),tot+=a[i],
buildroad(S,i,a[i],0),buildroad(i,S,0,0);
tot/=n;
for(int i=1;i<=n;i++)buildroad(i,T,tot,0),buildroad(T,i,0,0);
for(int i=1;i<n;i++)buildroad(i,i+1,inf,1),buildroad(i+1,i,0,-1);
buildroad(n,1,inf,1);buildroad(1,n,0,-1);
for(int i=2;i<=n;i++)buildroad(i,i-1,inf,1),buildroad(i-1,i,0,-1);
buildroad(1,n,inf,1);buildroad(n,1,0,-1);
int ans=0;
while(SPFA())
{
int min_flow=inf;
for(int i=fa[T];i;i=fa[e[i].x])min_flow=min(min_flow,e[i].z);
for(int i=fa[T];i;i=fa[e[i].x])
e[i].z-=min_flow,e[i^1].z+=min_flow,ans+=min_flow*e[i].cost;
}
printf("%d\n",ans);
}