시작점부터, BFS 탐색을 하여 마지막 연락 받는 사람을 찾는다.
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 | #include <stdio.h> #include <memory.h> #include <queue> using namespace std; int contact[101][101]; int visit[101]; int main(void) { int T=10; setbuf(stdout, NULL); //scanf("%d\n", &T); for (int test_case = 1; test_case <= T; test_case++) { memset(contact, 0, sizeof(contact)); memset(visit, 0, sizeof(visit)); int l, s; scanf("%d%d", &l,&s); for (int i = 0; i < l / 2; i++) { int f, t; scanf("%d%d", &f,&t); contact[f][t] = 1; } queue<int> q; queue<int> last; int max = 0; q.push(s);//시작점 푸쉬 visit[s] = 1; while (q.size()) { int temp = q.size(); while (last.size()) last.pop(); for (int i = 0; i < temp; i++)//큐에 있는 모든 숫자를 빼서 연락 { int from = q.front(); q.pop(); last.push(from); for (int j = 0; j < 101; j++) { if (contact[from][j] == 1 && visit[j]==0)//from이 연락 가능하고 j가 아직 연락을 안받았다면 { visit[j] = 1; q.push(j); } } } } while (last.size()) { int temp = last.front(); last.pop(); if (temp > max) max = temp; } printf("#%d %d\n", test_case,max); } return 0; } | cs |