Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 664 Accepted Submission(s): 256
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
题目大意:有一个1~n的排列,问所有区间中第k大的数的总和是多少?
解题思路:我们只要求出对于一个数x左边最近的k个比他大的和右边最近k个比他大的,扫一下就可以知道有几个区间的k大值是x.
我们考虑从小到大枚举x,每次维护一个双向链表,链表里只有>=x的数,那么往左往右找只要暴力跳k次,删除也是O(1)的。
时间复杂度:O(nk)
x从1开始找,因为1左右的都是比它大的数,找完后ans加上k大值是 1 的区间数 * 1 ,然后在数组里把 1 删除,然后找比 枚举 1 的下一位,因为1 已经被删除了,所以剩下的都是比 2 大的数字了,又用同样的方法,直到n - k +1.
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL MOD=1e9+7;
const int MAXN=1e6+7;
int a[MAXN],pos[MAXN];
int s[MAXN],t[MAXN];
int pre[MAXN],nxt[MAXN];
int n,k;
void erase(int x)//把下标为x的这个数从数组中删掉
{
int pp=pre[x],nn=nxt[x];
if(pre[x]) nxt[pre[x]]=nn;
if(nxt[x]<=n) pre[nxt[x]]=pp;
pre[x]=nxt[x]=0;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;++i)
{
scanf("%d",&a[i]);
pos[a[i]]=i;//每一个数对应的下标
}
for(int i=1;i<=n;++i)
{
pre[i]=i-1;
nxt[i]=i+1;
}
// for(int i=1;i<=n;++i)
// {
// cout<=1)
{
ans+=(LL)(t[k+1-i+1]-t[k+1-i])*(s[i]-s[i+1])*num;
}
}
erase(p);
}
printf("%lld\n",ans);
}
return 0;
}