Educational Codeforces Round 55 E. Increasing Frequency(尺取法+思维)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luyehao1/article/details/84859269

题目链接:

E. Increasing Frequency

题意:

有一个长度为 n 的序列,已知正整数 c 。可以做一次操作:把区间 [l,r] 的所有数 + k (k为任意整数,l,r也自己定)。问操作后序列中最多有多少个元素的值等于 c 。

思路:

题目所述操作等价于把区间 [l,r] 中的值为 x 的元素都变为 c 。因为 x 的取值范围为 [1,5e5],所以我们可以枚举 x 的值。

对于每个 x ,用vector(或数组均可)存序列中值为x的元素的位置(从小到大),然后尺取一遍该vector即可得到对于该 x 能得到的最大结果。对于所有 x,所有vector中的元素之和 = n,所以复杂度为 O(n)。(常数应该会比较大)

如何尺取:

对于 x,如果区间 [st,ed] 中 x 的元素个数大于 c 的元素个数,那么 ed++;否则,st++;当 ed 超出vector边界时结束尺取。这里的st,ed是vector中的下标。

Code:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int MAX = 5e5+10;

int n,c;
vector<int>mp[MAX];
int num[MAX]; //num[i]为前 i 个数中 c 的个数

int main()
{
    scanf("%d%d",&n,&c);
    int ans=0;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        if(x==c){
            ans++;
            num[i]=1;
        }
        mp[x].push_back(i);
    }
    for(int i=2;i<=n;i++){
        num[i]+=num[i-1];
    }
    for(int i=1;i<=5e5;i++){
        if(i==c)    continue;
        int len = mp[i].size();
        if(len==0) continue;
        //尺取法
        int st=0,ed=0;
        while(ed<len){
            if((ed-st+1)>(num[mp[i][ed]]-num[mp[i][st]-1])){
                int tmp = (ed-st+1)+num[mp[i][st]-1]+num[n]-num[mp[i][ed]];
                ans=max(ans,tmp);
                ed++;
            }
            else{
                st++;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}

/*
10 6
2 6 6 6 2 6 6 2 2 2
*/

猜你喜欢

转载自blog.csdn.net/luyehao1/article/details/84859269