#include <bits/stdc++.h>
using namespace std;
vector<int> nextGreaterPermutation(vector<int> &A) {
int n = A.size(); // size of the array.
// Step 1: Find the break point:
int ind = -1; // break point
for (int i = n - 2; i >= 0; i--) {
if (A[i] < A[i + 1]) {
// index i is the break point
ind = i;
break;
}
}
// If break point does not exist:
if (ind == -1) {
// reverse the whole array:
reverse(A.begin(), A.end());
return A;
}
// Step 2: Find the next greater element
// and swap it with arr[ind]:
for (int i = n - 1; i > ind; i--) {
if (A[i] > A[ind]) {
swap(A[i], A[ind]);
break;
}
}
// Step 3: reverse the right half:
reverse(A.begin() + ind + 1, A.end());
return A;
}
int main()
{
vector<int> A = {2, 1, 5, 4, 3, 0, 0};
vector<int> ans = nextGreaterPermutation(A);
cout << "The next permutation is: [";
for (auto it : ans) {
cout << it << " ";
}
cout << "]n";
return 0;
}
CiNpbmNsdWRlIDxiaXRzL3N0ZGMrKy5oPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdmVjdG9yPGludD4gbmV4dEdyZWF0ZXJQZXJtdXRhdGlvbih2ZWN0b3I8aW50PiAmQSkgewogICAgaW50IG4gPSBBLnNpemUoKTsgLy8gc2l6ZSBvZiB0aGUgYXJyYXkuCgogICAgLy8gU3RlcCAxOiBGaW5kIHRoZSBicmVhayBwb2ludDoKICAgIGludCBpbmQgPSAtMTsgLy8gYnJlYWsgcG9pbnQKICAgIGZvciAoaW50IGkgPSBuIC0gMjsgaSA+PSAwOyBpLS0pIHsKICAgICAgICBpZiAoQVtpXSA8IEFbaSArIDFdKSB7CiAgICAgICAgICAgIC8vIGluZGV4IGkgaXMgdGhlIGJyZWFrIHBvaW50CiAgICAgICAgICAgIGluZCA9IGk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgIH0KCiAgICAvLyBJZiBicmVhayBwb2ludCBkb2VzIG5vdCBleGlzdDoKICAgIGlmIChpbmQgPT0gLTEpIHsKICAgICAgICAvLyByZXZlcnNlIHRoZSB3aG9sZSBhcnJheToKICAgIC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