BOJ ๋งํฌ



๋ฌธ์ œ

image



ํ’€์ด

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


graph[i][k]์™€ graph[k][j]์˜ ๊ฐ„์„ ์ด ์กด์žฌํ•˜๋ฉด, graph[i][j]์˜ ๊ฐ„์„  ์—ญ์‹œ ์กด์žฌํ•œ๋‹ค. => ํ”Œ๋กœ์ด๋“œ-์›Œ์…œ์˜ ๊ธฐ๋ณธ ์•Œ๊ณ ๋ฆฌ์ฆ˜!


๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์ถœ๋ฐœ์ ์œผ๋กœ ์‚ผ๊ณ , ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋„์ฐฉ ๋…ธ๋“œ๋กœ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋ฏ€๋กœ, 3์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•œ๋‹ค.

cf) ๋‹ค์ต์ŠคํŠธ๋ผ/๋ฒจ๋งŒํฌ๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ํ•œ ๋…ธ๋“œ์—์„œ ๋ชจ๋“  ๋…ธ๋“œ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•œ๋‹ค.


์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” $O(n^{3})$์ด๋‹ค. ๊ทธ๋ž˜ํ”„๊ฐ€ ์ถฉ๋ถ„ํžˆ ์ž‘์„ ๊ฒฝ์šฐ ์‚ฌ์šฉํ•˜์ž!



์ฝ”๋“œ

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
#include <iostream>

int graph[101][101];

int main()
{
	// init & input
	int n;
	std::cin >> n;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			std::cin >> graph[i][j];
		}
	}

	// floyd-warshall
	for (int k = 0; k < n; k++)
	{
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (graph[i][k] && graph[k][j]) graph[i][j] = 1;
			}
		}
	}

	// output
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			std::cout << graph[i][j] << " ";
		}
		std::cout << "\n";
	}

	return 0;
}

Leave a comment