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

费用流 【bzoj1283】序列

2016-12-29 08:16 330 查看
题目大意:

给出一个长度为 的正整数序列Ci,求一个子序列,使得原序列中任意长度为M的子串中被选出的元素不超过K(K,M<=100) 个,并且选出的元素之和最大。

题目分析:

用容量为k,费用为0的边将原序列连成一条链,然后再把第i个点和第i+m个点连一条容量为1,费用为ci的边,跑最大费用最大流即可。

代码如下:

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<iostream>
#include<queue>
#define N 5000
using namespace std;
const int lar=1023456789;
int n,m,k,s,e,x,cs;
int fir
,nes
,v
,q
,w
,top=1;
int f
,bak
,road
;
bool b
;
void edge(int x,int y,int z,int c)
{
top++;
v[top]=y;q[top]=z;w[top]=c;bak[top]=x;
nes[top]=fir[x];fir[x]=top;
}
bool spfa()
{
queue<int> V;
memset(f,-1,sizeof(f));
memset(road,0,sizeof(road));
V.push(s);f[s]=0;b[s]=true;
while(!V.empty())
{
int c=V.front();
for(int t=fir[c];t;t=nes[t])
{
if(!q[t] || f[c]+w[t]<=f[v[t]]) continue;
f[v[t]]=f[c]+w[t]; road[v[t]]=t;
if(b[v[t]]) continue;
V.push(v[t]);b[v[t]]=true;
}
b[c]=false;
V.pop();
}
return f[e]!=-1;
}
int fly()
{
int ans=0,c;
while(spfa())
{
c=lar;
for(int t=e;t!=s;t=bak[road[t]]) c=min(q[road[t]],c);
for(int t=e;t!=s;t=bak[road[t]])
{
ans+=w[road[t]]*c;
q[road[t]]-=c;
q[road[t]^1]+=c;
}
}
return ans;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
s=4*n+1;e=4*n+2;
for(int i=2;i<=n;i++)
edge(i-1,i,k,0),edge(i,i-1,0,0);
edge(s,1,k,0);edge(1,s,0,0);
edge(n,e,k,0);edge(e,n,0,0);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
if(i+m<=n) edge(i,i+m,1,x),edge(i+m,i,0,-x);
else       edge(i,e,1,x),edge(e,i,0,-x);
}
printf("%d\n",fly());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络流