b进制分解 加乘最小步数

11.7

b进制分解 加乘最小步数_第1张图片

b进制分解

#include 
#include 
#include 
#include 
#define LL long long
#define N 1000010
using namespace std;

int S, T, a, b;
int f[N], pw[110];

int run(){
    f[S] = 0;
    for(int i=S+1; i<=T; i++){
        if(i - a >= 0 && f[i-a] != -1) f[i] = f[i-a] + 1;
        if(i % b == 0 && f[i/b] != -1) {
            if(f[i] == -1) f[i] = f[i/b] + 1;
            else f[i] = min(f[i], f[i/b] + 1);
        }
    }
    return f[T];
}

int solve(){
    int maxx=0, s=S, t=T, pos=0;
    pw[0] = 1; for(int i=1; pw[i-1]<=T; i++) pw[i] = pw[i-1] * b;
    while (S <= T){
        S *= b, ++maxx;
        if((T - S) % a && (T - S / b) % a == 0 && S <= T) pos = maxx;
        else if((T - S) % a == 0 && S <= T) pos = 0;
    }
    if( pos ) {
        S = s * pw[pos];
        maxx = pos;
    }
    S /= b; --maxx;
    if((T - S) % a) return -1;
    S = (T - S) / a;
    int ans = maxx;
    while (maxx >= 0){
        int cc = S / pw[maxx];
        S -= cc * pw[maxx];
        ans += cc; --maxx;
    }
    return ans;
}

int main(){
    freopen ("a.in", "r", stdin);
    freopen ("a.out", "w", stdout);
    scanf("%d%d%d%d", &S, &T, &a, &b);
    if(b == 1){
        if((T - S) % a) return printf("%d\n", -1), 0;
        return printf("%d\n", (T - S) / a), 0;
    }
    if(b == 0){
        if((T - S) % a == 0) return printf("%d\n", (T - S) / a), 0;
        if(T % a == 0) return printf("%d\n", T / a), 0;
        return printf("-1\n"), 0;
    }
    memset(f, -1, sizeof(f));
    if(T <= 1000000) printf("%d\n", run());
    else printf("%d\n", solve());
    return 0;
}

你可能感兴趣的:(—————练习赛—————,—————数论—————)