思路:
题目本身不难,把值离散化一下,然后对每种值尺取一下。
比赛的时候因为之前写尺取又卡了,这一发过的很快,很清晰,做个模板好了。
模板:
//尺取数组
int Left, Right;
Left = Right = 1; //双指针初始化
while(Left <= N){
//先让右指针跑,并且保证右指针的情况都是合法的
while(Right+1 <= N && Solution_Is_OK(Right+1)){
Change_ADD(); //改变中间值,靠近约束条件
Right++; //如果(右指针+1)符合,右指针往后移
}
GetValue(); //得到需要求的最优值
if(Right+1 == sz) //break条件 具体看情况决定
break;
//由于添加(右指针+1)的位置会造成冲突,所以左指针往后移
while(Left < sz && Right+1 < sz && Solution_Is_Not_OK(Right+1)){
Change_Erase(); //改变中间值,变成符合条件
Left++; //如果(右指针+1)不符合,左指针往后移
}
}
程序代码
//#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long LL;
#define mem(a, b) memset(a, b, sizeof(a))
const int Maxn = 1e5 + 10;
vector<int>xs;
int a[Maxn], n, k;
vector<int>p[Maxn];
void solve(){
int sz;
int tmp;
tmp = 0;
for(int i=1;i<=n;i++){
int Left, Right;
sz = (int)p[i].size();
Left = 0;
Right = 0;
int cost = 0;
while(Left < sz){
while(Right+1 < sz && cost+(p[i][Right+1]-p[i][Right]-1) <= k){
cost += (p[i][Right+1]-p[i][Right]-1);
Right++;
}
if(p[i][Right]-p[i][Left]+1-cost > tmp){
tmp = p[i][Right]-p[i][Left]+1-cost;
}
if(Right+1 == sz)
break;
while(Left < sz && Right+1 < sz && cost+(p[i][Right+1]-p[i][Right]-1) > k){
cost -= (p[i][Left+1]-p[i][Left]-1);
Left++;
}
}
}
printf("%d\n",tmp);
}
int main(){
scanf("%d%d", &n, &k);
for(int i=1;i<=n;i++) scanf("%d", &a[i]), xs.push_back(a[i]);
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()) , xs.end());
for(int i=1;i<=n;i++){
a[i] = lower_bound(xs.begin(), xs.end(), a[i]) - xs.begin() + 1;
p[a[i]].push_back(i);
}
solve();
return 0;
}