반응형
https://www.acmicpc.net/problem/15666
문제 해결 알고리즘
전형적인 dfs를 활용한 백트래킹 문제. 비내림차순일 때 출력해주는 것만 유의하면 된다.
소스 코드
#include <bits/stdc++.h>
using namespace std;
int N, M;
int arr[9];
vector<int> v;
map<int,int> numberCnt;
bool flag(){
for(int i=0;i<M-1;i++){
if(arr[i] > arr[i+1]) return false;
}
return true;
}
void dfs(int n){
if(n == M){
if(flag()){
for(int i=0;i<M;i++){
cout << arr[i] << ' ';
}
cout << '\n';
}
return;
}
for(int j=0;j<v.size();j++){
arr[n] = v[j];
dfs(n+1);
}
}
int main(){
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());
dfs(0);
}
메모
if문 작성할 때 순서에 유의해야한다.
if(n == M){
if(flag()){
for(int i=0;i<M;i++){
cout << arr[i] << ' ';
}
cout << '\n';
}
return;
}
if(n == M && flag()){
for(int i=0;i<M;i++){
cout << arr[i] << ' ';
}
cout << '\n';
}
return;
두 개의 코드는 차이는 엄청난 차이였다..
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[구현] BOJ 2004 조합 0의 개수 (0) | 2021.09.29 |
---|---|
[자료구조, 맵] BOJ 1620 나는야 포켓몬 마스터 이다솜 (0) | 2021.09.23 |
[자료구조, 스택] BOJ 1874 스택 수열 (0) | 2021.09.11 |
[플로이드-와샬] BOJ 11404 플로이드 (0) | 2021.09.10 |
[그래프 이론] BOJ 1197 최소 스패닝 트리 (0) | 2021.09.10 |