您的位置:首页 > 理论基础 > 计算机网络

Chocolate 网络流解法

2015-08-07 14:59 127 查看
Description

Lethe loves eating chocolates very much. In Lethe's birthday, her good friend echo brings N boxes to her, and makes the boxes on the circle. Furthermore, echo tells Lethe that there are many chocolates
in the boxes, but the total number of chocolates doesn't exceed N. Also, echo wants Lethe to displace the chocolates in such a way that in each box remains no more than one chocolate. In one move she can shift one chocolate from current box to its neighboring
box. (Each box has two neighboring boxes). Can you tell Lethe the minimum number of move to achieve this goal?

Input

There are multi-cases (The total number of cases won't exceed 20). First line is an integer N(1<=N<=500), the total number of boxes. Then N lines follow, each line includes a number, indicates the number
of chocolates in the box.

Output

Output the minimum number of move.

Sample Input

10
1
3
3
0
0
2
0
0
0
0


Sample Output

9


此题本是km练习题,然而本渣并不会,所以附上最简单的网络流做法,建图很无脑,根据题意建图即可,由于每个点可以向两边转移,因此分别建一条边,流量为INF,费用为1就ok了,考虑到最终结果为每个点不大于1,因此把每个点往汇点建一条流量为1,费用为0 的边即可。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define maxn 600
#define inf 0x3f3f3f
using namespace std;
struct node
{
int st;
int en;
int flow,cost;
int next;
}E[101000];
int num;
int p[maxn];
void init()
{
memset(p,-1,sizeof p);
num=0;
}
void add(int st,int en,int flow,int cost)
{
E[num].st=st;
E[num].en=en;
E[num].flow=flow;
E[num].cost=cost;
E[num].next=p[st];
p[st]=num++;
E[num].st=en;
E[num].en=st;
E[num].flow=0;
E[num].cost=-cost;
E[num].next=p[en];
p[en]=num++;
}
int pre[maxn];
int dis[maxn];
bool fg[maxn];
bool spfa(int st,int en)
{
for(int i=0;i<=en;i++)
fg[i]=0,dis[i]=inf,pre[i]=-1;
queue<int>q;
q.push(st);
fg[st]=1;
dis[st]=0;
while(!q.empty())
{
int u=q.front();
q.pop();
fg[u]=0;
for(int i=p[u];i+1;i=E[i].next)
{
int v=E[i].en;
if(E[i].flow&&dis[v]>dis[u]+E[i].cost)
{
dis[v]=dis[u]+E[i].cost;
pre[v]=i;
if(!fg[v])
{
fg[v]=1;
q.push(v);
}
}
}
}
if(dis[en]<inf)
return 1;
return 0;
}
int solve(int st,int en)
{
int ans=0;
while(spfa(st,en))
{
int d=inf;
for(int i=pre[en];i+1;i=pre[E[i].st])
d=min(d,E[i].flow);
for(int i=pre[en];i+1;i=pre[E[i].st])
{
E[i].flow-=d;
E[i^1].flow+=d;
ans+=d*E[i].cost;
}
}
return ans;
}
int ma[520];
int main()
{
int n;
while(~scanf("%d",&n))
{
int s=0,t=n+1;
init();
for(int i=1;i<=n;i++) scanf("%d",&ma[i]);
for(int i=1;i<=n;i++)
{
add(s,i,ma[i],0);
add(i,t,1,0);
if(i==1)
{
add(i,n,inf,1);
add(i,i+1,inf,1);
}
else if(i==n)
{
add(i,1,inf,1);
add(i,i-1,inf,1);
}
else
{
add(i,i-1,inf,1);
add(i,i+1,inf,1);
}
}
printf("%d\n",solve(s,t));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: