题目链接:点击这里
题目大意:
给出一个长度为
n
n
n 的序列
a
i
a_i
ai ,现在可以选择一个区间
[
l
,
r
]
[l,r]
[l,r] 让其每个数都加上
k
k
k ,现在求经过此次操作后,序列中有多少个元素等于
c
c
c
题目分析:
我们对区间操作肯定是希望
a
i
+
k
=
c
a_i+k=c
ai+k=c ,所以我们要对值
a
i
a_i
ai 的下标都装在一个桶里方便查找,同时统计记录序列中原本等于
c
c
c 的元素个数的前缀和
p
r
e
i
pre_i
prei。
对于答案的统计,我们可以通过枚举
a
x
a_x
ax 来统计答案,对于每一个
a
x
a_x
ax 设
c
n
t
i
cnt_i
cnti 为
[
1
,
x
]
[1,x]
[1,x] 中
a
x
a_x
ax 的个数
如果修改
[
l
,
r
]
[l,r]
[l,r] 那么序列中
c
c
c 的个数就是
p
r
e
l
−
1
+
c
n
t
r
−
c
n
t
l
−
1
+
p
r
e
n
−
p
r
e
r
pre_{l-1}+cnt_r-cnt_{l-1}+pre_n-pre_r
prel−1+cntr−cntl−1+pren−prer
移项可得
(
p
r
e
l
−
1
−
c
n
t
l
−
1
)
+
(
c
n
t
r
+
p
r
e
n
−
p
r
e
r
)
(pre_{l-1}-cnt_{l-1})+(cnt_r+pre_n-pre_r)
(prel−1−cntl−1)+(cntr+pren−prer) ,有了这个式子我们就可以枚举
a
x
a_x
ax 的每一个位置,维护
m
a
x
(
p
r
e
l
−
1
−
c
n
t
l
−
1
)
max(pre_{l-1}-cnt_{l-1})
max(prel−1−cntl−1) 即可
最终答案就是所有状态中的最大值。
具体细节见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
int n,c,ans,a[maxn],pre[maxn],cnt[maxn];
map<int,vector<int>>mp;
bool vis[maxn];
queue<int>qu;
signed main()
{
n = read(),c = read();
for(int i = 1;i <= n;i++)
{
a[i] = read();
mp[a[i]].push_back(i);
if(a[i] == c) pre[i] = pre[i-1]+1;
else pre[i] = pre[i-1];
}
for(auto it:mp)
{
int val = it.first,maxx = 0;
for(auto pos:it.second)
{
maxx = max(maxx,pre[pos-1]-cnt[val]++);
ans = max(ans,maxx+cnt[val]+pre[n]-pre[pos]);
}
}
cout<<ans<<endl;
return 0;
}