2017杭电多校联赛第三场-Kanade's sum (hdu6058) 求第k大的数的和

Kanade's sum

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 937    Accepted Submission(s): 385


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  rl+1<k.

Give you  k , you need to calculate  nl=1nr=lf(l,r,k)

There are T test cases.

1T10

kmin(n,80)

A[1..n] is a permutation of [1..n]

n5105
 

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

题目大意:有n个数,询问在任意区间内第k大的数的和值。

解题思路:题目说明有n个数,数据是1~n,只是数据可能是乱序,所以如果我们搜索任意区间,然后找到这个区间的第k大的数,再求和这种方法是会超时的,所以我们需要换个思路:我们假设第i个数是在其所在区间的第k大的数,所以我们只需要得到这个区间的数量就可以了,即知道有多少个区间中第k大的数是第i个数,然后把所有的i值得到的sum值相加就可以得到最后的总值了,具体实现方法是,我们可以使用数组来存储每一个数的下标和数值,而数值的存贮方式可以换一下,因为知道了数据一定是1~n,而且没有重复值,所以我们只需要得到每一个数的下标就可以了,然后我们还可以得到比他大的数的下标,因为我们存储了所有数的下标,然后我们寻找区间,左边的区间长度*右边的区间长度就是关于这个数的可能区间数量,然后加上总值就可以了。

ac代码:
#include 
using namespace std;
typedef long long LL;
const double eps=1e-8; 
const double pi=acos(-1.0);
const int K=1e6+7;
const int mod=1e9+7;
int n,k,p[K],pre[K],nxt[K],pos[K],tl[85],tr[85];
LL ans;
 int main(void)
 {
     int t;cin>>t;
     while(t--)
     {
         ans=0;
         scanf("%d%d",&n,&k);
         for(int i=1;i<=n;i++)
             scanf("%d",p+i),pos[p[i]]=i;
         for(int i=1;i<=n;i++)
             pre[i]=i-1,nxt[i]=i+1;
         pre[1]=0,nxt[n]=n+1;
         for(int i=1;i<=n;i++)
         {
             int la=0,lb=0;
             for(int j=pos[i];j>0&&la<=k;j=pre[j])
                 tl[la++]=j-pre[j];
             for(int j=pos[i];j<=n&&lb<=k;j=nxt[j])
                 tr[lb++]=nxt[j]-j;
             for(int j=0;j

题目链接: 点击打开链接http://acm.hdu.edu.cn/showproblem.php?pid=6058
 

你可能感兴趣的:(杭电随笔)