๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Baekjoon] 10971๋ฒˆ ์™ธํŒ์› ์ˆœํšŒ2

ibelieveinme 2022. 5. 8. 10:57
728x90

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

 

10971๋ฒˆ: ์™ธํŒ์› ์ˆœํšŒ 2

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 10) ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๋น„์šฉ ํ–‰๋ ฌ์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ–‰๋ ฌ์˜ ์„ฑ๋ถ„์€ 1,000,000 ์ดํ•˜์˜ ์–‘์˜ ์ •์ˆ˜์ด๋ฉฐ, ๊ฐˆ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๋Š” 0์ด ์ฃผ์–ด์ง„๋‹ค. W[i][j]๋Š” ๋„์‹œ i์—์„œ j

www.acmicpc.net


#include <iostream>
#include <vector>
#include <climits>
using namespace std;

void SearchCity(int startCity, int currentCity, int costSum, int count, vector<vector<int>> visitedCityArr, vector<bool> visitedCityVector);
int leastCost = INT_MAX;

int main() {
    int cityNum, input;
    cin >> cityNum;

    vector<vector<int>> cityVector(cityNum, vector<int>(cityNum, 0));
    vector<bool> visitedCityArr(cityNum, false);

    for (int i = 0; i < cityNum; i++) {
        for (int j = 0; j < cityNum; j++) {
            cin >> cityVector[i][j];
        }
    }

    //ํƒ์ƒ‰ gogo
    for (int city = 0; city < cityNum; city++) {
        SearchCity(city, city, 0, 0, cityVector, visitedCityArr);
    }
    cout << leastCost;

    //๋™์ ํ• ๋‹น ํ•ด์ œ
    for (int i = 0; i < cityNum; i++) {
        cityVector[i].clear();
    } cityVector.clear();
    visitedCityArr.clear();

    return 0;
}

void SearchCity(int startCity, int currentCity, int costSum, int count, vector<vector<int>> cityVector, vector<bool> visitedCityVector) {
    if (currentCity == startCity && count == cityVector.size()) {
        if (leastCost > costSum) leastCost = costSum;
        return;
    }
    for (int nextCity = 0; nextCity < cityVector.size(); nextCity++) {
        if (cityVector[currentCity][nextCity] != 0 && !visitedCityVector[currentCity]) {
            visitedCityVector[currentCity] = true;
            costSum += cityVector[currentCity][nextCity];

            if (leastCost >= costSum) SearchCity(startCity, nextCity, costSum, count + 1, cityVector, visitedCityVector);

            visitedCityVector[currentCity] = false;
            costSum -= cityVector[currentCity][nextCity];
        }
    }
}
728x90