Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1842 Accepted Submission(s): 751
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
题目大意:
给你一个长度为N的序列(包含1~N并且不重复),一个区间的价值是其第k大的数,问所有区间的价值总和是多少。
思路:
我们首先建立出来一个双向链表,使得pre【i】表示位子i的前边的位子,nex【i】表示位子i后边的位子。
那么有初始化:pre【i】=i-1&&nex【i】=i+1
同时我们维护一个数组pos【i】,表示数字i在原序列的位子。
那么我们一开始,找到数字1,显然此时无论向左找还是向右找,我们遍历到的数字一定都是比1大的。
那么我们暴力向左找最多k个数,暴力向右找最多k个数,同时维护两个数:
numl【i】,表示以数字1所在位子作为起点,向左找到i个比他大的数之前,序列的长度。
numr【i】,表示以数字1所在位子作为起点,向右找到i个比他大的数之前,序列的长度。
然后我们枚举一个值r,表示向右找到了r个比数字1大的数字,那么我们需要判断左边是否找到m-1-r个比数字1大的数字,如果可以,那么累加答案即可。
累加答案的过程大致如图(我们将黄色部分长度相乘累加即可):
然后处理完数字1之后,我们将数字1从链表中删除,然后继续处理数字2即可,依次类推。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#define ll __int64
int pos[500500];
int nex[500500];
int pre[500500];
int a[500500];
int n,m;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{
pos[a[i]]=i;
nex[i]=i+1;
pre[i]=i-1;
}
ll output=0;
for(int i=1;i<=n;i++)
{
ll numl[100],numr[100];
int mid=pos[i];
int contl=0;
int contr=0;
while(mid>=1&&contl<m)
{
numl[contl++]=mid-pre[mid];
mid=pre[mid];
}
mid=pos[i];
while(mid<=n&&contr<m)
{
numr[contr++]=nex[mid]-mid;
mid=nex[mid];
}
contl--;contr--;
ll sum=0;
for(int r=0;r<=contr;r++)
{
int l=m-1-r;
if(l>=0&&l<=contl)
{
sum+=numl[l]*numr[r];
}
}
output+=i*sum;
mid=pos[i];
nex[pre[mid]]=nex[mid];
pre[nex[mid]]=pre[mid];
}
printf("%I64d\n",output);
}
}