跳到正文

题解

P3543题解

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

文章信息

发布
2022年6月12日
收录
2026年6月7日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
2
题目
P3543

版本

  1. v1当前

题目

传送门

分析

这道题其实很简单(大雾

用前缀和使其变成单点修改,可以求出 ax+by=cax+by=c 使得代价最小。

先让 xx 为正,yy 为负。

然后 xx 不断减 bb,yy 加 aa。

通过堆得到一个最优的答案。

代码

C++
//By AKNOI的梓钦 On 2022-06-12
#include<cmath>
#include<cstdio>
#include<climits>
#include<cstring>
#include<iostream>
#include<algorithm>
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define N 100005
using namespace std;
int read(){
	int x=0,f=1,ch=getchar();
	for(;!isdigit(ch);ch=getchar()) f=(ch=='-')?-1:1;
	for(;isdigit(ch);ch=getchar()) x=(x<<3)+(x<<1)+(ch^48);
	return x*f;
}
ll llread(){
	ll x=0,f=1,ch=getchar();
	for(;!isdigit(ch);ch=getchar()) f=(ch=='-')?-1:1;
	for(;isdigit(ch);ch=getchar()) x=(x<<3)+(x<<1)+(ch^48);
	return x*f;
}
void print(ll x){
	if(x<0) putchar('-'),x=~(x-1);
	if(x>9) print(x/10);
	putchar(x%10+48);
}
int n,rt,s[N][2];
ll a,b,lst,ans,tot,x,y,c[N],p[N],q[N],v[N],t;
ll exgcd(ll a,ll b,ll &x,ll &y){
	if(!b){
		x=1;
		y=0;
		return a;
	}
	ll tmp=exgcd(b,a%b,y,x);
	y-=x*(a/b);
	return tmp;
}
ll get(int x){
	ll res=0;
	if(p[x]>0) res+=p[x];
	if(q[x]>0) res+=q[x];
	if(q[x]+a>0) res-=q[x]+a;
	return res;
}
int mag(int x,int y){
	if(!x || !y) return x+y;
	if(v[x]<v[y]) swap(x,y);
	s[x][1]=mag(s[x][1],y);
	swap(s[x][0],s[x][1]);
	return x;
}
void init(){
	n=read();
	a=llread(),b=llread();
	if(a>b) swap(a,b);
	t=exgcd(a,b,x,y);
	a/=t,b/=t;
	x=(x+b)%b;
	for(int i=1;i<=n;++i){
		y=llread();
		c[i]=lst-y;
		lst=y;
	}
	c[++n]=lst;
	for(int i=1;i<=n;++i){
		if(c[i]%t){
			puts("-1");
			exit(0);
		}
		c[i]/=t;
		p[i]=c[i]*x%b;
		if(p[i]<0) p[i]+=b;
		q[i]=(c[i]-p[i]*a)/b;
		tot+=p[i];
		v[i]=get(i);
		rt=mag(rt,i);
	}
}
void solve(){
	tot/=b;
	while(tot--){
		x=rt;
		rt=mag(s[rt][0],s[rt][1]);
		s[x][0]=s[x][1]=0;
		p[x]-=b;
		q[x]+=a;
		v[x]=get(x);
		rt=mag(rt,x);
	}
	for(int i=1;i<=n;++i){
		if(p[i]>0) ans+=p[i];
		if(q[i]>0) ans+=q[i];
	}
	print(ans);
}
int main(){
	init();
	solve();
	return 0;
}
原文
存档评论3 条抓取于