File size: 1,344 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
/*
  >>~~ UVa Online Judge ACM Problem Solution ~~<<

  ID: 10009
  Name: All Roads Lead Where?
  Problem: https://onlinejudge.org/external/100/10009.pdf
  Language: C++

  Author: Arash Shakery
  Email: [email protected]
*/

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <list>
using namespace std;

int T, n, q, par[26], asc[26][26];
char c1[100], c2[100];
int main(){
    cin>>T;
    while (T--) {
        cin >> n >> q;

        for (int i=0; i<n; i++) {
            cin>>c1>>c2;

            par[c2[0]-'A'] = c1[0]-'A';
            asc[c1[0]-'A'][c2[0]-'A']=1;
        }

        for (int k=0; k<26; k++) {
            asc[k][k]=1;
            for (int i=0; i<26; i++)
            if (asc[i][k])
                for (int j=0; j<26; j++)
                if (asc[k][j])
                    asc[i][j]=1;
        }

        for (int i=0; i<q; i++) {
            cin>>c1>>c2;
            int j, u=c1[0]-'A', v=c2[0]-'A';
            for (j=u; !asc[j][v]; j=par[j])
                putchar('A' + j);
            putchar('A'+j);
            list<int> ll;
            for (int k=v; k!=j; k=par[k])
                ll.push_front(k);

            for (int j: ll) putchar('A' + j);
            putchar('\n');
        }

        if (T) {
            memset(asc, 0, sizeof(asc));
            putchar('\n');
        }
    }
}