Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2017 Accepted Submission(s): 813
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
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]
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
2017 Multi-University Training Contest - Team 3
Recommend
liuyiding | We have carefully selected several similar problems for you: 6066 6065 6064 6063 6062
我们只要求出对于一个数xx左边最近的kk个比他大的和右边最近kk个比他大的,扫一下就可以知道有几个区间的kk大值是xx.
我们考虑从小到大枚举xx,每次维护一个链表,链表里只有>=x>=x的数,那么往左往右找只要暴力跳kk次,删除也是O(1)O(1)的。
时间复杂度:O(nk)O(nk)
计算每个数的贡献, 找到左边k-1个大于 pi的,右边 大于pi 的, 所有有贡献的区间都在这个范围内。
注意题目中是1到n的序列, 用链表维护位置,结束后删除pi, 从小到大 枚举,可以保证链表中的数 >=pi; 然后再把pi删除, 这点很重要,题中从1遍历到n,因为1对2并不会影响2是第k大,从而大大减少了时间。
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef long long ll;
const int mod =1e9+7;
const int Size = 510000;
int pre[Size],nxt[Size],pos[Size];//前一个数,后一个数,这个数的位置
int main()
{
std::ios::sync_with_stdio(false);
int t,n,k;
cin>>t;
while(t--)
{
int p=0,x;
cin>>n>>k;
for(int i=1;i<=n;i++)//pre[1]=0
{
cin>>x;
pos[x]=i;
nxt[p]=x;
pre[x]=p;
p=x;
}
nxt[x]=n+1; //防止溢出
pos[n+1]=n+1;
ll ans=0;
for(int i=1;i<=n;i++)//题中数据是一个1到n的序列
{
p=i;
int cnt=1,p1=i;
ll sum=0;
while(cnt<k && pre[p]) p=pre[p],cnt++;//从这个数往左找第k个比他大的数
while(cnt<k && nxt[p1]!=n+1) p1=nxt[p1],cnt++;//往右找
if(cnt<k) continue;
for(;p!=nxt[i];p=nxt[p])//找到左边k-1个大于 pi的,右边第1个大于pi 的
{
int l1=pos[p] - pos[pre[p]];
int r1=pos[nxt[p1]] - pos[p1];
sum+= l1*r1;
p1=nxt[p1]; //p1往右推,p也往右推
if(p1>=n+1) break;
}
pre[nxt[i]]=pre[i];//删除i
nxt[pre[i]]=nxt[i];
ans+=(ll) sum*i;//这个数乘以他的贡献值
}
printf("%lld\n",ans);
}
}