(CodeForces) D. Frets On Fire

本文介绍了一种基于排序和查询的算法优化方案,通过过滤重复元素、计算最大贡献值并进行排序,使用前缀和加速查询过程。适用于处理大量数据的场景,提高算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

解题思路:对于排序好的a序列,先将相同的过滤掉得到b序列,然后计算每个值的最大贡献,即bi和b(i+1)的差,超过了这个就重合了,然后最后一个数的贡献当然是可以无穷大。对于贡献up当然也需要排个序,用sum来算一下前缀和。这样在每次查询的时候,二分一下区间长度+1在up数组上的位置pos,pos左边的,说明贡献都可以跑满,即前缀和sum[pos-1],后面的贡献都是大于len+1的,所以每个都是len。

#include<bits/stdc++.h>
#define il inline
#define pb push_back
#define fi first
#define se second
#define ms(_data,v) memset(_data,v,sizeof(_data))
#define sc(n) scanf("%d",&n)
#define SC(n,m) scanf("%d %d",&n,&m)
#define sz(a) int((a).size())
#define rep(i,a,b) for(int i=a;i<=b;++i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll inf=LONG_LONG_MAX;
const int maxn=1e5+5;
int n,q;
ull a[maxn],l,r;
ull b[maxn],up[maxn],sum[maxn];
int main(){
	std::ios::sync_with_stdio(0);
	cin>>n;
	rep(i,1,n)	cin>>a[i];
	sort(a+1,a+1+n);
	a[0]=-1;
	int cnt=0;
	rep(i,1,n){
		if(a[i]!=a[i-1])
		b[++cnt]=a[i];
	}
	rep(i,1,cnt-1)	up[i]=b[i+1]-b[i];
	sort(up+1,up+cnt);
	rep(i,1,cnt-1)	sum[i]+=sum[i-1]+up[i];
	up[cnt]=inf,sum[cnt]=inf;
	cin>>q;
	while(q--){
		cin>>l>>r;
		ull len=r-l+1;
		ll pos=lower_bound(up+1, up+cnt+1,len+1)-up;
		cout<<sum[pos-1]+len*(cnt-pos+1)<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值