首页 > 代码库 > HDU 4106 Fruit Ninja 区间k覆盖问题 最小费用流

HDU 4106 Fruit Ninja 区间k覆盖问题 最小费用流

题目链接:点击打开链接

题意:

给定n长的序列,m ,k

选择一些数使得 选择的数和最大。输出和。

限制:对于任意的区间[i, i+m]中至多有k个数被选。

思路:

白书P367,区间k覆盖问题,把一个区间看成一个点,那么选了一个点就相当于覆盖了m个区间。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
using namespace std;
#define ll int
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define N 3000
#define M 3000*3000
struct Edge {
    ll to, cap, cost, nex;
    Edge(){}
    Edge(ll to,ll cap,ll cost,ll next):to(to),cap(cap),cost(cost),nex(next){}
} edge[M];
ll head[N], edgenum;
ll D[N], A[N], P[N];
bool inq[N];
void add(ll from,ll to,ll cap,ll cost) {
    edge[edgenum] = Edge(to,cap,cost,head[from]);
    head[from] = edgenum++;
    edge[edgenum] = Edge(from,0,-cost,head[to]);
    head[to] = edgenum++;
}
bool spfa(ll s, ll t, ll &flow, ll &cost) {
    for(ll i = 0; i <= t; i++) D[i] = inf;
    memset(inq, 0, sizeof inq);
    queue<ll>q;
    q.push(s);
    D[s] = 0; A[s] = inf;
    while(!q.empty()) {
        ll u = q.front(); q.pop();
        inq[u] = 0;
        for(ll i = head[u]; ~i; i = edge[i].nex)
        {
            Edge &e = edge[i];
            if(e.cap && D[e.to] > D[u] + e.cost)
            {
                D[e.to] = D[u] + e.cost;
                P[e.to] = i;
                A[e.to] = min(A[u], e.cap);
                if(!inq[e.to])
                {inq[e.to]=1; q.push(e.to);}
            }
        }
    }
	//若费用为inf则中止费用流
    if(D[t] == inf) return false;
    cost += D[t] * A[t];
    flow += A[t];
    ll u = t;
    while(u != s) {
        edge[ P[u] ].cap -= A[t];
        edge[P[u]^1].cap += A[t];
        u = edge[P[u]^1].to;
    }
    return true;
}
ll Mincost(ll s,ll t){
    ll flow = 0, cost = 0;
    while(spfa(s, t, flow, cost));
    return cost;
}
void init(){memset(head,-1,sizeof head); edgenum = 0;}
int a[N], from, to, n, m, k;
void input(){
    for(int i = 1; i<= n; i++)scanf("%d", &a[i]);
    init();
    from = 0; to = n+2;
    add(from, 1, k, 0);
    for(int i = 1; i <= n; i++){
        int tmp = min(m+i, n+1);
        add(i, tmp, 1, -a[i]);
        add(i, i+1, k, 0);
    }
    add(n+1, to, k, 0);
}
int main(){
    while(~scanf("%d %d %d", &n, &m, &k)){
        input();
        int cost = Mincost(from, to);
        cout<<-cost<<endl;
    }
    return 0;
}


HDU 4106 Fruit Ninja 区间k覆盖问题 最小费用流