본문 바로가기

코딩/알고리즘

SW expert academy 1238 Contact




#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <utility>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <math.h>
#include <string>

using namespace std;

int len, start;

int main() {

	for (int tc = 1; tc <= 10; tc++) {
		scanf("%d %d", &len, &start);

		set<int> adj[101];

		int from, to;
		for (int i = 0; i < len / 2; i++) {
			cin >> from;
			cin >> to;

			adj[from].insert(to);
		}

		queue<int> next;
		bool isVisit[101];
		for (int i = 0; i < 101; i++) {
			isVisit[i] = false;
		}

		//isVisit[start] = true;
		next.push(start);
		next.push(-1);

		vector<int> last = vector<int>();
		last.push_back(start);

		while (true) {
			int nextnode = next.front();
			next.pop();
			if (nextnode != -1 && isVisit[nextnode]) continue;

			last.push_back(nextnode);
			if (next.empty()) break;
			if (nextnode == -1) {
				if (next.size() != 0) last.clear();
				next.push(-1);
				continue;
			}

			isVisit[nextnode] = true;
			for (auto i : adj[nextnode]) {
				if (isVisit[i]) continue;
				next.push(i);
			}
		}

		int maxnum = 0;
		for (auto a : last) {
			if (maxnum < a) maxnum = a;
		}

		printf("#%d %d\n", tc, maxnum);

	}

	return 0;
}