Problem - D - Codeforces

Problem - D - Codeforces

这道题我们每次要选择一个长度大于等于k的区间,删除第k小元素,那么显然,对于整个数组的第1到第k-1小的元素,一定不会被删除,因为他们不会是任何一个子数组的第k小,因此只要不是这些数字,我们都可以删除,删除后,我们用双指针维护两端 ,如果相同就左右向中间移动,如果不同,如果其中一个是第k小的元素,那么我么那就删除 直到结束或者没有删除次数

代码实现如下:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define int long long 
void solve(){
    int n,k;
    cin>>n>>k;
    vector<int>a(n+1,0);
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    vector<int>b=a;
    sort(b.begin()+1,b.end());
    int line=b[k-1];
    vector<int>ans;
    for(int i=1;i<=n;i++){
        if(a[i]<=line)ans.push_back(a[i]);
    }
    int sz=ans.size();
    int num=ans.size()-(k-1);
    int l=0,r=sz-1;
    while(l<r){
        if(ans[l]==ans[r]){
            l++,r--;
        }else {
            if(num&&ans[l]==line){
                l++,num--;
            }else if(num&&ans[r]==line){
                r--,num--;
            }else {
                cout<<"No\n";
                return ;
            }
        }
    }
    cout<<"YES\n";
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t;
    while(t--)solve();
    return 0;
}
相关推荐
鹿角片ljp21 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技1 天前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
.道阻且长.1 天前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq71 天前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.1 天前
032动态规划之区间DP——算法备赛
算法·动态规划
小欣加油1 天前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
不会代码的小猴1 天前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军1 天前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术1 天前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent