P3543题解

· · 题解

题目

传送门

分析

这道题其实很简单(大雾

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

先让 x 为正,y 为负。

然后 x 不断减 b,y 加 a。

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

代码

//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;
}