Codeforces Round #584

题目:https://codeforc.es/contest/1209/problem/G1

题意:给你一个序列,要你进行一些操作后把他变成一个好序列,好序列的定义是,两个相同的数中间的数都要与他相同,可以把某一种数统一变成另一个数,问最少变得个数

思路:我们可以考虑贪心,对于一个互相牵扯的区间,我肯定是用总长减掉里面出现次数最多的元素才是最划得来的,我们直接求出这些牵扯区间的长度即可,方法就是我用数组记录每个元素出现最右的位置,然后从左到右遍历,我保留当前区间往右延伸的最长位置,然后减去出现最多即可,累加所有这种联通块

#include<bits/stdc++.h>
#define maxn 200005
#define mod 1000000007
using namespace std;
typedef long long ll;
ll n,q,a[maxn];
ll num[maxn],dex[maxn];
int main(){
    cin>>n>>q;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        num[a[i]]++;
        dex[a[i]]=i;
    }
    ll l=1;
    ll ans=0,mx=0,r=0;
    for(int i=1;i<=n;i++){
        r=max(r,dex[a[i]]);
        mx=max(mx,num[a[i]]);
        if(i==r){
            ans+=r-l+1-mx;
            mx=0;l=r+1;
            r=0;
        }
    }
    cout<<ans;
} 
原文地址:https://www.cnblogs.com/Lis-/p/11535821.html