代码实现
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int maxn = 30;
vector<int> adj[maxn];
int n;
int m;
int res;
void dfs(int u,int v,int depth){
if(u==v){
res=depth;
return;
}else{
depth++;
for(int i=0;i<adj[u].size();i++){
dfs(adj[u][i],v,depth);
}
return;
}
}
void show(int cas){
if(cas == 1){
if(res==1){
printf("parent\n");
}else if(res==2){
printf("grandparent\n");
}else{
string output = "grandparent";
while(res>2){
output = "great-"+output;
res--;
}
cout<<output<<endl;
}
}else if(cas == 2){
if(res==1){
printf("child\n");
}else if(res==2){
printf("grandchild\n");
}else{
string output = "grandchild";
while(res>2){
output = "great-"+output;
res--;
}
cout<<output<<endl;
}
}
}
int main(){
while(scanf("%d",&n)!=EOF){
scanf("%d",&m);
for(int i=0;i<maxn;i++){
adj[i].clear();
}
while(n--){
char cx,cy,cz;
scanf("\n%c%c%c",&cx,&cy,&cz);
int x = cx-'A';
int y = cy-'A';
int z = cz-'A';
if(cy!='-'){
adj[y].push_back(x);
}
if(cz!='-'){
adj[z].push_back(x);
}
}
while(m--){
res=-1;
char cx,cy;
scanf("\n%c%c",&cx,&cy);
int x = cx-'A';
int y = cy-'A';
dfs(x,y,0);
if(res == -1){
dfs(y,x,0);
if(res == -1){
printf("-\n");
}else{
show(2);
}
}else{
show(1);
}
}
}
return 0;
}
码后反思
- 第一遍我做错了,我只考虑了parent,没有考虑child,原来题目的意思是求前一个是后一个什么关系。我没有理解清楚题目的意思。。。
- 这道题虽然出在并查集,但是我使用了DFS。。。