Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2320 Accepted Submission(s): 956
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
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]
1 5 2 1 2 3 4 5
30
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
#define LL long long
const int N = 5*1e5+33;
int pre[N],nxt[N],pos[N],l[N],r[N];
LL ans;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,k;
ans=0;
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
{
int a;
scanf("%d",&a);
pos[a]=i;
}
for(int i=1;i<=n;i++)
{
pre[i]=i-1;
nxt[i]=i+1;
}
for(int i=1;i<=n;i++)
{
int l_cnt=0;
int r_cnt=0;
for(int j=pos[i];j>=1&&l_cnt<k;j=pre[j])
{
l[l_cnt++]=j-pre[j];
}
for(int j=pos[i];j<=n&&r_cnt<k;j=nxt[j])
{
r[r_cnt++]=nxt[j]-j;
}
for(int j=0;j<l_cnt;j++)
{
if(k-1-j<r_cnt)
{
ans+=(LL)l[j]*r[k-1-j]*i;
}
}
pre[nxt[pos[i]]]=pre[pos[i]];
nxt[pre[pos[i]]]=nxt[pos[i]];
}
printf("%lld\n",ans);
}
return 0;
}
1万+



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



