File size: 1,778 Bytes
c4b0eef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <stack>
#include <map>
#include <vector>
#include <queue>

using namespace std;

int n, m;
map <string, int> names;
map <int, string> numes;
vector < vector<int> > graph;

void initialize()

{
	names.clear();

	graph.clear();

	graph.resize(n + 10);
}

void makeGraph()

{
	int index = 1;

	for (int i = 0; i < n; i++)
	{
		int v, w;
		string a, b;

		cin >> a >> b;

		if (names[a] == 0)
		{
			v = index++;

			names[a] = v;

			numes[v] = a;
		}

		else
		{
			v = names[a];
		}

		if (names[b] == 0)
		{
			w = index++;

			names[b] = w;

			numes[w] = b;
		}

		else
		{
			w = names[b];
		}

		graph[v].push_back(w);
		graph[w].push_back(v);
	}
}

string bfs(int start, int end)

{
	vector<int> parent(n + 10, -1);

	vector<bool> visited(n + 10, false);

	visited[start] = true;

	queue<int> q;

	q.push(start);

	while (!q.empty())
	{
		int top = q.front();

		q.pop();

		for (int i = 0; i < graph[top].size(); i++)
		{
			if (!visited[graph[top][i]])
			{
				visited[graph[top][i]] = true;

				q.push(graph[top][i]);

				parent[graph[top][i]] = top;
			}
		}
	}

	stack<char> s;

	string ans = "";

	for (int i = end; i != -1; i = parent[i])
	{
		s.push(numes[i][0]);
	}

	while (!s.empty())
	{
		ans += s.top();

		s.pop();
	}

	return ans;
}

int main()

{
	bool first = true;

	int t;

	cin >> t;

	while (t--)
	{
		cin >> n >> m;

		initialize();

		makeGraph();

		for (int i = 0; i < m; i++)
		{
			string start, end;

			cin >> start >> end;

			cout << bfs(names[start], names[end]) << endl;
		}

		if (t != 0) cout << endl;
	}
}