Codeforces Round #739 (Div. 3),D

博客介绍了如何通过预处理2的幂次数并利用动态规划策略,找到将给定整数转换为2的幂次最少的操作次数。程序涉及字符串处理和最优化问题解决技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. Make a Power of Two

题意:
给定一个整数n,对它可以进行下面2种操作
1.删除一个数字
2.添加一个数字

求把它变成一个2的整数次幂最少操作次数

思路:
首先n的范围是1e9,所以最多涉及到的,也就10多位,完全可以先把2的整数次幂预处理出来,然后统计这个数变成其中每一个数字需要的次数,取一个最小值

#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

const int N = 1e7;
long long M = 1e9 + 10;
vector<string> s;
int a[11],b[11];

void init()
{
    for(int i = 0;i < 64;i ++)
    {
        long long x = pow(2,i);
        string t = to_string(x);
        s.push_back(t);
    }
}

int main()
{
    init();
    int t;
    cin >> t;
   // for(auto x:s) cout << x << endl;
    while(t --)
    {
        string c;
        cin >> c;
        int res = 0x3f3f3f3f;
        for(auto x:s)
        {
            int ans = 0;
            int cnt = 0;
            for(int i = 0,j = 0;i < x.size();i ++)
            {
                while(j < c.size() && c[j] != x[i]) j ++;
                if(c[j] == x[i]) cnt ++;
                else break;
                j ++;
            }
                    
            ans = c.size() - cnt;
            if(cnt < x.size()) ans += x.size() - cnt;
            res = min(res,ans);
            //if(c == "301" && res == 1) cout << x << endl;
        }
        cout << res << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值