【Codeforces 1373E】Sum of Digits 贪心构造

题目链接:https://codeforces.ml/contest/1373/problem/E

题目大意:

定义一个f(x)为,x的数位和。

给出n,k,求最小的x使得f(x) + f(x+1) + f(x+k) == n

题目思路:

非常好的构造思路(看了榜一巨巨的

虽然思路和我略像,但我实现不出来,看完之后恍然大悟

首先确定一个性质:

对于任何一个数字来说,想要数位和最大的情况下最小,肯定会组成x9999的形式

根据这个性质我们去暴力构造这个数字

枚举所有的个位数字,所以答案一定为x999x的形式

所以变的只是中间有多少个9

所以枚举所有个位数字+枚举中间的9

这样就可以求出去除个位和中间的9的贡献,此时需要加上共有部分,所以剩下的数位和一定可以整除k+1

整除k+1

剩下之后首先看那个数字是否大于8,大于8首先把8放上

之后按照贪心继续9就可以了

此题的贪心性质:是在于要明白全选9会缩短数字长度,而在数字比较中长度是非常重要的

Code:

/*** keep hungry and calm CoolGuang!***/
#include <bits/stdc++.h>
#pragma GCC optimize(3)
//#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
#include<iostream>
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll INF=2e18;
const int maxn=1e6+6;
const int mod=1000000007 ;
const double eps=1e-15;
inline bool read(ll &num)
{char in;bool IsN=false;
    in=getchar();if(in==EOF) return false;while(in!='-'&&(in<'0'||in>'9')) in=getchar();if(in=='-'){ IsN=true;num=0;}else num=in-'0';while(in=getchar(),in>='0'&&in<='9'){num*=10,num+=in-'0';}if(IsN) num=-num;return true;}
ll n,m,p;
int s = 0;
ll num[maxn],dp[maxn];
ll F[maxn],b[maxn],a[maxn];
string cmp(string a,string b){
    if(a=="") return b;
    if(b=="") return a;
    if(a.size()<b.size()) return a;
    if(b.size()<a.size()) return b;
    if(a<b) return a;
    return b;
}
int main()
{
    int T;scanf("%d",&T);
    while(T--){
        read(n);read(m);
        string ans = "";
        for(int last = 0;last<=9;last++){
            for(int pre=0;pre<=19;pre++){
                string res;
                res += last + '0';
                for(int i=1;i<=pre;i++) res += '9';
                ll temp = n,cot = 0;
                for(int i=0;i<=m;i++){
                    temp -= (i+last)%10;
                    if(i+last > 9) cot++;
                }
                temp -= (m+1-cot)*9*pre;
                temp -= cot;
                if(temp < 0) continue;
                if(temp%(m+1) != 0) continue;
                temp/=m+1;
                if(temp>8){
                    res += '8';
                    temp -= 8;
                }
                while(temp>0){
                    res += '0'+min(temp,9ll);
                    temp -= 9;
                }
                reverse(res.begin(),res.end());
                ans =cmp(ans,res);
            }
        }
        if(ans=="") printf("-1\n");
        else  cout<<ans<<endl;
    }
    return 0;
}
/**

**/

猜你喜欢

转载自blog.csdn.net/qq_43857314/article/details/106976727