C. Sequence Transformation(模拟+STL) Codeforces Round #686 (Div. 3)

原题链接: http://codeforces.com/contest/1454/problem/C

在这里插入图片描述

测试样例

input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
output
0
1
1
2
3

题意: 给定一个整数序列,现在你可以选定一个在序列中出现过的数值 x x x进行若干次操作:
即可以选定一个区间 [ l , r ] [l,r] [l,r]这个区间不能出现过 x x x,然后删除这个区间中的元素,这个区间之后的元素位置向前移。问你最少需要多少次这样的操作才能使得序列中剩余的元素都相等。

解题思路: 其实就是在其中找一个最优的 x x x,所以我们可以遍历模拟取最小值。那么我们选定一个 x x x之后,怎么计算它需要的操作次数呢?即是看这个 x x x能将这个序列分成多少个段,那即是我们需要的操作数。这个我们可以利用 m a p < i n t , v e c t o r < i n t > > map<int,vector<int> > map<int,vector<int>>来记录 x x x所对应出现的下标,利用下标去计算我们需要的操作数,具体看代码。 然后我们只需要遍历map模拟即可得解。

AC代码

/*
*blog:https://blog.csdn.net/hzf0701
*邮箱:unique_powerhouse@qq.com
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*/
#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,n,a) for(int i=n;i>=a;i--)

using namespace std;

typedef long long ll;
const int maxn=2e5+5;//数组所开最大值
const int mod=1e9+7;//模
const int inf=0x3f3f3f3f;//无穷大

int t,n;
int a[maxn];
map<int,vector<int> > p;//存储对应下标,遍历寻找最小值。
int cal(vector<int> &temp){
    int len=temp.size();
    int cnt=0;
    rep(i,0,len-1){
        if(i==0&&temp[i]!=1){
            cnt++;
        }
        if(i==len-1&&temp[i]!=n){
            cnt++;
        }
        if(i>0&&temp[i]-temp[i-1]>1){
            cnt++;
        }
    }
    return cnt;
}
void solve(){
    int minn=inf;
    for(auto temp:p){
        minn=min(minn,cal(temp.second));
    }
    cout<<minn<<endl;
}
int main(){
    while(cin>>t){
        while(t--){
            cin>>n;
            p.clear();
            rep(i,1,n){
                cin>>a[i];
                p[a[i]].push_back(i);//将下标放入对应位置。
            }
            solve();
        }
    }
    return 0;
}
posted @   unique_pursuit  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示