happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

코딩테스트/C++ 문제풀이

[백준] N과 M (9)

2022. 12. 25. 21:43

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

 

15663번: N과 M (9)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

문제부터 요약하면, 

N개의 숫자가 주어질 때, 조건에 알맞게 M개를 뽑아서 사전순으로 출력해야 합니다.

이 문제의 조건은 중복되는 수열이 없도록 출력해야 하는 것이 조건이였습니다.

 

<Solution>

일반적인 DFS의 로직에서 used 배열을 두어서 각 숫자마다 사용 가능 횟수를 체크해서 사용 가능한 경우에만 상태 발전이 이루어지도록 하여 구현하였습니다.

 

실제 구현은 아래와 같습니다.

#include <iostream>
#include <algorithm>

using namespace std;

int N, M;
int num_array[10];
int num_array_[10];

int print_num[10];
int used[10000+10];

int cnt[10000+10];

int k;

void getinput(){
    cin >> N >> M;
    for(int i = 0; i<N; i++){
        cin >> num_array[i];
        cnt[num_array[i]]++;
    }
    // 중복제거
    sort(num_array, num_array+N);

    // first number just push

    num_array_[k] = num_array[k];
    k++;
    for(int i = 1; i<N; i++){
        if(num_array_[k-1] == num_array[i]) continue;

        num_array_[k] = num_array[i];
        k++;
    }

}

void dfs(int turn){

    // return 조건
    if(turn >= M){
        // print num 
        for(int i = 0; i<M; i++){
            cout << print_num[i] << ' ';
        }
        cout << endl;
        return;
    }

    // 상태발전
    for(int i = 0; i<k; i++){
        // 사용 더 못하는 경우 continue
        if(used[num_array_[i]] >= cnt[num_array_[i]]) continue;

        // 사용가능시 상태발전
        used[num_array_[i]]++;
        print_num[turn] = num_array_[i];
        dfs(turn+1);
        used[num_array_[i]]--;

    }

}

void solution(){

    dfs(0);


}

int main(){
    getinput();

    solution();

    return 0;


}
반응형

'코딩테스트 > C++ 문제풀이' 카테고리의 다른 글

[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal  (0) 2023.01.01
[LeetCode] 3Sum Closest  (0) 2022.12.31
[백준] Java vs C++  (0) 2022.12.18
[백준] N과 M (12)  (0) 2022.12.10
[백준] 마라톤 1  (0) 2022.12.01
    '코딩테스트/C++ 문제풀이' 카테고리의 다른 글
    • [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
    • [LeetCode] 3Sum Closest
    • [백준] Java vs C++
    • [백준] N과 M (12)
    happy318
    happy318

    티스토리툴바