题解:CF933B A Determined Cleanup

· · 题解

D

分析

提供一个简洁易懂的做法:

注意到 f(-k) = p,也就是说 f(-k) = \sum_{i=0}^{d-1} a_i (-k)^i = p,那本质上就是在求以 -k 为基的 p 的表出。

故做法类似于十进制,只不过是把基底 b = 10 换成 b=-k 。考虑除式 p = q b + r,可以发现 r 对应着 a_i \geq 0,所以做除法的时候注意把 r 调整到 [0, k-1] 即可。

代码

// Problem: D. A Determined Cleanup
// Contest: Codeforces - Codeforces Round 462 (Div. 2)
// URL: https://codeforces.com/contest/934/problem/D
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;

#define debug(x) cerr << #x << ": " << (x) << endl
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define dwn(i,a,b) for(int i=(a);i>=(b);i--)
#define SZ(a) ((int) (a).size())
#define pb push_back
#define all(x) (x).begin(), (x).end()

#define x first
#define y second
#define int long long
using pii = pair<int, int>;
using ll = long long;

inline void read(int &x){
    int s=0; x=1;
    char ch=getchar();
    while(ch<'0' || ch>'9') {if(ch=='-')x=-1;ch=getchar();}
    while(ch>='0' && ch<='9') s=(s<<3)+(s<<1)+ch-'0',ch=getchar();
    x*=s;
}

void solve(){
    int p, k; cin>>p>>k;
    const int b=-k;
    // p = qb + r (r>=0)
    vector<int> a;
    while(p){
        int r=p%b, q=(p-r)/b;
        if(r<0) r+=-b, ++q;
        p=q;
        a.pb(r);
    }
    cout<<a.size()<<"\n";
    for(auto e: a) cout<<e<<" ";
    puts("");
}

signed main(){
    solve();
    return 0;
}

补充

我 VP 的时候没有想到上面的做法,用了一种比较麻烦的做法,这里简单说一下供参考:

记 q(x) = \sum b_i x^i, ~ b_0 = p。那根据题目约束,我们有 a_i = b_i k + b_{i-1} \in [0, k-1]。

故可以考虑解上面的不等式组得到 b_i,然后将 a_i 还原出来。

代码:

void solve(){
    int p, k; cin>>p>>k;
    vector<int> b={p};
    while(b.back()<0 || b.back()>=k){
        int nb=(b.back()>=0? -(b.back()/k): -b.back()/k+(-b.back()%k!=0? 1: 0));
        b.pb(nb);
    }
    vector<int> a;
    rep(i, 1, SZ(b)-1) a.pb(b[i]*k+b[i-1]);
    a.pb(b.back());
    cout<<a.size()<<"\n";
    for(auto e: a) cout<<e<<" ";
    puts("");
}

signed main(){
    solve();
    return 0;
}