순열조합 템플릿 구현

Nitroblue 1·어제

코딩 스킬들

목록 보기
16/16
#include <iostream>
#include <vector>

using namespace std;

#define PERMUTATION 1
#define REPEATED_PERMUTATION 2
#define COMBINATION 3
#define REPEATED_COMBINATION 4
#define RESET 5
#define QUIT -1

int n, r;
vector<bool> visited;
vector<int> selected;

void InitVisited() {
	for (int i = 1; i <= n; i++) visited[i] = false;
}

void Permutation(int depth) {
	if (depth == r) {
		for (int i = 0; i < r; i++) cout << selected[i] << ' ';
		cout << endl;
		return;
	}

	for (int i = 1; i <= n; i++) {
		if (visited[i]) continue;

		visited[i] = true;
		selected.push_back(i);
		Permutation(depth + 1);
		selected.pop_back();
		visited[i] = false;
	}
}

void RPermutation(int depth) {
	if (depth == r) {
		for (int i = 0; i < r; i++) cout << selected[i] << ' ';
		cout << endl;
		return;
	}

	for (int i = 1; i <= n; i++) {
		selected.push_back(i);
		RPermutation(depth + 1);
		selected.pop_back();
	}
}

void Combination(int start, int depth) {
	if (depth == r) {
		for (int i = 0; i < r; i++) cout << selected[i] << ' ';
		cout << endl;
		return;
	}

	for (int i = start; i <= n; i++) {
		selected.push_back(i);
		Combination(i + 1, depth + 1);
		selected.pop_back();
	}
}

void RCombination(int start, int depth) {
	if (depth == r) {
		for (int i = 0; i < r; i++) cout << selected[i] << ' ';
		cout << endl;
		return;
	}

	for (int i = start; i <= n; i++) {
		selected.push_back(i);
		RCombination(i, depth + 1);
		selected.pop_back();
	}
}

int main() {
	bool quit = false;
	bool reset = false;
	while (true) {
		cout << "n : ";
		cin >> n;
		visited.resize(n + 1);

		cout << "r : ";
		cin >> r;
		while (true) {
			cout << "1:p    2: rp    3:c    4:rc    5:reset r, c    -1:q" << endl;
			int op;
			cin >> op;
			if (op == QUIT) {
				quit = true;
				break;
			}
			if (op == RESET) {
				reset = true;
				break;
			}

			selected.clear();
			InitVisited();
			if (op == PERMUTATION) Permutation(0);
			if (op == REPEATED_PERMUTATION) RPermutation(0);
			if (op == COMBINATION) Combination(1, 0);
			if (op == REPEATED_COMBINATION) RCombination(1, 0);
		}
		if (quit) break;
		if (reset) reset = false;
	}

	return 0;
}

0개의 댓글