codeforces Gym 100338E Numbers (贪心,实现)

本文介绍了一个CodeForces平台上的贪心算法题目解析,通过枚举不同规模的10的幂次,并利用补数原理来寻找最优解。文章详细展示了如何使用C++实现这一算法思路,并附带完整的代码实现。

题目:http://codeforces.com/gym/100338/attachments

贪心,每次枚举10的i次幂,除k后取余数r在用k-r补在10的幂上作为候选答案。

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxbit = 19;
ull base[maxbit], n, k;

void preDeal()
{
    base[0] = 1;
    for(int i = 1; i < maxbit; i++){
        base[i] = 10*base[i-1];
    }
}


void ull2str(ull x,string& s)
{
    int st[maxbit],top = 0;
    while(x){
        st[top++] = x%10+'0';
        x /= 10;
    }
    reverse(st,st+top);
    s.assign(st,st+top);
}

void work()
{
    priority_queue<string,vector<string>,greater<string> > q;
    int sz = maxbit-1;
    while(base[sz]>n) sz--;
    string str;
    for(int i = 0; i <= sz; i++){
        ull cur = base[i];
        ull r = cur%k;
        if(r != 0){
            cur += k-r;
        }
        if(cur <= n){
            ull2str(cur,str);
            q.push(str);
        }
    }
    printf("%s\n",q.top().c_str());
}

int main()
{
    freopen("numbers.in","r",stdin);
    freopen("numbers.out","w",stdout);
    preDeal();
    while(scanf("%I64u%I64u",&n,&k),n){
        work();
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/jerryRey/p/4748635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值