网络流24题 负载平衡(DCOJ8013)

题目描述

G 公司有 n nn 个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等。如何用最少搬运量可以使 n nn 个仓库的库存数量相同。搬运货物时,只能在相邻的仓库之间搬运。

输入格式

文件的第 1 11 行中有 1 11 个正整数 n nn,表示有 n nn 个仓库。
第 2 22 行中有 n nn 个正整数,表示 n nn 个仓库的库存量。

输出格式

输出最少搬运量。

样例

样例输入

5
17 9 14 16 4

样例输出

11

数据范围与提示

1≤n≤100 1 \leq n \leq 1001n100

 

费用流  感觉数据有坑

一开始数组开小了,T、WA、RE,贼好看

//Serene
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=200+10,maxm=3*maxn,INF=0x3f3f3f3f;
int n,m,S,T,sum=0;
  
int aa;char cc;
int read() {
    aa=0;cc=getchar();
    while(cc<'0'||cc>'9') cc=getchar();
    while(cc>='0'&&cc<='9') aa=aa*10+cc-'0',cc=getchar();
    return aa;
}
  
struct Node{
    int x,y,cap,flow,w;
    Node(){}
    Node(int x,int y,int cap,int w):x(x),y(y),cap(cap),w(w){}
}node[2*maxm];
  
int fir[maxn],nxt[2*maxm],e=1;
void add(int x,int y,int z,int w) {
    node[++e]=Node(x,y,z,w); nxt[e]=fir[x];fir[x]=e;
    node[++e]=Node(y,x,0,-w); nxt[e]=fir[y];fir[y]=e;
}
  
int from[maxn],zz[maxn],dis[maxn];
bool vis[maxn];
bool spfa() {
    int s=1,t=0,x,y,z;
    memset(dis,0x3f3f3f3f,sizeof(dis));
    memset(zz,0,sizeof(zz));
    zz[++t]=S;vis[S]=1;dis[S]=0;
    while(s<=t) {
        x=zz[s%maxn];
        for(y=fir[x];y;y=nxt[y]) {
            z=node[y].y;
            if(node[y].flow>=node[y].cap||dis[z]<=dis[x]+node[y].w) continue;
            dis[z]=dis[x]+node[y].w;from[z]=y;
            if(!vis[z]) {
                vis[z]=1; t++;
                zz[t%maxn]=z;
            }
        }
        s++;vis[x]=0;
    }
    return dis[T]!=INF;
}
  
int now,rs2=0;
int MCMF() {
    while(spfa()) {
        now=INF;
        for(int i=T;i!=S;i=node[from[i]].x) now=min(now,node[from[i]].cap-node[from[i]].flow);
        for(int i=T;i!=S;i=node[from[i]].x) {
            node[from[i]].flow+=now;
            node[from[i]^1].flow-=now;
            rs2+=node[from[i]].w*now;
        }
    }
    return rs2;
}
  
int main() {
    n=read();
    int x,y,z;S=n+1;T=S+1;
    for(int i=1;i<=n;++i) {
    	x=read();
    	add(S,i,x,0);
    	sum+=x;
    }
    for(int i=1;i<=n;++i) {
    	x= i==n? 1:i+1;
    	add(i,x,INF,1);
    	add(x,i,INF,1);
    }
    sum/=n;
    for(int i=1;i<=n;++i) add(i,T,sum,0);
    printf("%d",MCMF());
    return 0;
}

  

posted @ 2017-08-28 20:25  shixinyi  阅读(272)  评论(0编辑  收藏  举报