Little Jay

[C++] 백준 10552번 - DOM 본문

알고리즘/BOJ

[C++] 백준 10552번 - DOM

Jay, Lee 2022. 5. 3. 17:41

인접행렬로 문제를 푸는 것을 선호하는데,

이렇게 인접 리스트로 푸는게 오랜만이라 시간이 좀 걸렸다.

항상 느끼는 거지만 인접행렬이 더 편한 것 같다. 

#include <bits/stdc++.h>
#define endl '\n'
#define MAX 100005
using namespace std;

int n, m, init;

vector<int> v[MAX];
bool visited[MAX];

int solve() {
	int cnt = 0;
	queue<int> q;
	q.push(init);
	visited[init] = true;

	while (!q.empty()) {
		auto current = q.front(); q.pop();

		if (!v[current].size()) {
			return cnt;
		}
		if (visited[v[current][0]]) break;

		q.push(v[current][0]);
		visited[v[current][0]] = true;
		cnt++;
	}
	return -1;
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> n >> m >> init;
	for (int i = 0; i < n; i++) {
		int l, h; cin >> l >> h;
		v[h].push_back(l);
	}

	cout << solve() << endl;

	return 0;
}
Comments