CodeforcesProblemset problem 1077 F2 Pictures with Kittens (hard version) —— 优先队列+DP

The only difference between easy and hard versions is the constraints.

Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th picture has beauty ai.

Vova wants to repost exactly x pictures in such a way that:

each segment of the news feed of at least k consecutive pictures has at least one picture reposted by Vova;
the sum of beauty values of reposted pictures is maximum possible.
For example, if k=1 then Vova has to repost all the pictures in the news feed. If k=2 then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.

Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.

Input
The first line of the input contains three integers n,k and x (1≤k,x≤n≤5000) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.

The second line of the input contains n integers a1,a2,…,an (1≤ai≤109), where ai is the beauty of the i-th picture.

Output
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.

Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.

Examples
inputCopy
5 2 3
5 1 3 10 1
outputCopy
18
inputCopy
6 1 5
10 30 30 70 10 10
outputCopy
-1
inputCopy
4 3 1
1 100 1 1
outputCopy
100

题意:

给你n个点的值,你要从中选取x个使得这x个的值加起来最大,且选取的相邻两个点的距离小于等于k

题解:

线段树爆了。。好像确实会T来着,于是就换了优先队列,dp[i][j]记录的是在i位置已经取了j个最大的值是多少。优先队列存的是dp[i][j]和i。由于它有一个限制条件k,那么我们就需要将所有都初始化为-inf,或者打个标记,代表这个状态不可到达,比如说dp[1][2]。我们先for x,再for n,这样的话每次就可以开一个优先队列,否则需要N个优先队列,可能会爆炸。那么我们每次for n的时候,取的都是在j-k到j-1之间最大的那个,之后存进去的是dp[j][i-1],这样的话就避免了两个点之间的距离会超过k的情况。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pl pair<ll,int>
const int N=5e3+5;
const ll inf=1e18;
ll a[N],dp[N][N];
int main()
{
    int n,k,x;
    scanf("%d%d%d",&n,&k,&x);
    for(int i=1;i<=n;i++)
        scanf("%lld",&a[i]);
    for(int i=0;i<N;i++)
        for(int j=0;j<N;j++)
            dp[i][j]=-inf;
    dp[0][0]=0;
    for(int i=1;i<=x;i++)
    {
        priority_queue<pl>Q;
        Q.push({dp[0][i-1],0});
        for(int j=1;j<=n;j++)
        {
            while(!Q.empty()&&Q.top().second<j-k)
                Q.pop();
            dp[j][i]=Q.top().first+a[j];
            Q.push({dp[j][i-1],j});
        }
    }
    ll ans=-1;
    for(int i=n-k+1;i<=n;i++)
        ans=max(ans,dp[i][x]);
    printf("%lld\n",ans==0?-1:ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/89020406