您的位置:首页 > 其它

hdu 6058 Kanade's sum

2017-08-02 12:42 330 查看
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

题目分析:第一眼看求区间第K大,主席树。。。结果发现要求的区间居然有平方个。。。

实际上就是一道模拟题,枚举每一个x,对于x,找到x之前的K个比x大的点,和x之后比x大的点。那么就可以在这个2k的区间里面找到所有x是第K大的区间。具体细节详见代码。

代码入下:

/* Author:kzl */
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef long long LL;
const int maxx = 5e5+10;
int t,n,k,a[maxx];
int l[maxx],r[maxx];
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)scanf("%d",&a[i]);
LL ans=0;l[0] = r[0] = 0;
for(int i=0;i<n;i++)
{
int lcnt=1,rcnt=1,j;
for( j=i+1;j<n;j++)
{
if(rcnt>k)break;
if(a[j]>a[i])r[rcnt++]=j-i;//r存储的是距离当前点的距离
}
if(j>=n)r[rcnt]=n-i;//在i右边没有K个比a[i]大的数的情况下。i右边最后比a[i]大的数的右边还有比i小的一些数,存储下来。
for(j=i-1;j>=0;j--)
{
if(lcnt>k)break;
if(a[j]>a[i])l[lcnt++]=i-j;
}
if(j<=0) l[lcnt]=i+1;
for(j=0;j<lcnt;j++)
{
if(k-j-1>=rcnt)continue;
int lnum=l[j+1]-l[j];//就是i右边第j+1个比a[i]大的数与第j个比a[i]大的数之间有多少个数。
int rnum=r[k-j]-r[k-j-1];//因为两边区间内加起来比a[i]大的数要是k-1个。
ans+=(LL)a[i]*lnum*rnum;
}
}
printf("%lld\n",ans);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多校 模拟