๋ฌธ์ œ


BOJ ๋งํฌ





ํ’€์ด

ํ”Œ๋กœ์ด๋“œ-์›Œ์…œ ๋ฌธ์ œ๋‹ค.


3์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ํ™œ์šฉํ•ด ๋ชจ๋“  ๋…ธ๋“œ์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•œ ํ›„, kb ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด ๊ฐ ๋…ธ๋“œ์˜ ์ผ€๋นˆ-๋ฒ ์ด์ปจ ์ˆ˜๋ฅผ ์ €์žฅํ–ˆ๋‹ค.


๋ชจ๋“  ๋…ธ๋“œ์˜ ๊ฐ€์ค‘์น˜๋ฅผ kb์— ๋”ํ•˜๋ฉด ์ž๊ธฐ ์ž์‹ ๋„ ํ•จ๊ป˜ ๊ณ„์‚ฐ๋˜๋ฏ€๋กœ ๋ฐ˜๋ณต๋ฌธ ํ›„์—ด์— fw[i][i] ๋…ธ๋“œ๋งŒํผ ๋นผ์ค€๋‹ค.



์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

int fw[101][101];
int kb[101] = { 0, };

int floydWarshall(int n)
{
	for (int k = 1; k <= n; k++)
	{
		for (int i = 1; i <= n; i++)
		{
			for (int j = 1; j <= n; j++)
			{
				fw[i][j] = min(fw[i][j], fw[i][k] + fw[k][j]);
			}
		}
	}

	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			kb[i] += fw[i][j];
		}
		kb[i] -= fw[i][i];
	}

	int ans, min = 1e9;
	for (int i = 1; i <= n; i++)
	{
		if (kb[i] < min)
		{
			min = kb[i];
			ans = i;
		}
	}

	return ans;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	// input & init
	int n, m;
	cin >> n >> m;

	fill(&fw[0][0], &fw[n][n+1], 1e9);

	for (int i = 0; i < m; i++)
	{
		int a, b;
		cin >> a >> b;
		fw[a][b] = 1;
		fw[b][a] = 1;
	}

	// solve
	cout << floydWarshall(n);

	return 0;
}



๊ฒฐ๊ณผ

image

Leave a comment