跳到正文

个人记录

Hrdyo OJ 1020 第k大查询

EZ_XHX约 5 分钟
原文
文章信息与版本

文章信息

发布
2023年3月2日
收录
2026年7月22日
更新
2026年11月5日
篇幅
约 5 分钟

版本

  1. v1当前

题意

给定一个1∼n1\sim n的排列 a1,a2,a3,⋯ ,ana_1,a_2,a_3,\cdots,a_n 想知道所有满足r−l+1≥kr-l+1\geq k的区间 [l,r][l,r]里的数中第kk大的元素,输出它们的和。

思路

这题其实可以一眼整体二分 但是时间复杂度太差++单调栈特判k=1k=1的情况仅能得到6060分 然后你可以将a备份 然后从小到大排序 先建一个总链表 然后枚举每一个为第k大的答案具体就是往前找k个往后找k个然后你就类似于一个滑动窗口那样枚举每一个长度为k的区间向左向右扩就行然后更新完答之后再把原来的在链表中删除即可 最好还是数据点分治k=1k=1特判

C++
#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;
}
原文