Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2427 Accepted Submission(s): 998
Problem Description
Give you an array A[1..n]A[1..n]of length nn.
Let f(l,r,k)f(l,r,k) be the k-th largest element of A[l..r]A[l..r].
Specially , f(l,r,k)=0 f(l,r,k)=0 if r-l+1< k
Give you kk , you need to calculate ∑nl=1∑nr=lf(l,r,k)∑l=1n∑r=lnf(l,r,k)
There are T test cases.
1≤T≤101≤T≤10
k≤min(n,80)k≤min(n,80)
A[1..n] is a permutation of [1..n]A[1..n] is a permutation of [1..n]
∑n≤5∗105∑n≤5∗105
Input
There is only one integer T on first line.
For each test case,there are only two integers nn,kk on first line,and the second line consists of nn integers which means the array A[1..n]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大的数之和
解析:
将A[1…n]维护成一个双向链表,再从小到大枚举每一个数,计算每一个数的贡献——计算他在多少区间是第k大的数,计算完一个数的贡献后,将这个数从链表中删掉,在继续枚举下一个数,这样在链表中的都是比这个数大的数。这样只要不断枚举下去就是答案了。
在计算一个数的贡献是,分别向左右找k-1个比他大的数,再从最左边比他大的数(在k-1个数里),向左不断移动区间,这就是区间跳跃的思想。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long int ll;
const int MAXN = 5*1e5+10000;
int a[MAXN];
int pre[MAXN],nxt[MAXN];
int pos[MAXN];
int lcnt,rcnt;
int main()
{
int t,n,k;
scanf("%d",&t);
while(t--)
{
ll ans=0;
scanf("%d%d",&n,&k);
memset(pre,0,sizeof(pre));
memset(nxt,0,sizeof(nxt));
for(int i=1;i<=n;i++) //初始化
{
scanf("%d",&a[i]);
pos[a[i]]=i;
pre[i]=i-1;
nxt[i]=i+1;
}
nxt[0]=1;
pre[n+1]=n;
for(int num=1;num<=n-k+1;num++)
{
int p=pos[num];
int cnt1=0,cnt2=0;
int p1,p2,tmp;
p1=p2=tmp=p;
while(cnt1<k-1&&pre[p1])cnt1++,p1=pre[p1]; //在左边找k-1个比它大的数
while(cnt2<k-1&&nxt[p2]<n+1) //在右边找k-1个比它大的数
{
cnt2++;
p2=nxt[p2];
if(cnt1+cnt2==k-1) tmp=p2; //记录右边满足条件的起始点(即最左边的大于num的数能包括在内的右边的数的情况)
}
if(cnt1+cnt2<k-1)continue; //如果此处找不到k-1个大于num的数的话就continue
//p1表示最左边大于num的数(在k-1个里面),p2表示最右边大于num的数(在k-1个里面),分别表示,左边的遍历起点和右边的遍历终点
//,tmp表示满足p1的区间右端点
while(1)
{
int l=p1-pre[p1]; //在算的是pos[最左边大于num的数]=p1的情况
int r=nxt[tmp]-tmp;
ans+=(ll)(l*r)*num;
if(tmp==p2||p1==p) break; //若现在左边的遍历到了num的位置(此时位置已计算过了)或者是右边遍历到第k-1个大于num的数(此时位置已计算过了),就结束
tmp=nxt[tmp];
p1=nxt[p1];
}
//将num这个点在链表中删除
pre[nxt[p]]=pre[p];
nxt[pre[p]]=nxt[p];
pre[p]=nxt[p]=0;
}
printf("%lld\n",ans);
}
return 0;
}