Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit:65536/65536 K (Java/Others)
Total Submission(s): 561 Accepted Submission(s): 210
Problem Description
Give you an array A[1..n] of lengthn.
Let f(l,r,k) be the k-thlargest 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 ofn integers which means the arrayA[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
【题意】
给出n和k以及1~n的某个排列,求所有区间里第k大元素的和(若没有第k大,为0)。
【思路】
由于这道题数据范围较大,套主席树模板会超时,于是我们来考虑优化方法。
问题是要求所有区间第k大元素的和,其实我们可以把它转化为排列中每个数在多少区间里为第k大即可。
例如枚举的数为x,那么我们如果在它的右边找了aa个比它大的数,那么在它的左边应该找能有(k-1-aa)个数比它大的区间个数。
由于是1~n的排列,每个数都只出现一次,那么我们可以利用链表来实现优化,我们可以从小到大枚举,这样的话一个数枚举完之后就直接可以把它从链表中删除,因为后来枚举的数都要比它大,找比这个数大的数的时候会跳过。
由于蒟蒻对链表写法很生疏,我们可以用数组来模拟链表,用pre数组表示一个点之前第一个比它大的数的位置,用nex数组表示一个点之后第一个比它大的数的位置。
具体细节见代码,不能理解的话多在纸上模拟一下过程就好了。。。
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define rush() int T;scanf("%d",&T);while(T--)
typedef long long ll;
const int maxn = 500005;
const ll mod = 1e9+7;
const int INF = 0x3f3f3f;
const double eps = 1e-9;
int pos[maxn];
int pre[maxn];
int nex[maxn];
int num[maxn];
int main()
{
int n,k;
int x;
rush()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
pos[x]=i;
pre[i]=i-1;
nex[i]=i+1;
}
pre[0]=0,nex[n+1]=n+1;
ll ans=0;
for(int i=1;i<=n;i++) //从小到大枚举
{
int x=pos[i];
int l=0,r=0;
for(int j=x;j<=n&&r<k;j=nex[j])
{
num[++r]=nex[j]-j; //表示每找一个大于这个数的数要跳几个数,例如 3 5 2 6 就是 1 2。
//下面的j-pre[j]同理
}
ll cnt=0;
for(int j=x;j>0&&l<k;j=pre[j])
{
l++;
if(k-l+1>r) continue;
cnt+=(ll)(j-pre[j])*num[k-l+1];
}
ans+=cnt*i; //单个数的贡献:满足的区间个数*这个数的大小
pre[nex[x]]=pre[x]; //由于这个数比后面枚举的数要小,直接跳过
nex[pre[x]]=nex[x]; //相当于链表里的删除节点操作
}
printf("%I64d\n",ans);
}
return 0;
}