牛客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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章