For an array aaa, define its cost as ∑i=1nmex†([a1,a2,…,ai])\sum_{i=1}^{n} \operatorname{mex} ^\dagger ([a_1,a_2,\ldots,a_i])∑i=1nmex†([a1,a2,…,ai]).
You are given a permutation‡^\ddagger‡ ppp of the set {0,1,2,…,n−1}\{0,1,2,\ldots,n-1\}{0,1,2,…,n−1}. Find the maximum cost across all cyclic shifts of ppp.
†mex([b1,b2,…,bm])^\dagger\operatorname{mex}([b_1,b_2,\ldots,b_m])†mex([b1,b2,…,bm]) is the smallest non-negative integer xxx such that xxx does not occur among b1,b2,…,bmb_1,b_2,\ldots,b_mb1,b2,…,bm.
‡^\ddagger‡A permutation of the set {0,1,2,...,n−1}\{0,1,2,...,n-1\}{0,1,2,...,n−1} is an array consisting of nnn distinct integers from 000 to n−1n-1n−1 in arbitrary order. For example, [1,2,0,4,3][1,2,0,4,3][1,2,0,4,3] is a permutation, but [0,1,1][0,1,1][0,1,1] is not a permutation (111 appears twice in the array), and [0,2,3][0,2,3][0,2,3] is also not a permutation (n=3n=3n=3 but there is 333 in the array).
Input
Each test consists of multiple test cases. The first line contains a single integer ttt (1≤t≤1051 \le t \le 10^51≤t≤105) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer nnn (1≤n≤1061 \le n \le 10^61≤n≤106) — the length of the permutation ppp.
The second line of each test case contain nnn distinct integers p1,p2,…,pnp_1, p_2, \ldots, p_np1,p2,…,pn (KaTeX parse error: Expected 'EOF', got '&' at position 11: 0 \le p_i &̲lt; n) — the elements of the permutation ppp.
It is guaranteed that sum of nnn over all test cases does not exceed 10610^6106.
Output
For each test case, output a single integer — the maximum cost across all cyclic shifts of ppp.
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> PII;
const int N = 1e6+10;
LL a[N];
bool vis[N];
void slove()
{
int n;
cin>>n;
for(int i=0;i<n;i++)cin>>a[i];
memset(vis,0,n + 10);
LL s=0;
deque<PII> q;
for(LL i=0,j=0;i<n;i++)
{
vis[a[i]]=true;
while(vis[j])j++;
q.push_back({j,1});
s+=j;
}
LL ret=0;
for(int i=0;i<n;i++)
{
s-=q.front().first;
if(--q.front().second==0)q.pop_front();
LL cnt=0;
while(!q.empty()&&q.back().first>a[i])
{
s-=q.back().first*q.back().second;
cnt+=q.back().second;
q.pop_back();
}
s+=a[i]*cnt+n;
q.push_back({a[i],cnt});
q.push_back({n,1});
ret=max(ret,s);
}
cout<<ret<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)slove();
}
文章讨论了给定一个由0到n-1的唯一整数组成的排列p,计算其所有可能循环移位中mex值的最大成本。mex函数用于找出一个数组中未出现的最小正整数。

被折叠的 条评论
为什么被折叠?



