Cod sursa(job #3360593)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 15 iulie 2026 10:56:54
Problema Generare de permutari Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>

using namespace std;
int v[10];
void reverse(int v[], int st, int dr) {
    while (st <= dr) {
        swap(v[st], v[dr]);
        st++;
        dr--;
    }
}
bool next_permutation(int n) {
    if (n <= 1) {
        return false;
    }
    int i = n - 1;
    while (i >= 1 && v[i] >= v[i + 1]) {
        i --;
    }
    if (i < 1) {
        return false;
    }
    int j = n;
    while (j >= 1 && v[j] <= v[i]) {
        j --;
    }
    if (j < 1) {
        return false;
    }
    swap(v[i], v[j]);
    reverse(v, i + 1, n);
    return true;
}
int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    freopen("permutari.in", "r", stdin);
    freopen("permutari.out", "w", stdout);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        v[i] = i;
        cout << v[i] << " ";
    }
    cout << '\n';
    while (next_permutation(n) == true) {
        for (int i = 1; i <= n; i++) {
            cout << v[i] << " ";
        }
        cout << '\n';
    }
    return 0;
}