For an array a a a, define its cost as ∑ i = 1 n mex † ( [ a 1 , a 2 , … , a i ] ) \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 ‡ p p p 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 p p p.
† mex ( [ b 1 , b 2 , … , b m ] ) ^\dagger\operatorname{mex}([b_1,b_2,\ldots,b_m]) †mex([b1,b2,…,bm]) is the smallest non-negative integer x x x such that x x x does not occur among b 1 , b 2 , … , b m b_1,b_2,\ldots,b_m b1,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
n
n
n distinct integers from
0
0
0 to
n
−
1
n-1
n−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 (
1
1
1 appears twice in the array), and
[
0
,
2
,
3
]
[0,2,3]
[0,2,3] is also not a permutation (
n
=
3
n=3
n=3 but there is
3
3
3 in the array).
Input
Each test consists of multiple test cases. The first line contains a single integer t t t ( 1 ≤ t ≤ 1 0 5 1 \le t \le 10^5 1≤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 n n n ( 1 ≤ n ≤ 1 0 6 1 \le n \le 10^6 1≤n≤106) — the length of the permutation p p p.
The second line of each test case contain n n n distinct integers p 1 , p 2 , … , p n p_1, p_2, \ldots, p_n p1,p2,…,pn (KaTeX parse error: Expected 'EOF', got '&' at position 11: 0 \le p_i &̲lt; n) — the elements of the permutation p p p.
It is guaranteed that sum of
n
n
n over all test cases does not exceed
1
0
6
10^6
106.
Output
For each test case, output a single integer — the maximum cost across all cyclic shifts of p p p.
#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();
}