Cod sursa(job #233186)

Utilizator stef2nStefan Istrate stef2n Data 17 decembrie 2008 00:37:58
Problema Generare de permutari Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.89 kb
//  Testing my next permutation

#include <stdio.h>

int N, P[8];

void swap(int *x, int *y) {
    *x ^= *y ^= *x ^= *y;
}

int my_next_permutation() {
    int pos = N - 1, backup;

    for(; pos > 0 && P[pos] < P[pos - 1]; --pos);
    backup = pos;

    if(!pos)
        return 0;

    for(; pos < N; ++pos)
        if(P[pos] < P[backup - 1])
            break;
    --pos;
    swap(&P[pos], &P[backup - 1]);

    pos = backup;
    int pos2 = N - 1;
    while(pos < pos2)
        swap(&P[pos++], &P[pos2--]);

    return 1;
}


int main() {
    freopen("permutari.in", "r", stdin);
    freopen("permutari.out", "w", stdout);

    int i;
    scanf("%d", &N);
    for(i = 0; i < N; ++i) {
        P[i] = i + 1;
        printf("%d ", P[i]);
    }
    printf("\n");

    while(my_next_permutation()) {
        for(i = 0; i < N; ++i)
            printf("%d ", P[i]);
        printf("\n");
    }

    return 0;
}