b_51_凑数字(小思维+贪心)

给定一个n,要求找出一个最短的字符串S的长度,使得所有1到n的整数都是S的子序列。
比如n=10,那么S=”1234056789”的时候,是满足条件的。这个时候S的长度是10。

思路

  • 对于1位数的数字x:至少需要长度为x的字符串(比如x=8,需要表示1~8之间的数字,则为12345678)
  • 特殊情况:最高为数字比非最高位大时,看下图
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
    std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    string s; cin>>s;
    ll n=s.size(), ans=10*(n-1)+(s[0]-'1'), add=1; //add判断是否需要添加一位,只要全部数位上的数字相同就需要额外增加一位
    for (int i=1; i<n; i++) {
        if (s[i-1]<s[i]) break;
        if (s[i-1]>s[i]) {add=0; break;}
    }
    cout<<ans+add;
    return 0;
}
原文地址:https://www.cnblogs.com/wdt1/p/13861993.html