Cod sursa(job #2202610)

Utilizator Steff94Stefan Steff94 Data 9 mai 2018 15:33:56
Problema Generare de permutari Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include<iostream>
#include<fstream>
#define MAX 9
using namespace std;

ifstream f("permutari.in");
ofstream g("permutari.out");

int check(int *s, int k) { //checking if the elements of an array are all distinct
	for (int i = 1; i <= k - 1; i++)
		for (int j = i + 1; j <= k; j++)
			if (s[i] == s[j])
				return 0;
	return 1;
}

int solution(int *s, int k, int N) { //if we have reached N numbers it's a solution
	if (k == N)
		return 1;
	return 0;
}

void print_solution(int *s, int N) { //print the permutation
	for (int i = 1; i <= N; i++)
		g << s[i] << " ";
	g << endl;
}

void permutation_bkt(int *s, int k, int N) { //backtracking permutations
	for (int i = 1; i <= N; i++) {
		s[k] = i;
		if (check(s, k)) {
			if (solution(s, k, N)) {
				print_solution(s, N);
			}
			else {
				permutation_bkt(s, k+1, N);
			}
		}
	}
}

int main() {
	int s[MAX], k = 1;
	int N; f >> N;
	permutation_bkt(s, k, N);

	f.close();
	g.close();
	return 0;
}