fork(1) download
  1. #include <algorithm>
  2. #include <exception>
  3. #include <iostream>
  4. #include <list>
  5.  
  6. int detach(std::list<int>& l)
  7. {
  8. if (l.size() < 2) {
  9. throw std::runtime_error("too short list");
  10. }
  11. auto it = std::is_sorted_until(l.begin(), l.end());
  12. if (it == l.end()) {
  13. throw std::runtime_error("already sorted list");
  14. }
  15. if (!std::is_sorted(it, l.end())) {
  16. throw std::runtime_error("not 'partially' sorted list");
  17. }
  18. if (std::prev(it) == l.begin() || *it < *std::prev(it, 2)) {
  19. auto res = *it;
  20. l.erase(it);
  21. return res;
  22. } else {
  23. auto res = *std::prev(it);
  24. l.erase(std::prev(it));
  25. return res;
  26. }
  27. }
  28.  
  29. void test(std::list<int> l)
  30. {
  31. try {
  32. std::cout << detach(l) << std::endl;
  33. if (!std::is_sorted(l.begin(), l.end())) {
  34. std::cout << "result not sorted\n";
  35. }
  36. } catch (const std::exception& e) {
  37. std::cout << e.what() << std::endl;
  38. }
  39.  
  40. }
  41.  
  42. int main()
  43. {
  44. test({1}); // too short list
  45. test({1, 2, 3}); // already sorted list
  46. test({1, 3, 2, 0}); // not partially sorted list
  47.  
  48. test({3, 1}); // 3 or 1 (currently 1)
  49. test({3, 1, 5}); // 1
  50. test({1, 4, 2, 10}); // 4 or 2 (currently 4)
  51. test({28, 144, 44, 52, 60}); // 144
  52. test({60, 68, 76, 84, 65, 100}); // 65
  53. }
  54.  
Success #stdin #stdout 0s 4364KB
stdin
Standard input is empty
stdout
too short list
already sorted list
not 'partially' sorted list
1
1
4
144
65