Cod sursa(job #2093807)

Utilizator arcoC. Nicolae arco Data 24 decembrie 2017 14:48:35
Problema Generare de permutari Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.22 kb
#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);
			}
		}
	}
}