반응형
문제 출처 :
https://www.acmicpc.net/problem/5214
알고리즘 분석 :
문제 해결에 필요한 사항
1. BFS
BFS를 통해서 문제를 해결 할 수 있다.
하이퍼 튜브를 하나의 정점으로 생각하여(10만 + 1 ~ 10만 + M) 그래프를 모델링하면 아래 그림과 같이 모델링 할 수 있다.
그 후 BFS를 돌려 최단 거리를 구하는데 하이퍼 튜브를 지나면 cnt로, 하이퍼 튜브가 아닌 다른 정점을 지나면 cnt + 1을 하여 정답을 구한다.
소스 코드 :
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 | #include <iostream> #include <cstdio> #include <vector> #include <queue> using namespace std; int hyper[1002]; vector<int> adj[101111]; bool visit[101111]; int main() { int n, k, m; scanf("%d %d %d", &n, &k, &m); for (int i = 1; i <= m; i++) { for (int j = 0; j < k; j++) scanf("%d", &hyper[j]); for (int j = 0; j < k; j++) { adj[100000+i].push_back(hyper[j]); adj[hyper[j]].push_back(100000+i); } } queue<pair<int, int> > q; q.push({ 1, 1 }); int ans = 0; while (!q.empty()) { int here = q.front().first; int cnt = q.front().second; q.pop(); if (visit[here]) continue; visit[here] = true; int len = adj[here].size(); for (int i = 0; i < len; i++) { int there = adj[here][i]; if (there == n) { printf("%d", cnt + 1); return 0; } if (there > 100000) q.push({ there, cnt }); else q.push({ there, cnt + 1 }); } } printf("-1"); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[5012번] 불만 정렬 (2) | 2017.09.09 |
---|---|
[4246번] To and Fro (0) | 2017.09.08 |
[14425번] 문자열 집합 (0) | 2017.08.29 |
[1535번] 안녕 (0) | 2017.08.24 |
[2585번] 경비행기 (8) | 2017.08.24 |