๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 1389๋ฒˆ - ์ผ€๋นˆ ๋ฒ ์ด์ปจ์˜ 6๋‹จ๊ณ„ ๋ฒ•์น™

by dkswnkk 2021. 11. 6.
 

1389๋ฒˆ: ์ผ€๋นˆ ๋ฒ ์ด์ปจ์˜ 6๋‹จ๊ณ„ ๋ฒ•์น™

์ฒซ์งธ ์ค„์— ์œ ์ €์˜ ์ˆ˜ N (2 ≤ N ≤ 100)๊ณผ ์นœ๊ตฌ ๊ด€๊ณ„์˜ ์ˆ˜ M (1 ≤ M ≤ 5,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์—๋Š” ์นœ๊ตฌ ๊ด€๊ณ„๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์นœ๊ตฌ ๊ด€๊ณ„๋Š” A์™€ B๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, A์™€ B๊ฐ€ ์นœ๊ตฌ๋ผ๋Š” ๋œป

www.acmicpc.net

#include <iostream>
#include <vector>
#include <algorithm>
#define INF 1e9    //๋ฌดํ•œ๋Œ€๋ฅผ ์˜๋ฏธํ•˜๋Š” ๊ฐ’์œผ๋กœ 10์–ต์„ ์ง€์ •
using namespace std;
int N, M; //N=์œ ์ €์˜ ์ˆ˜, M=์นœ๊ตฌ ๊ด€๊ณ„ ์ˆ˜
int graph[101][101];
int main() {
    cin >> N >> M;

    for (int i = 0; i < 101; i++) {    
        fill(graph[i], graph[i] + 101,INF);    //๋ฌดํ•œ๋Œ€๋กœ ์ดˆ๊ธฐํ™”    
    }

    for (int a = 1; a <= N; a++) {
        for (int b = 1; b <= N; b++) {
            if (a == b) graph[a][b] = 0;    //์ž๊ธฐ ์ž์‹ ์œผ๋กœ ํ†ตํ•˜๋Š” ๊ฒƒ์€ 0
        }
    }

    for (int i = 1; i <= M; i++) {    //์นœ๊ตฌ ๊ด€๊ณ„ ์ž…๋ ฅ. ํ•œ๋‹ค๋ฆฌ์”ฉ ๊ฑด๋„๋•Œ 1์”ฉ ์ฆ๊ฐ€
        int a, b; cin >> a >> b;
        graph[a][b] = 1;
        graph[b][a] = 1;    //์–‘๋ฐฉํ–ฅ์ฒ˜๋ฆฌ.
    }

    for (int k = 1; k <= N; k++) {    //ํ”Œ๋กœ์ด๋“œ-์™€์ƒฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜ํ–‰
        for (int a = 1; a <= N; a++) {
            for (int b = 1; b <= N; b++) {
                graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b]);
            }
        }
    }    
    vector<int>kevin(N+1);    //์ผ€๋นˆ๋ฒ ์ด์ปจ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ํ…Œ์ด๋ธ”
    kevin[0] = INF;
    for (int a = 1; a <= N; a++) {
        for (int b = 1; b <= N; b++) {
            if(graph[a][b]==INF)continue;
            kevin[a] += graph[a][b];    //๊ฐ ์‚ฌ๋žŒ๋งˆ๋‹ค ๋‹ค๋ฅธ์‚ฌ๋žŒ์—๊ฒŒ ๊ฐˆ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๋”ํ•ด์ค€๋‹ค.
        }
    }

    int min_index = min_element(kevin.begin(), kevin.end()) - kevin.begin();    //์ผ€๋นˆ๋ฒ ์ด์ปจ ์ˆ˜๊ฐ€ ๊ฐ€์žฅ ์ ์€ ์‚ฌ๋žŒ์„ ์ถœ๋ ฅํ•œ๋‹ค.
    cout << min_index;


}

๋Œ“๊ธ€