Codeforces 770B 思维

版权声明:欢迎转载,不要求署名~~~ https://blog.csdn.net/shadandeajian/article/details/82119016

传送门:题目

题意:

给一个数n,求 n的,所有数位相加最大的,如果多个数都是可行解,取值最大的作为最优解输出。

题解:

这题我第一开始WA了,看CF代码,发现少枚举了一种情况,最大值无非就是三种情况:

  • 首位不变,后面的都变成9
  • 首位减一,后面的都变成9
  • 首位不变,后面的其中一位是8,其余位都是9

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <sstream>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define int long long
using namespace std;

int n, first_digit, temp, mmax,kk;
string str;
stringstream ss;
signed main(void) {
    cin >> n;
    ss << n;
    ss >> str;
    first_digit = str[0] - '0';
    mmax = first_digit;
    for (int i = 1; i < (int)str.size(); i++)//第一种情况
        mmax = mmax * 10 + 9;
    if (mmax <= n) {
        cout << mmax;
        return 0;
    }
    int mmax = first_digit - 1;
    for (int i = 1; i < (int)str.size(); i++)//第二种情况
        mmax = mmax * 10 + 9;
    for (int i = 1; i < (int)str.size(); i++)//第三种情况
        str[i] = '9';
    for (int i = 1; i < (int)str.size(); i++) {
        str[i] = '8';
        ss.clear();
        ss << str;
        ss >> temp;
        if (temp <= n)
            mmax = max(temp, mmax);
        str[i] = '9';
    }
    cout << mmax << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/82119016
今日推荐