Codeforces1560 D. Make a Power of Two(思维+暴力)

Posted live4m

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces1560 D. Make a Power of Two(思维+暴力)相关的知识,希望对你有一定的参考价值。

题意:

解法:

2的倍数只有log种,
因此枚举2的倍数t,计算出n变成t至少需要多少次操作即可,
计算过程很简单,从高到低遍历n的数位,用来匹配t的从高到低的数位,
能匹配则匹配,不能用就必须删掉,
如果最后还是不能匹配玩,那么需要在使用加数操作.

对计算出来的数取min就是答案.

code:

#include<bits/stdc++.h>
#define int long long
using namespace std;
vector<int>temp;
int n;
int check(int x){
    stack<int>s;
    while(x){
        s.push(x%10);
        x/=10;
    }
    int ans=0;
    for(auto i:temp){
        if(s.size()&&i==s.top()){
            s.pop();
        }else{
            ans++;
        }
    }
    ans+=s.size();
    return ans;
}
void solve(){
    cin>>n;
    map<int,int>mp;
    int x=n;
    temp.clear();
    while(x){
        temp.push_back(x%10);
        x/=10;
    }
    reverse(temp.begin(),temp.end());
    int ans=1e9;
    for(int i=1;i<=1e18;i*=2){
        ans=min(ans,check(i));
    }
    cout<<ans<<endl;
}
signed main(){
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif
    ios::sync_with_stdio(0);cin.tie(0);
    int T;cin>>T;while(T--)
        solve();
    return 0;
}

以上是关于Codeforces1560 D. Make a Power of Two(思维+暴力)的主要内容,如果未能解决你的问题,请参考以下文章