Pagini recente » Cod sursa (job #1329198) | Cod sursa (job #1462120) | Cod sursa (job #720416) | Cod sursa (job #1919809) | Cod sursa (job #233186)
Cod sursa(job #233186)
// 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;
}