๋ฌธ์ œ


BOJ ๋งํฌ


ํ’€์ด

์‹œ๊ฐ„์—ฌํ–‰์„ ์‹œ์ž‘ํ•ด ๋‹ค์‹œ ์ถœ๋ฐœ์ ์œผ๋กœ ๋Œ์•„์™”์„ ๋•Œ, ์‹œ๊ฐ„์ด ๋˜๋Œ์•„๊ฐ„ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•ด์•ผ ํ•œ๋‹ค.

์‹œ๊ฐ„์„ ๊ฐ„์„ ์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์„ ๋•Œ, ์‹œ๊ฐ„ ์—ญํ–‰์„ ์Œ์˜ ๊ฐ€์ค‘์น˜๋กœ ๋‘๊ณ  ์Œ์˜ ์‚ฌ์ดํด์ด ์กด์žฌํ•˜๋ฉด ์‹œ๊ฐ„ ์—ฌํ–‰์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.


๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜์— ์Œ์ˆ˜๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ, ๋ฒจ๋งŒ ํฌ๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•ด ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

์šฐ์„  ๋ชจ๋“  ์ •์ ์˜ ์ตœ์†Œ ๋น„์šฉ์„ ์•Œ๊ธฐ ์œ„ํ•ด ๋ฐ˜๋ณต๋ฌธ์„ ๋‘ ๋ฒˆ ์‚ฌ์šฉํ•ด ๋ชจ๋“  ๊ฐ„์„ ์„ ํ™•์ธํ•œ๋‹ค.

๊ฐ„์„ ์„ ๋ชจ๋‘ ํƒ์ƒ‰ํ•œ ์ดํ›„, ๊ทธ๋ž˜ํ”„์— ์Œ์˜ ์‚ฌ์ดํด์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ„์„ ์„ ํ•œ ๋ฒˆ ๋” ํƒ์ƒ‰ํ•œ๋‹ค. ๋งŒ์•ฝ ์Œ์˜ ์‚ฌ์ดํด์ด ์กด์žฌํ•œ๋‹ค๋ฉด, ์ตœ์†Ÿ๊ฐ’์ด ๋‹ค์‹œ ๊ฐฑ์‹ ๋˜๋ฏ€๋กœ true๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.


์ฝ”๋“œ

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <vector>
using namespace std;

struct Edge
{
	int from, to, cost;
};

vector<Edge> graph;

bool bellmanFord(int n)
{
	vector<int> dist(n + 1, 1e9);
	dist[1] = 0;

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < graph.size(); j++)
		{
			int from = graph[j].from;
			int to = graph[j].to;
			int cost = graph[j].cost;

			if (dist[from] + cost < dist[to])
			{
				dist[to] = dist[from] + cost;
			}
		}
	}

	for (int i = 0; i < graph.size(); i++)
	{
		int from = graph[i].from;
		int to = graph[i].to;
		int cost = graph[i].cost;

		if (dist[to] > dist[from] + cost) return 1;
	}

	return 0;
}

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

	// test
	int test_case;
	cin >> test_case;

	for (int tc = 0; tc < test_case; tc++)
	{
		// input & init
		graph.clear();

		int n, m, w;
		cin >> n >> m >> w;

		for (int i = 0; i < m; i++)
		{
			int s, e, t;
			cin >> s >> e >> t;

			graph.push_back({ s, e, t });
			graph.push_back({ e, s, t });
		}

		for (int i = 0; i < w; i++)
		{
			int s, e, t;
			cin >> s >> e >> t;

			graph.push_back({ s, e, -t });
		}

		// solve
		if (bellmanFord(n)) cout << "YES\n";
		else cout << "NO\n";
	}

	return 0;
}



๊ฒฐ๊ณผ

image

Leave a comment