【SPOJ】NPC2016C - Strange Waca

Waca loves maths,.. a lot. He always think that 1 is an unique number. After playing in hours, Waca suddenly realize that every integer can be represented by digit '1', plus operator and minus operator. For example, 1534 can be represented as 1111 + 1 + 111 + 111 - 11 - 11 + 111 + 111. In that case, there are total 7 operators (plus and minus).

Now, Waca wants to know, what is the minimum number of operators needed to achieve X

Input

First row is an integer T, the number of test cases.
Next T rows will each contain an integer, X, the number given to Waca

Output

For each test cases, print an integer, the minimum number of operators needed to achieve X.

[預設] cf[i] = 11...11 共i+1個1, "x的答案"指achieve x所需的最少運算符數量, "a到b的花費"指achieve |a-b|所需的最少運算符數量

[引理1] 最優解的算式中不可能同時出現"+cf[i]","-cf[i]"

[引理2] 對於任意的正整數b,a的答案≤b的答案+a到b的花費,且存在一個正整數c滿足a的答案=c的答案+a到c的花費

[引理3] 對於任意的正整數a,假設cf[i]≤a≤cf[i+1],如果a的答案不使用cf[j](j>i),那麼a的答案要麼正好有a/cf[i]個cf[i],要麼正好有a/cf[i]+1個cf[i]

引理1和引理2都非常顯然,現在我們來證明引理3.

考慮正整數a,cf[i]≤a≤cf[i+1],假設我們使用了正好k個cf[i]。如果k<\frac{a}{cf[i]},在a的最優分解算式 a=k*cf[i]+x_{i-1}*cf[i-1]+...中,兩邊減去k*cf[i],得到 a-k*cf[i]=x_{i-1}*cf[i-1]+... 此時a-k*cf[i]>cf[i],也就是說,在右邊我們要使x_{i-1}\geq 10來滿足等式,這顯然不是最優的方法,因爲cf[i] - 1 = cf[i-1]*10。對於k>\frac{a}{cf[i]}+1,我們可以類似的得到相同的結論。那麼我們就不那麼嚴謹地證明了引理3.

現在我們想到了一種方法:如果不考慮高位的cf[i],對於當前的每一位我們都最多有兩種填法,這樣,我們得到了一種O(X^{log_{10}2})的做法,符合數據範圍的要求。

代碼如下:

#include<bits/stdc++.h>
using namespace std;
long long cf[14]={1ll,11ll,111ll,1111ll,11111ll,111111ll,1111111ll,11111111ll,111111111ll,1111111111ll,11111111111ll,111111111111ll,1111111111111ll};
int dfs(int p, long long a){
    if(a == 0) return 0;
    if(p < 0) return 10086;
    int bes = 10086;
    bes = min(1ll * bes, dfs(p - 1, a - a/cf[p] * cf[p]) + a/cf[p]);
    bes = min(1ll * bes, dfs(p - 1, (a/cf[p] + 1) * cf[p] - a) + a/cf[p] + 1);
    return bes;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        long long a;
        cin>>a;
        cout << dfs(12,a) - 1 <<endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章