题意
给定一个的排列 想知道所有满足的区间 里的数中第大的元素,输出它们的和。
思路
这题其实可以一眼整体二分 但是时间复杂度太差单调栈特判的情况仅能得到分 然后你可以将a备份 然后从小到大排序 先建一个总链表 然后枚举每一个为第k大的答案具体就是往前找k个往后找k个然后你就类似于一个滑动窗口那样枚举每一个长度为k的区间向左向右扩就行然后更新完答之后再把原来的在链表中删除即可 最好还是数据点分治特判
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<stack>
#define int long long
using namespace std;
const int maxn=5e5+5;
int n,val[maxn],a[maxn],k,tot,zuo[maxn],you[maxn];
vector<int> l;
stack<int> st;
int read() {
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') {
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*f;
}
struct node {
int pre,bac;
} b[maxn];
void dfs_pre(int now,int kkk) {
if(now==-1||(!kkk)) return;
dfs_pre(b[now].pre,kkk-1);
l.push_back(now);
}
void dfs_bac(int now,int kkk) {
if(now==-1||(!kkk))return;
l.push_back(now);
dfs_bac(b[now].bac,kkk-1);
}
signed main() {
// freopen("1.txt","r",stdin);
// freopen("2.txt","w",stdout);
n=read();
k=read();
for(int i=1; i<=n; ++i) a[i]=read(),val[a[i]]=i;//一会要排序
for(int i=0; i<=n+1; ++i) b[i].pre=i-1,b[i].bac=i+1;
b[n+1].bac=-1;
if(k==1) {
for(int i=1; i<=n; ++i) {
while((!st.empty())&&a[i]>a[st.top()]) {
zuo[st.top()]=i;
st.pop();
}
st.push(i);
}
while(!st.empty()) {
zuo[st.top()]=n+1;
st.pop();
}
for(int i=n; i>0; --i) {
while((!st.empty())&&a[i]>a[st.top()]) {
you[st.top()]=i;
st.pop();
}
st.push(i);
}
while(!st.empty()) {
you[st.top()]=0;
st.pop();
}
//for(int i=1; i<=n; ++i) printf("%lld ",you[i]);
// printf("\n");
for(int i=1; i<=n; ++i) tot+=(zuo[i]-i)*(i-you[i])*a[i];
printf("%lld",tot);
} else {
sort(a+1,a+n+1);
for(int i=1; i<=n-k+1; ++i) { //就说明不会有没有的情况
int p=k;
l.clear();
dfs_pre(b[val[a[i]]].pre,p);
l.push_back(val[a[i]]);
dfs_bac(b[val[a[i]]].bac,p);//利用dfs来更新l
// printf("%lld\n",l.size());
// if(k>1) {
for(int j=l.size()-2; j-k+1>0; j--) {
int kk=j-k+1;
tot+=a[i]*(l[kk]-l[kk-1])*(l[j+1]-l[j]);
}
//tot-=a[i];
// }
//if(k==1) tot+=a[i];
//printf("%lld\n",tot);
b[b[val[a[i]]].bac].pre=b[val[a[i]]].pre;
b[b[val[a[i]]].pre].bac=b[val[a[i]]].bac;
}
printf("%lld",tot);
}
// fclose(stdin);fclose(stdout);
return 0;
}