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
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
Source
题意:
给你一个排列,求所有区间[l,r]内第k大的数,若没有第k大的数,就为0。求和。
POINT:
建立一个物理意义上的链表,来连接这个排列。
排列固定是1-n的数。所以先从1开始找。那么顺着链表往前和往后都是比1大的,往前最多找k-1个数,往后也一样。
这样往前找0个数,对应往后找k-1个数。往前找1个数,对应往后找k-2个数。依此类推。
只要求出往前找(0-k-1)个数的时候有几种可能,记录l数组。同理对r数组一样的操作。
答案就是对应的l乘r。
找完1就把1删了,找2。
#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;
}