Kanade's sum(hdu 6058)

本文介绍了一种算法,用于解决给定数组中所有子数组的第K大元素之和的问题。通过构建特殊的数据结构,实现了高效的计算。
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

题目大意:把一个数组分成若干子部分,求每部分中第k大的数的和是多少?

比较详细的解释:点击打开链接

#include <iostream> #include <bits/stdc++.h> using namespace std; int a[500005],lef[500005],righ[500005]; typedef long long ll; int main() {     int T;     scanf("%d",&T);     while(T--)     {         int n,k,x;         scanf("%d%d",&n,&k);         for(int i=1; i<=n; i++)         {             scanf("%d",&x);             a[x]=i;             lef[i]=0;             righ[i]=n+1;         }         set<int>s;         set<int>::iterator ite;         lef[n+1]=0;         righ[n+1]=n+1;         s.insert(0);         s.insert(n+1);         ll ans=0;         int r;         for(int i=n; i>0; i--)         {             s.insert(a[i]);             ite=s.find(a[i]);             ite++;             r=*ite;             int l=lef[r];             lef[r]=a[i];             righ[a[i]]=r;             righ[l]=a[i];             lef[a[i]]=l;             if(n-i+1<k)                 continue;             int nowl=a[i];             for(int j=1; j<=k&&nowl; j++)                 nowl=lef[nowl];             int nowr=nowl;             for(int j=1; j<=k&&nowr!=n+1; j++)                 nowr=righ[nowr];             for(int j=1; j<=k; j++)             {                 if(nowl==a[i]||nowr==n+1)                     break;                 int nextl=righ[nowl];                 int nextr=righ[nowr];                 ans+=(ll)(nextl-nowl)*(nextr-nowr)*i;                // cout<<ans<<" ";                 //cout<<"_____________"<<endl;                 nowl=nextl;                 nowr=nextr;             }         }         printf("%lld\n",ans);     }     return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值