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
#include<bits/stdc++.h>
using namespace std;
#define int unsigned long long
#define ll unsigned long long
int T,n,k,u=0,tu[501001],qian[501001],hou[501001],q,qq[101],ww[101];
void shanchu(int x)
{
qian[hou[x]]=qian[x];
hou[qian[x]]=hou[x];
}
int jiejue(int x)
{
memset(qq,0,sizeof(qq));
memset(ww,0,sizeof(ww));
int er=0,re=0;
for(int a=x;a<=n;a=hou[a])
{
qq[++re]=hou[a]-a;
if(re==k)break;
}
for(int a=x;a;a=qian[a])
{
ww[++er]=a-qian[a];
if(er==k)break;
}
int fs=0;
for(int a=1;a<=er;a++)
{
if(k-a+1>re)continue;
fs+=ww[a]*qq[k-a+1]*1ll;
}
return fs;
}
main()
{
// freopen("1003in.txt", "r", stdin);
// freopen("s.txt", "w", stdout);
cin>>T;
while(T--)
{
memset(tu,0,sizeof(tu));
memset(qian,0,sizeof(qian));
memset(hou,0,sizeof(hou));
cin>>n>>k;
for(int a=1;a<=n;a++)
{
scanf("%llu",&q);
tu[q]=a;
qian[a]=a-1;
hou[a]=a+1;
}
qian[0]=0;
hou[n+1]=n+1;
hou[0]=1;
qian[n+1]=n;
int dan=0;
for(int a=1;a<=n;a++)
{
dan+=a*jiejue(tu[a])*1ll;
shanchu(tu[a]);
}
printf("%llu\n",dan);
}
}