문제 링크입니다: https://www.acmicpc.net/problem/15663
15663번: N과 M (9)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해야 한다.
www.acmicpc.net
기존 문제들과는 달리 해쉬맵을 써야 풀 수 있는 백트래킹 문제였습니다.
해쉬맵을 통해 해당 숫자가 몇 번 등장했는지 표시하고 최초 등장할 때만 v 벡터에 추가하면서 백트래킹을 적용하면 됐습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <map> | |
#include <algorithm> | |
using namespace std; | |
const int MAX = 8; | |
int N, M; | |
vector<int> v; | |
int visited[MAX]; | |
map<int, int> numberCnt; | |
void func(int idx, int cnt) | |
{ | |
if (cnt == M) | |
{ | |
for (int i = 0; i < M; i++) | |
{ | |
cout << v[visited[i]] << " "; | |
} | |
cout << "\n"; | |
return; | |
} | |
if (idx == N) | |
{ | |
return; | |
} | |
for (int i = 0; i < v.size(); i++) | |
{ | |
if (numberCnt[v[i]]) | |
{ | |
numberCnt[v[i]]--; | |
visited[idx] = i; | |
func(idx+1, cnt + 1); | |
numberCnt[v[i]]++; | |
} | |
} | |
} | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> N >> M; | |
for (int i = 0; i < N; i++) | |
{ | |
int num; | |
cin >> num; | |
if (!numberCnt.count(num)) | |
{ | |
numberCnt[num] = 1; | |
v.push_back(num); | |
} | |
else | |
{ | |
numberCnt[num]++; | |
} | |
} | |
sort(v.begin(), v.end()); | |
func(0, 0); | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 15665번 N과 M (11) (0) | 2019.10.22 |
---|---|
백준 15664번 N과 M (10) (0) | 2019.10.22 |
백준 15657번 N과 M (8) (0) | 2019.10.22 |
백준 15656번 N과 M (7) (2) | 2019.10.22 |
백준 10867번 중복 빼고 정렬하기 (0) | 2019.10.22 |