Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 15654] N과 M(5) (C++) 본문

Problem Solving

[BOJ 15654] N과 M(5) (C++)

흑개 2021. 10. 28. 00:55

https://www.acmicpc.net/problem/15654

 

15654번: N과 M (5)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

vector<int> v;
vector<vector<int>> ans;
int N, M, x;
bool check[9] = { false, };

void dfs(int cnt, vector<int> &c) {
	if (cnt == M) {
		ans.push_back(c);
		return;
	}
	for (int i = 0; i < N; i++) {
		if (!check[i]) {
			c.push_back(v[i]);
			check[i] = true;
			dfs(cnt + 1, c);
			check[i] = false;
			c.pop_back();
		}
	}
}

int main() {
	cin >> N >> M;
	vector<int> temp;
	for (int i = 0; i < N; i++) {
		cin >> x;
		v.push_back(x);
	}
	sort(v.begin(), v.end());
	dfs(0, temp);
	for (int i = 0; i < ans.size(); i++) {
		for (int j = 0; j < M; j++) {
			cout << ans[i][j] << " ";
		}
		cout << "\n";
	}
	return 0;
}

vector를 파라미터로 전달하는 것보다는 더 간단한 방법은 배열을 하나 만들어서, cnt를 인덱스로 삼아 거기다가 숫자를 넣어줘서 cnt==M 이면 그 배열을 출력하는 것이다. 그러면 자동 갱신될 수 있다!