⭐⭐⭐【DFS+理解题意】找出直系亲属

62 篇文章 0 订阅

题目描述

代码实现

//我觉得使用DFS更简单易懂一些
//采用邻接表记录
#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;
} 

码后反思

  1. 第一遍我做错了,我只考虑了parent,没有考虑child,原来题目的意思是求前一个是后一个什么关系。我没有理解清楚题目的意思。。。
  2. 这道题虽然出在并查集,但是我使用了DFS。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值