题目链接:Problem - 1744F - Codeforces
input:
8
1
0
2
1 0
3
1 0 2
4
0 2 1 3
5
3 1 0 2 4
6
2 0 4 1 3 5
8
3 7 2 6 0 1 5 4
4
2 0 1 3
output:
1
2
4
4
8
8
15
6
题意:
给定一个长度为 n 的排列,元素为 0 ~ n - 1 ,对于该排列的某一子段,给定以下两种定义:
mex:指该字段中未出现的最小元素
med:指该字段的中位数(字段长度为偶数 k 时,中位数为从小到大第 k / 2 个)
问该排列有多少字段满足其 mex > med。
思路:
首先我们研究一下这道题的规律:
对于一个长度为 s 的段,其 med 为第 大的数,要想满足 mex > med ,我们需要使 0 ~ 全部出现在该段内,这样的话,其med为 ,其mex为 ,显然满足要求。
所以我们的做法就是枚举所有长度 s ,并用双指针 l ,r 动态维护 0 ~ 所有数的最靠左和最靠右的位置,当前所有查长度为 s ,且完整包含 l < r 的子段满足要求。统计答案即可。
注意:长度为1时,只有0满足要求。
Code
#pragma GCC optimize(3)
#include<bits/stdc++.h>
#define endl "\n"
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e5+10;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3f;
int t,n;
int index[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--)
{
cin>>n;
int p;
for(int i=1;i<=n;i++)
{
cin>>p;
index[p]=i;
}
int l=index[0],r=index[0];
ll ans=1;
for(int s=2;s<=n;s++)
{
int mid=(s-1)/2;
l=min(l,min(index[mid],n-s+1));
r=max(r,max(index[mid],s));
if(r-l<s)
{
ans+=(s-(r-l));
}
}
cout<<ans<<endl;
}
return 0;
}