bzoj1283 序列 费用流

Description


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

20%的数据:n<=10。
100%的数据:N<=1000,k,m<=100。Ci<=20000。

Solution


似乎不是第一次做这种题

如果不看n的范围就是线性规划上单纯形,但是这题显然可以费用流
考虑k=1的情况就是每m个数字才能选一个,对于c[i]可以不选(i,i+1,k,0),也可以选(i,i+m,1,c[i]),这样最大费用最大流就是答案
对于k不为1的情况只需要做k次就可以了

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>

#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))

const int INF=0x3f3f3f3f;
const int N=200005;
const int E=500005;

std:: queue <int> que;

struct edge {int x,y,w,c,next;} e[E];

int dis[N],pre[N];
int ls[N],edCnt=1;

bool vis[N];

int read() {
    int x=0,v=1; char ch=getchar();
    for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
    for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
    return x*v;
}

void add_edge(int x,int y,int w,int c) {
    e[++edCnt]=(edge) {x,y,w,c,ls[x]}; ls[x]=edCnt;
    e[++edCnt]=(edge) {y,x,0,-c,ls[y]}; ls[y]=edCnt;
}

bool spfa(int st,int ed) {
    fill(dis,-31); int inf=dis[st]; dis[st]=0;
    for (;!que.empty();) que.pop();
    que.push(st); vis[st]=1;
    for (;!que.empty();) {
        int now=que.front(); que.pop();
        for (int i=ls[now];i;i=e[i].next) {
            if (e[i].w>0&&dis[now]+e[i].c>dis[e[i].y]) {
                dis[e[i].y]=dis[now]+e[i].c;
                pre[e[i].y]=i;
                if (vis[e[i].y]) continue;
                que.push(e[i].y);
                vis[e[i].y]=1;
            }
        }
        vis[now]=0;
    }
    return dis[ed]!=inf;
}

int modify(int ed) {
    int mn=INF;
    for (int i=ed;pre[i];i=e[pre[i]].x) {
        mn=std:: min(mn,e[pre[i]].w);
    }
    for (int i=ed;pre[i];i=e[pre[i]].x) {
        e[pre[i]].w-=mn;
        e[pre[i]^1].w+=mn;
    }
    return mn*dis[ed];
}

int mcf(int st,int ed) {
    int ret=0;
    for (;spfa(st,ed);) ret+=modify(ed);
    return ret;
}

int main(void) {
    int n=read(),m=read(),k=read();
    rep(i,1,n) {
        int x=read();
        add_edge(i,i+1,k,0);
        add_edge(i,std:: min(i+m,n+1),1,x);
    }
    add_edge(0,1,k,0);
    add_edge(n+1,n+2,k,0);
    printf("%d\n", mcf(0,n+2));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jpwang8/article/details/80498746
今日推荐