Pagini recente » Cod sursa (job #1697881) | Cod sursa (job #1076759) | Cod sursa (job #2260672) | Cod sursa (job #2325151) | Cod sursa (job #2093807)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
typedef unsigned int uint;
void backtrack(uint *stiva, uint nivel, uint n, FILE *out);
void tipar(uint *stiva, uint nivel, FILE *out);
bool valid(uint *stiva, uint nivel, uint last);
int main(void)
{
FILE *in = fopen("permutari.in", "r");
FILE *out = fopen("permutari.out", "w");
if(in != NULL && out != NULL)
{
uint n;
fscanf(in, "%u%*c", &n);
uint stiva[10];
backtrack(stiva, 0, n, out);
fclose(in);
fclose(out);
}
else
{
printf("Error\n");
}
return 0;
}
bool valid(uint *stiva, uint nivel, uint last)
{
uint i = 0;
for(; i < nivel; i++)
{
if(stiva[i] == last)
{
return false;
}
}
return true;
}
void tipar(uint *stiva, uint nivel, FILE *out)
{
uint i = 0;
for(; i <= nivel; i++)
{
fprintf(out, "%u ", stiva[i]);
}
fprintf(out, "\n");
}
void backtrack(uint *stiva, uint nivel, uint n, FILE *out)
{
uint i = 1;
for(; i <= n; i++)
{
stiva[nivel] = i;
if(valid(stiva, nivel, i))
{
if(nivel == (n - 1))
{
tipar(stiva, nivel, out);
}
else
{
backtrack(stiva, nivel + 1, n, out);
}
}
}
}