7-27 家谱处理 (30分)--map
参考链接:数据结构与算法题目集7-27——家谱处理
1 #include <iostream> 2 #include <string> 3 #include <cstring> 4 #include <cstdio> 5 #include <map> 6 7 using namespace std; 8 9 int main() 10 { 11 int n1, n2; 12 cin >> n1 >> n2; 13 getchar();//需要吸收回车符,否则下面读入名字的时候会将'\n'先读入 14 map<string, int> s_to_i;//名字字符串到读入顺序的映射 15 //map<int, string> i_to_s; 16 int space_num[200] = {0}; 17 for (int i = 0; i < n1; i++) 18 { 19 int j = 0;//字符在数组中的下标 20 int space_cnt = 0;//暂时记录人名字前的空格数 21 char t_name[20];//暂时储存读入名字 22 while (1)//循环读取名字的字符 23 { 24 char ch = getchar();//键盘读入字符 25 if (ch == '\n') 26 { 27 t_name[j] = '\0'; 28 space_num[i] = space_cnt; 29 s_to_i[t_name] = i; 30 //i_to_s[i] = t_name; 31 break;//读取完毕,退出循环 32 } 33 else if (ch == ' ') 34 { 35 space_cnt++; 36 } 37 else 38 { 39 t_name[j++] = ch; 40 } 41 } 42 } 43 44 for (int i = 0; i < n2; i++) 45 { 46 char str1[20], str2[10], str3[10], str4[20], str5[10], str6[20]; 47 cin >> str1 >> str2 >> str3 >> str4 >> str5 >> str6; 48 if (!strcmp(str4, "child")) 49 { 50 int flag = 1;//标志判断是否正确,正确为1,预设为1 51 int x = s_to_i[str1], y = s_to_i[str6]; 52 if (y < x && (space_num[x] - space_num[y] == 2)) 53 { 54 for (int j = y + 1; j < x; j++) 55 { 56 if (space_num[j] < space_num[x]) 57 flag = 0; 58 } 59 } 60 else flag = 0; 61 if (flag == 1)cout << "True" << endl; 62 else cout << "False" << endl; 63 } 64 else if (!strcmp(str4, "parent")) 65 { 66 int flag = 1; 67 int x = s_to_i[str1], y = s_to_i[str6]; 68 if (y > x && (space_num[x] - space_num[y] == -2)) 69 { 70 for (int j = x + 1; j < y; j++) 71 { 72 if (space_num[j] < space_num[y]) 73 flag = 0; 74 } 75 } 76 else flag = 0; 77 if (flag == 1)cout << "True" << endl; 78 else cout << "False" << endl; 79 } 80 else if (!strcmp(str4, "sibling")) 81 { 82 int flag = 1; 83 int x = s_to_i[str1], y = s_to_i[str6]; 84 int a = x < y ? x : y; 85 int b = x > y ? x : y; 86 if (space_num[x] == space_num[y]) 87 { 88 for (int j = a + 1; j < b; j++) 89 { 90 if (space_num[j] < space_num[b]) 91 flag = 0; 92 } 93 } 94 else flag = 0; 95 if (flag == 1)cout << "True" << endl; 96 else cout << "False" << endl; 97 } 98 else if (!strcmp(str4, "descendant")) 99 { 100 int flag = 1; 101 int x = s_to_i[str1], y = s_to_i[str6]; 102 if (x > y && (space_num[x] > space_num[y])) 103 { 104 for (int j = y+1; j < x; j++) 105 { 106 if (space_num[j] == space_num[y]) 107 flag = 0; 108 } 109 } 110 else flag = 0; 111 if (flag == 1) cout << "True" << endl; 112 else cout << "False" << endl; 113 } 114 else if (!strcmp(str4, "ancestor")) 115 { 116 int flag = 1; 117 int x = s_to_i[str1], y = s_to_i[str6]; 118 if (x < y && (space_num[x] < space_num[y])) 119 { 120 for (int j = x+1; j < y; j++) 121 { 122 if (space_num[j] == space_num[x]) 123 flag = 0; 124 } 125 } 126 else flag = 0; 127 if (flag == 1) cout << "True" << endl; 128 else cout << "False" << endl; 129 } 130 } 131 return 0; 132 }