1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <algorithm>
#include <iostream>
template<typename T>
bool solveableSequence(const T& container) {
if (container.size() <= 1) {
return true;
}
const auto begin = std::begin(container);
auto last = begin;
std::size_t operations = 0;
for (auto iter = last, end = std::prev(std::end(container)); iter != end;) {
auto next = std::next(iter);
if (!(*last < *next)) { //< is for strict ascending, <= is for loose ascending
if (operations) {
return false;
}
++operations;
if (last != begin) {
auto prev = std::prev(last);
if (*prev < *next) {
last = next;
}
}
else if (*next < *last) {
last = next;
}
}
else {
last = next;
}
iter = next;
}
return operations <= 1; // <= for already sorted data;
}
template<typename T>
void solveSequence(const T& container) {
std::cout << std::boolalpha << solveableSequence(container) << std::endl;
}
using initList = std::initializer_list<int>;
int main() {
solveSequence(initList{1, 2, 1, 2});
solveSequence(initList{8, 8, 8, 7, 7, 7});
solveSequence(initList{1, 2, 2, 3});
solveSequence(initList{1, 2, 3, 2, 3});
solveSequence(initList{1, 2, 3, 2, 4});
solveSequence(initList{1, 2, 3, 6, 5});
solveSequence(initList{9, 8, 7});
solveSequence(initList{1, 2, 3, 6, 5, 4});
solveSequence(initList{1, 2, 5, 3, 5});
solveSequence(initList{40, 50, 60, 10, 20, 30});
solveSequence(initList{5, 1, 5, 7});
}
| |