题解:CF2025C New Game
题意:找到一组数字,这些数字最多包含 \(k\) 个不同的数字,并且这些数字在排序后是连续的(即相邻数字之差不超过 \(1\))。
思路:先统计每个数字的出现次数,然后对所有数字排序,使用滑动窗口寻找最多包含 \(k\) 个连续数字的窗口,并计算该窗口内数字的总出现次数。
代码:
#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
vector<int> a(n);
map<int,int> mp;
for(auto &x:a) cin>>x,mp[x]++;
vector<pair<int,int>> nums;
for(auto &[num,cnt]:mp){
nums.push_back({num,cnt});
}
sort(nums.begin(),nums.end());
int m=nums.size();
int l=0;
ll tmp=0;
ll maxn=0;
for(int r=0;r<m;r++){
tmp+=nums[r].second;
while(l<=r&&(r-l+1)>k){
tmp-=nums[l].second;
l++;
}
while(l<=r&&nums[r].first-nums[l].first>r-l){
tmp-=nums[l].second;
l++;
}
maxn=max(maxn,tmp);
}
cout<<maxn<<"\n";
}
}

浙公网安备 33010602011771号