4-1-7 二叉树及其遍历 家谱处理 (30 分)

源代码博客
在原博客的基础上加了一些注释
统计个数count的用法

count()用来统计元素出现的次数:count(first,last,value); first是容器的首迭代器,last是容器的末迭代器,value是询问的元素,可以使用在容器,数组,字符串中,用于统计元素出现的次数。

#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
	string name[200];//存人物名字
	map<string, string>father;
	int number, times;
	cin >> number >> times;
	getchar();//读掉反斜杠
	for (int t = 0; t < number; t++)
	{
		string str;
		getline(cin,str);//要把前面的空格读进去
		int cnt = count(str.begin(), str.end(),' ');//计数空格的个数
		if (cnt == 0)
		{
			father[str] = "no";//起始祖宗没有父亲
			name[0] = str;
		}
		else
		{
			str = str.substr(cnt);
			father[str] = name[cnt / 2 - 1];//存储每个人名的父亲
			name[cnt / 2] = str;
			//每出现一个同辈份的就会把之前的数据覆盖掉,
			//但其实name数组只是为了找当前字符串的父母,所以不影响
		}
	}
	for (int i = 0; i < times; i++)
	{
		string name1, none,relation, name2;
		cin >> name1 >> none >> none >> relation >> none >> name2;
		switch (relation[0])
		{
			case 'c':
			//child
				swap(name1, name2);//这里没有break,换位置后判断,是等效的
			case 'p':
			//father
				if (father[name2] == name1) printf("True\n");
				else printf("False\n");
				break;
			case 'd':
			//descendant
				swap(name1, name2);
			case 'a':
			//ancestor
				while (father[name2] != name1&&father[name2]!="no")
					name2 = father[name2];
					//往上一直找name2的父亲节点,当name2的父亲节点==name1或者
					//查到了初始祖宗那就跳出
				if (father[name2] == name1) printf("True\n");//往上父亲节点是一致的
				else printf("False\n");//追查到了原始祖宗并且也不一样
				break;
			case 's':
			//sibling(只算亲兄妹,表兄妹之类的不算)
				if (father[name2] == father[name1]) printf("True\n");
				else printf("False\n");
				break;
		}
	}
	return 0;

}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值