Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 2553 Accepted Submission(s): 1065
Problem Description Give you an array of length .
Let be the k-th largest element of .
Specially , if .
Give you , you need to calculate
There are T test cases.
Input There is only one integer T on first line.
For each test case,there are only two integers , on first line,and the second line consists of integers which means the array
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
题意:给你一个n个数的排列,问你全部区间第k大的总和为多少。 分析: 将a[i]看做要找的区间的第k大的数,并获取下标。。
从a[i]开始往后找,将比a[i]大的元素的下标到a[i]下标的距离用一个数组保存下来。直到找到k-1个比a[i]大的数结束,或找到数组末尾结束。
再从a[i-1]开始向前找,将比a[i]大的元素的下标到a[i]下标的距离用一个数组保存下来。直到找到k-1个比a[i]大的数结束,或找到数组开始结束。
然后遍历左边的区间,每一次相当于左边能加上一个,右边的区间能减去一个,且保证这之间的元素的个数正好为k个,那么左边区间当前取到的最前面的元素与再前面那个元素之间的元素个数,加上右面区间最后面的那个元素与其后面那个元素的元素个数就是整个区间可以变化的次数。乘上当前的a[i]。
#include<iostream> #include<cstdio> using namespace std; #define read(a) scanf("%d",&a) #define LL long long const int maxn=500000+10; int a[maxn]; int l[maxn],r[maxn]; int main() { int t; read(t); while(t--) { int n,k; read(n); read(k); for(int i=0;i<n;i++) { read(a[i]); } LL ans=0; for(int i=0;i<n;i++) { int lcnt=1,rcnt=1,j;///lcnt代表元素a[i]左边比他大的数有多少个,rcnt同理 for( j=i+1;j<n;j++) { if(rcnt>k) break; if(a[j]>a[i]) { r[rcnt++]=j-i;///r[rcnt]代表右边第rcnt个比a[i]大的数距离a[i]的距离,这个是方便计算的,可以等于j, ///但是计算的时候要特殊处理右边只有一个比a[i]大的时候,下方的rnum=1,比较麻烦, ///原来是那样做的,不建议 } } if(j>=n) r[rcnt]=n-i; ///如果a[i]右边比他大的数没超过k个, ///那么我们知道a[i]右边比他大的数只有rcnt-1个, ///我们假设距离a[i]最远的比他大的那个数为righht, ///(程序中没有right这个变量,这里就是为了方便理解) ///这里的r[rcnt]就是为了方便后面统计right右边有多少个比a[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]; int rnum=r[k-j]-r[k-j-1]; ans+=(LL)a[i]*lnum*rnum; } } printf("%lld\n",ans); } return 0; }