源代码博客
在原博客的基础上加了一些注释
统计个数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;
}