邻接表 + dfs

#include<iostream>
#include<cstring>

using namespace std;

const int N = 30;

int idx, h[N], e[N], ne[N];

int dfs(int x, int y){
    int cnt = -1;
    for(int i = h[x]; i != -1; i = ne[i]){
        int j = e[i];
        if(j == y) cnt = 1;
        else if(dfs(j, y) != -1)
            cnt = dfs(j, y) + 1; 
    }
    return cnt;
}

int main()
{
    int m, n;
    while(cin >> n >> m){
        idx = 0;
        memset(h, -1, sizeof h);
        while(n--){
            string tmp;
            cin >> tmp;
            int child = tmp[0]-'A';
            int par1 = tmp[1]-'A';
            int par2 = tmp[2]-'A';
            if(par1 != '-'-'A'){
                e[idx] = par1; ne[idx] = h[child]; h[child] = idx++;
            }
            if(par2 != '-'-'A'){
                e[idx] = par2; ne[idx] = h[child]; h[child] = idx++;
            }       
        }
        while(m--){
            string tmp;
            cin >> tmp;
            int child = tmp[0]-'A';
            int par = tmp[1]-'A';
            int cnt = 0;
            string s = "child";
            cnt = dfs(child, par);
            if(cnt == -1){
                s = "parent";    
                cnt = dfs(par, child);    
            }  
            if(cnt == -1) cout << "-" << endl;
            else{
                if(cnt == 1) cout <<s << endl;
                else{
                    cnt--;
                    cnt -=1;
                    while(cnt--){
                        cout << "great-";
                    }
                    cout <<"grand"+s << endl;
                }  
            }
        }
    }
    return 0;
}