跳到正文

题解

题解:AT_abc429_d [ABC429D] On AtCoder Conference

recloud约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年11月12日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
3

版本

  1. v2当前
  2. v1

题意:

一个环上有 nn 个节点有权值,问你环上每个点向后权值累加第一次大于给定的 cc 时累加权值和的和。

n≤500,000n \le 500,000。

思路:

你发现值域很大,但有权值的点最多只有 nn 个,且相邻两个点之间的向后遇到的次数是一样的,考虑把有权值的点拍下来,对于每个点之间算贡献,相邻两权值点之间的点贡献与上一个权值点贡献相等。

做法:

发现答案可以继承,直接记录向后总权值,到下一个点后减去该点权值,暴力向后拓展,由于保证了 C≤mC\le m,所以每个权值只会计算一次,是 O(n)O(n) 的。

代码:

C++
/*
雲璃猫猫が好きです
すべての生命よ,歌のように輝いています
截剣式、斬、断、破です!
*/
#include<bits/stdc++.h>
#include<bits/extc++.h>
#define int long long
#define INF 1e18
#define lb long double
#define ls (id<<1)
#define rs (id<<1|1)
#define rep(i,l,r,k) for(int i=(l);i<=(r);i+=(k))
#define dep(i,r,l,k) for(int i=(r);i>=(l);i-=(k))
#define tep(x,y) for(auto x:y)
#define wl while
#define mk(a,b) make_pair(a,b)
#define me(a,b) memset(a,b,sizeof(a))
#define pb(x) push_back(x)
#define pr putchar
#define fi first
#define se second
#define max(a,b)((a)>(b)?(a):(b))
#define min(a,b)((a)<(b)?(a):(b))
using namespace std;
random_device rd;
unsigned int seed=rd();
mt19937 Rand(seed);
typedef pair<int,int> pii;
const int M=5e5+110,mod=1e9+7,Mod=998244353;
__gnu_pbds::gp_hash_table<string,int>ml;
inline int read(){int sum=0,k=1;char c=getchar();
	while(c>'9'||c<'0'){if(c=='-')k=-1;c=getchar();
	}while(c>='0'&&c<='9'){sum=sum*10+c-48;c=getchar();
	}return sum*k;
}inline void wr(int x){if(x<0) putchar('-'),x=-x;
	if(x>9) wr(x/10);return void(putchar(x%10+'0'));}
int n,m,cnt,c=read(),Li[M],a[M],he,pl[M],ans=0,pos=0;
signed main(){
	n=read(),m=read();
	rep(i,1,n,1) Li[i]=a[i]=read();
	sort(Li+1,Li+1+n);
	cnt=unique(Li+1,Li+1+n)-Li-1;
	rep(i,1,n,1)//离散化,再把点权拍下来
		pl[lower_bound(Li+1,Li+1+cnt,a[i])-Li]++;
	
	//处理位置0到第一个权值点
	while(he<c)
		pos++,he+=pl[pos];
	ans+=(Li[1])*he;
	he=0,pos=1;
	//pos是最后一个点的位置 he是向后到pos遇到的总人数
	rep(i,1,cnt,1){
		if(i!=1) he-=pl[i];//减去之前该点的人数
		while(he<c){//暴力拓展
			pos++;
			if(pos>cnt) pos=0;//环状取
			he+=pl[pos];
		}
		if(i==cnt)//处理最后一个权值点到末尾
			ans+=(m-Li[i])*he;
		else//相邻的两个中的点产生的贡献
			ans+=(Li[i+1]-Li[i])*he;
		
	}wr(ans),pr(10);
	return 0;
}
原文