백준 문제/백트래킹

[백준] 15664번 N과 M(10)

dubu0721 2025. 1. 29. 14:07

문제: 15664번: N과 M (10)

basic-algo-lecture/workbook/0x0C.md at master · encrypted-def/basic-algo-lecture

 

basic-algo-lecture/workbook/0x0C.md at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

 

#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iomanip> // setprecision을 사용하기 위한 헤더
#include <climits>
#include <list>

using namespace std;

int n, m;
int curNums[8]; // max 가 8
int nums[8]; // max 가 8
int used[8]; // 해당 인덱스 사용 여부(숫자 중복 허용)


void Funct(int functM, int prev) {
	if (m == functM) {
		for (int i = 0; i < m; i++)
			cout << curNums[i] << " ";
		cout << "\n";
		return;
	}

	set<int> curUseNums; // 현재 단계에서 다음 단계로 갈 때 쓴 애들 목록(목록에 있으면 안 쓸 것)
	
	// 아직 수열이 다 안 찼으면 재귀..
	for (int i = 0; i < n; i++) {
		// 만약 집합에 있으면 패스
		// 또는 해당 인덱스 요소를 이미 사용했으면 패스
		if (used[i] == 1 || curUseNums.find(nums[i]) != curUseNums.end()) continue;

		// 수열은 오름차순이어야 하므로 이전 값이 현재 값보다 크다면 패스!
		if (prev > nums[i]) continue;

		used[i] = 1; // 해당 인덱스 요소 사용 표시
		curNums[functM] = nums[i];
		curUseNums.insert(nums[i]); // 집합에 넣기

		Funct(functM + 1, nums[i]);

		used[i] = 0; // 해당 인덱스 요소 사용 표시 없애기
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> n >> m;
	for (int i = 0; i < n; i++)
		cin >> nums[i];
	sort(nums, nums + n); // 오름차수 정렬

	Funct(0, 0);

	return 0;
}

 

음.. N과 M(9) 번 문제 풀이에서 수열만 오름차순으로 구성되도록 수정해주면 된다.

 

수열이 오름차순으로 구성되려면 현재 curNums 의 맨 뒤에 있는 값보다 지금 넣으려는 값이 크면 되는데 이를 위해 Funct 메서드에 매개변수로 현재 단계에서 curNums 의 맨 뒤 요소값을 전달하도록 했다.

 

 

 

참고자료:

BaaaaaaaarkingDog | [실전 알고리즘] 0x0C강 - 백트래킹

 

[실전 알고리즘] 0x0C강 - 백트래킹

이번에는 백트래킹을 배워보도록 하겠습니다. 백트래킹도 재귀와 더불어 많은 사람들이 고통을 호소하는 알고리즘 중 하나이지만 의외로 그 재귀적인 구조에 매료되어서 참재미를 알아버리는

blog.encrypted.gg