Problem Description
Give you an array
A[1..n]
of length
n
.
Let f(l,r,k) be the k-th largest element of A[l..r] .
Specially , f(l,r,k)=0 if r−l+1<k .
Give you k , you need to calculate ∑nl=1∑nr=lf(l,r,k)
There are T test cases.
1≤T≤10
k≤min(n,80)
A[1..n] is a permutation of [1..n]
∑n≤5∗105
Let f(l,r,k) be the k-th largest element of A[l..r] .
Specially , f(l,r,k)=0 if r−l+1<k .
Give you k , you need to calculate ∑nl=1∑nr=lf(l,r,k)
There are T test cases.
1≤T≤10
k≤min(n,80)
A[1..n] is a permutation of [1..n]
∑n≤5∗105
Input
There is only one integer T on first line.
For each test case,there are only two integers n , k on first line,and the second line consists of n integers which means the array A[1..n]
For each test case,there are only two integers n , k on first line,and the second line consists of n integers which means the array A[1..n]
Output
For each test case,output an integer, which means the answer.
Sample Input
1 5 2 1 2 3 4 5
Sample Output
30
从小往大加数。每次加完以后统计当前数对于答案的贡献
因为加入的数都比当前小,所以我们往左往右各找k个已经加入的数。答案就只能在这个区间中
然后左右维护两个指针扫过去,表示左边选x右边选k-x-1个数,然后统计区间个数再乘当前枚举的数加入答案即可
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<cassert>
#include<iostream>
#include<algorithm>
using namespace std;
struct link
{
int pre,next;
}p[1000001];
long long a[500001];
int fx[500001];
int p1[101],p2[101];
int main()
{
int T;
scanf("%d",&T);
while(T>0)
{
T--;
int n,k;
scanf("%d%d",&n,&k);
int i,j;
for(i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
fx[a[i]]=i;
}
for(i=1;i<=n;i++)
{
p[i].next=i+1;
p[i].pre=i-1;
}
p[0].pre=-1;
p[n+1].next=n+2;
long long ans=0;
for(i=1;i<=n-k+1;i++)
{
int t1=0,t2=0,d=p[fx[i]].pre;
p1[t1]=fx[i];
p2[t2]=fx[i];
while(d!=-1&&t1<k)
{
t1++;
p1[t1]=d;
d=p[d].pre;
}
d=p[fx[i]].next;
while(d!=n+2&&t2<k)
{
t2++;
p2[t2]=d;
d=p[d].next;
}
int dx;
for(j=t1;j>=1;j--)
{
dx=k-j+1;
if(dx<=t2&&dx>0)
ans=ans+(long long)(p1[j-1]-p1[j])*(long long)(p2[dx]-p2[dx-1])*(long long)i;
}
int t=p[fx[i]].pre;
p[p[fx[i]].pre].next=p[fx[i]].next;
p[p[fx[i]].next].pre=p[fx[i]].pre;
}
printf("%lld\n",ans);
}
return 0;
}