Created
March 11, 2017 14:44
-
-
Save Acarus/74ec6311ce8db976b0d21d76a55b6d47 to your computer and use it in GitHub Desktop.
B. Максимизируй сумму цифр
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
using ll = long long; | |
ll GetNum(vector<int>& digits) { | |
while (!digits.empty() && digits[0] == 0) digits.erase(begin(digits)); | |
ll ans = 0; | |
for (auto digit: digits) ans = ans * 10 + digit; | |
return ans; | |
} | |
ll GetSum(vector<int>& digits) { | |
ll ans = 0; | |
for (auto x: digits) ans += x; | |
return ans; | |
} | |
vector<int> ToDigits(ll num) { | |
vector<int> digits; | |
while (num != 0) { | |
digits.push_back(num % 10); | |
num /= 10; | |
} | |
if (digits.empty()) digits.push_back(0); | |
reverse(begin(digits), end(digits)); | |
return digits; | |
} | |
int main(int argc, char **argv) { | |
ios::sync_with_stdio(false); | |
srand(time(0)); | |
ll n; | |
cin >> n; | |
vector<int> digits = ToDigits(n); | |
ll max_sum = GetSum(digits); | |
ll ans = n; | |
for (int i = (int) digits.size() - 1; i > 0; --i) { | |
if (digits[i] == 9) continue; | |
int to = i - 1; | |
while (to >= 0 && digits[to] == 0) digits[to--] = 9; | |
if (to < 0) break; | |
--digits[to]; | |
digits[i] = 9; | |
if (GetSum(digits) > max_sum) { | |
max_sum = GetSum(digits); | |
ans = GetNum(digits); | |
} | |
} | |
cout << ans << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment