백준 15686번 c++ : 치킨배달

Rena·2022년 12월 23일
0

알고리즘 문제풀이

목록 보기
34/45
#include <bits/stdc++.h>
using namespace std;

int n,m;
int board[50][50];
vector<pair<int,int>> house;
vector<pair<int,int>> chicken;

int main(void){ 
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            cin >> board[i][j];
            if(board[i][j]==1) house.push_back({i,j});
            if(board[i][j]==2) chicken.push_back({i,j}); 
        }
    }

    vector<int> brute(chicken.size(),1);
    fill(brute.begin(), brute.begin()+chicken.size()-m,0);
    int dist = 0x7f7f7f7f; //결과값
    do{
        int city = 0;
        for(auto h : house) {
            int hdist = 0x7f7f7f7f;
            for(int i=0; i<chicken.size(); i++) {
                if(brute[i]==0) continue;
                hdist = min(hdist, abs(h.first-chicken[i].first)+abs(h.second-chicken[i].second));    
            }
            city += hdist;
        }
        dist = min(dist, city);
    }while(next_permutation(brute.begin(),brute.end()));

    cout << dist;
}

brute라는 백터에 m개 치킨집을 1로 설정하고 나머지는 0으로 설정한 후 next_permutaion을 사용하면 중복되지 않는 치킨집 조합을 만들어 낼 수 있다.

profile
일을 사랑하고 싶은 개발자

0개의 댓글