๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 2309 ์ผ๊ณฑ ๋‚œ์Ÿ์ด backtracking

by Jouureee 2021. 4. 6.

๋ฌธ์ œ :

www.acmicpc.net/problem/2309

 

2309๋ฒˆ: ์ผ๊ณฑ ๋‚œ์Ÿ์ด

์•„ํ™‰ ๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๋‚œ์Ÿ์ด๋“ค์˜ ํ‚ค๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ํ‚ค๋Š” 100์„ ๋„˜์ง€ ์•Š๋Š” ์ž์—ฐ์ˆ˜์ด๋ฉฐ, ์•„ํ™‰ ๋‚œ์Ÿ์ด์˜ ํ‚ค๋Š” ๋ชจ๋‘ ๋‹ค๋ฅด๋ฉฐ, ๊ฐ€๋Šฅํ•œ ์ •๋‹ต์ด ์—ฌ๋Ÿฌ ๊ฐ€์ง€์ธ ๊ฒฝ์šฐ์—๋Š” ์•„๋ฌด๊ฑฐ๋‚˜ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

 

๋ถ„์„ :

๋ธŒ๋ก ์ฆˆ์˜€์Œ์—๋„ ์–ด๋ ค์› ๋‹ค.. ์•ž์œผ๋กœ ๋ธŒ๋ฃจํŠธ ํฌ์Šค, ๋ฐฑํŠธ๋ž˜ํ‚น์ชฝ์„ ์ข€ ๋” ๊ณต๋ถ€ํ•ด ๋ณด์•„์•ผ๊ฒ ๋‹ค.

์ข…๋งŒ๋ถ์—์„œ ๋ณด์•˜๋˜ ์•„์ด๋””์–ด๋ฅผ ๊ฐ€์ง€๊ณ  ๋ฌธ์ œ ์ ‘๊ทผ์„ ํ•˜์˜€๋‹ค.

๊ฐ ๋‚œ์Ÿ์ด๋“ค์€ 100์„ ํฌํ•จํ•˜๋Š”๋ฐ ์†ํ•˜๊ฑฐ๋‚˜ ์•ˆ ์†ํ•˜๊ฑฐ๋‚˜ ๋‘˜์ค‘ ํ•˜๋‚˜์ด๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ๋ชจ๋“  ๋‚œ์Ÿ์ด๋“ค์„ ํƒ์ƒ‰ํ•˜๋Š”๋ฐ return ๋ฌธ์„ ๋งŒ๋‚˜ ์žฌ๊ท€๊ฐ€ ๋๋‚˜๊ฒŒ ๋˜๋ฉด visit๋ฅผ false๋กœ ํ•ด ์†ํ•˜์ง€ ์•Š๊ฒŒ๋” ๋งŒ๋“ค๊ณ  ๋‹ค๋ฅธ ์›์†Œ๋“ค์„ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์ด๋‹ค. 

์ด๋ ‡๊ฒŒ ํ•˜์—ฌ ์†ํ•˜๋Š” ์›์†Œ๋“ค๋งŒ์„ ์ •๋ ฌํ•ด ์ถœ๋ ฅํ•œ๋‹ค.

 

C++ ์ฝ”๋“œ :

//
//  2309_dwarf7.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/04/06.
//

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


using namespace std;
vector<int>arr;
vector<int>re_arr;

int visit[100];
int cnt = 0;

void brute_dwarf7(int score, int cnt){
    if (score == 100 and cnt == 7){
        sort(re_arr.begin(), re_arr.end());
        
        for(int i = 0; i < 7; i++){
            cout << re_arr.at(i) << "\n";
        }
        exit(0);
    }
    
    if (cnt > 7 || score > 100){
        return;
    }
    
    for(int i= 0; i <9; i++){
        if(visit[arr[i]] == false){
            visit[arr[i]] = true;
            re_arr.push_back(arr[i]);
            brute_dwarf7(score + arr[i], cnt + 1);
            visit[arr[i]] = false;
            re_arr.pop_back();
        }
    }
    return;

}

int main(){
    memset(visit, false, sizeof(visit));
    for(int i =0; i < 9; i++){
        int temp;
        cin >> temp;
        arr.push_back(temp);
    }
    brute_dwarf7(0, 0);
    
    return 0;
}

๋Œ“๊ธ€