Skip to content

Instantly share code, notes, and snippets.

@velicast
Created July 30, 2018 20:35
Show Gist options
  • Save velicast/4d99f9c26a33b541113af72d87869093 to your computer and use it in GitHub Desktop.
Save velicast/4d99f9c26a33b541113af72d87869093 to your computer and use it in GitHub Desktop.
Ordered Numbers en C++. Compile with g++ ordered.cpp -ansi -O3
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
// O(d) where d is the length of input_N
int firstIndexOfUnorderedPair(const string &input_N) {
for (int i = 0; i+1 < input_N.length(); i++) {
if (input_N[i] > input_N[i+1]) {
return i;
}
}
return input_N.length();
}
// O(d) where d is the length of input_N
long long getOrderedLowerBound(string &input_N) {
int unordered_index = firstIndexOfUnorderedPair(input_N);
if (unordered_index < input_N.length()) {
int current_index = input_N.length()-1;
input_N[unordered_index]--;
while (current_index > unordered_index) {
input_N[current_index--] = '9';
}
while (current_index > 0 && input_N[current_index-1] > input_N[current_index]) {
input_N[current_index--] = '9';
input_N[current_index]--;
}
}
return atol(input_N.c_str());
}
// O(d) where d is the length of input_N
void solveTest(int test) {
string input_N;
cin >> input_N;
cout << "Caso " << test << ": N=" << input_N;
long long ordered_N = getOrderedLowerBound(input_N);
cout << ", O=" << ordered_N << "\n";
}
// O(test_cases*max_d)
int main() {
// redirect standard streams
freopen("entrada.txt", "r", stdin);
freopen("salida.txt", "w", stdout);
// unbind iostream from stdio
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
int test_cases;
cin >> test_cases;
for (int test = 1; test <= test_cases; test++) {
solveTest(test);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment