Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 완전탐색
- 구현
- dfs
- 시뮬레이션
- 투 포인터
- 유니온 파인드
- 수학
- 백트래킹
- 프로그래머스
- Kotlin
- 문자열
- 에라토스테네스의 체
- Network
- 후니의 쉽게 쓴 시스코 네트워킹
- 백준
- java
- CS
- 세그먼트 트리
- 이분탐색
- swea
- 플로이드-와샬
- JUnit 5
- 알고리즘
- mst
- 동적계획법
- 그리디
- Effective Java
- BFS
- 스택
- 위상정렬
Archives
반갑습니다!
[백준] 15663 N과 M (9) 본문
풀이
엄청 많은 시리즈가 있는 문제이다. N개의 자연수 중에서 M개를 고르는 것은 백트래킹을 사용해서 어렵지 않게 구현할 수 있다. 하지만 이 문제에는 중복이 발생하기 때문에 중복을 제거해야한다. 아래의 코드에서는 set을 사용해서 중복을 제거했는데, 수열을 string
으로 변환해서 set에 넣어주는 방식으로 구현했다. 또한 수열은 사전 순으로 출력해야하므로 맨 처음 입력받은 N개의 자연수를 정렬한 뒤 백트래킹했다.
코드
C++
This file contains hidden or 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 <algorithm> | |
#include <unordered_set> | |
using namespace std; | |
int n, m; | |
int num[10]; | |
bool chk[10]; | |
unordered_set<string> chk_set; | |
void dfs(int cnt, string s) { | |
if (cnt == m) { | |
if (chk_set.find(s) == chk_set.end()) { | |
cout << s << '\n'; | |
chk_set.insert(s); | |
} | |
return; | |
} | |
for (int i = 0; i < n; i++) { | |
if (!chk[i]) { | |
string tmp = s + to_string(num[i]); | |
tmp += ' '; | |
chk[i] = true; | |
dfs(cnt + 1, tmp); | |
chk[i] = false; | |
} | |
} | |
} | |
int main() { | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> n >> m; | |
for (int i = 0; i < n; i++) | |
cin >> num[i]; | |
sort(num, num + n); | |
dfs(0, ""); | |
return 0; | |
} |
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 2959 거북이 (0) | 2020.11.04 |
---|---|
[백준] 12096 (0) | 2020.11.04 |
[백준] 5557 1학년 (0) | 2020.11.01 |
[백준] 1644 소수의 연속합 (0) | 2020.10.23 |
[백준] 2631줄 세우기 (0) | 2020.10.22 |