牛客oj 习题11.1 找出直系亲属(前驱记录)

题目链接:https://www.nowcoder.com/practice/2c958d09d29f46798696f15ae7c9703b?tpId=40&tqId=21453&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

思路:其实我不是很懂为什么要把这题和并查集扯上关系,直接一个前驱关系就解决的问题,用并查集是不是有点大材小用?

其中son[i]数组代表i节点的孩子。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <cctype>
#include <climits>
 
using namespace std;
 
const int MAXN = 30000;
const int INF = INT_MAX;

int main(){
//	freopen("in.txt", "r", stdin);
	int n, m;
	char son[MAXN];
	string str; 
	while(~scanf("%d %d", &n, &m)){
		for(int i = 0; i < 27; i++){
			son['A' + i] = '#';
		}
		for(int i = 0; i < n; i++){
			cin >> str;
			if(isupper(str[1])) son[str[1]] = str[0];
			if(isupper(str[2])) son[str[2]] = str[0];
		}
		for(int i = 0; i < m; i++){
			cin >> str;
			bool flag = false;
			int count = 0;
			char tmp = str[0];
			while(son[tmp] != '#'){
				tmp = son[tmp];
				count++;
				if(tmp == str[1]){
					flag = true;
					break;
				}
			}
			if(!flag){
				count = 0;
				tmp = str[1];
				while(son[tmp] != '#'){
					tmp = son[tmp];
					count--;
					if(tmp == str[0]){
						flag = true;
						break;
					}
				}
			}
			if(!flag) printf("-\n");
			else{
				if(count == 1) printf("parent\n");
				else if(count == 2) printf("grandparent\n");
				else if(count >= 3){
					while(count > 2){
						printf("great-");
						count--;
					}
					printf("grandparent\n");
				}
				else if(count == -1) printf("child\n");
				else if(count == -2) printf("grandchild\n");
				else if(count <= -3){
					while(count < -2){
						printf("great-");
						count++;
					}
					printf("grandchild\n");
				}
			}
		}
	}
	return 0;
}
发布了411 篇原创文章 · 获赞 72 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/Flynn_curry/article/details/105419772