반응형

https://www.acmicpc.net/problem/5214

 

5214번: 환승

첫째 줄에 역의 수 N과 한 하이퍼튜브가 서로 연결하는 역의 개수 K, 하이퍼튜브의 개수 M이 주어진다. (1 ≤ N ≤ 100,000, 1 ≤ K, M ≤ 1000) 다음 M개 줄에는 하이퍼튜브의 정보가 한 줄에 하나씩 주어

www.acmicpc.net

 

역 뿐만 아니라, 하이퍼튜브도 하나의 정점으로 보고 그래프 형태를 만들어주었습니다.

BFS를 수행하며 역의 개수만 세어주면 됩니다.

 

#include <iostream>
#include <vector>
#include <queue>
#define TUBE 100001
using namespace std;

int n, k, m, a;
vector<int> graph[101001];
bool visit[101001] = { false };

int bfs() {
	queue<pair<int, int>> q;
	q.push({1, 1});
	visit[1] = true;
	while (!q.empty()) {
		int x = q.front().first;
		int c = q.front().second;
		q.pop();
		if (x == n) return c;
		for (int i = 0; i < graph[x].size(); i++) {
			if (visit[graph[x][i]]) continue;
			visit[graph[x][i]] = true;
			q.push({ graph[x][i], c + (x < TUBE) });
		}
	}
	return -1;
}

int main() {
	scanf("%d %d %d", &n, &k, &m);
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < k; j++) {
			scanf("%d", &a);
			graph[TUBE + i].push_back(a);
			graph[a].push_back(TUBE + i);
		}
	}
	printf("%d", bfs());
}
 
 
 
반응형

'Algorithm' 카테고리의 다른 글

백준 6497 : 전력난  (0) 2021.11.17
백준 15926 : 현욱은 괄호왕이야!!  (0) 2021.11.17
백준 16398 : 행성 연결  (0) 2021.11.17
백준 14719 : 빗물  (0) 2021.11.17
백준 17490 : 일감호에 다리 놓기  (0) 2021.11.17

+ Recent posts