(网络流24题大多需要spj,所以需要一个有spj的oj,本系列代码均在www.oj.swust.edu.cn测试通过)
这题的思路挺好的,就是说我们可以看得出来数值高于平均数和数值低于平均数是对立的状态,所以借助这种关系把这个环拆分成两半,左边的由源点向其链接一条容量为与平均值之差费用为0的流,右边的点则向汇点连,原环中相邻的点之间链接一条容量为INF,费用为1的流,这样跑一边最小费用最大流即可。
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define INF 100000000
int dis[10000];
bool pd[10000];
int fro[10000];
int s=0,t=9999;
struct bian
{
int l,r,f,v;
}a[1000000];
int fir[1000000];
int nex[1000000];
int tot=1;
void add_edge(int l,int r,int f,int v)
{
a[++tot].l=l;
a[tot].r=r;
a[tot].f=f;
a[tot].v=v;
nex[tot]=fir[l];
fir[l]=tot;
}
bool spfa()
{
static int dui[1000000];
memset(dis,0x1f,sizeof(dis));
int top=1,my_final=2;
dui[top]=s;
dis[s]=0;
pd[s]=true;
while(topint u=dui[top++];
for(int o=fir[u];o;o=nex[o])
{
if(a[o].f && dis[a[o].r]>dis[u]+a[o].v)
{
dis[a[o].r]=dis[u]+a[o].v;
fro[a[o].r]=o;
if(!pd[a[o].r])
{
pd[a[o].r]=true;
dui[my_final++]=a[o].r;
}
}
}
pd[u]=false;
}
if(dis[t]==0x1f1f1f1f) return false;
return true;
}
int cost;
void add_flow()
{
int mid=t;
int temp=2147483647;
while(mid!=s)
{
temp=min(temp,a[fro[mid]].f);
mid=a[fro[mid]^1].r;
}
cost+=dis[t]*temp;
mid=t;
while(mid!=s)
{
a[fro[mid]].f-=temp;
a[fro[mid]^1].f+=temp;
mid=a[fro[mid]^1].r;
}
}
int val[10000];
int main()
{
int n;
scanf("%d",&n);
int sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&val[i]);
sum+=val[i];
}
int ave=sum/n;
for(int i=1;i<=n;i++)
{
if(val[i]>ave)
{
add_edge(s,i,val[i]-ave,0);
add_edge(i,s,0,0);
}
else
{
add_edge(i,t,ave-val[i],0);
add_edge(t,i,0,0);
}
int l=i-1;
if(l==0) l=n;
int r=i+1;
if(r==n+1) r=1;
add_edge(i,l,INF,1);
add_edge(l,i,0,-1);
add_edge(i,r,INF,1);
add_edge(r,i,0,-1);
}
while(spfa()) add_flow();
cout<return 0;
}