1001: 土豪我们做朋友吧! 课程作业
1001: 土豪我们做朋友吧!
Time Limit: 1 Sec Memory Limit: 16 MBDescription
Water最近掌握了一大波土豪的电话,他决定一个个打电话去找土豪做朋友。可是土豪们不堪骚扰,于是联合通信公司对Water的电话做了一个封杀规则。
每当Water打出一个电话后,该电话号码以及以该电话号码开始的号码都永久无法被Water打出。
举个栗子,Water打出了号码12345,不管有没人接电话,下一次拨号时12345及12345*(类似1234567)的号码都无法拨出,只能听到“您拨打的用户不接你电话,请不要再拨”。
但是如果Water先拨打了1234567,下一次若为12345还是可以打出的。
Water是个锲而不舍的人,他会把他手头上的电话列表按列表顺序都打一次。
Input
第一行为N [1,1 000 000]。
接下来N行是N个土豪的电话。电话为长度在[1,100]的数字序列。
Output
一个整数M,代表Water成功骚扰到的土豪的个数。(即没有被封杀的电话个数)
Sample Input
5
123
12
12345
123
23451
Sample Output
3
也是数据结构的作业的某道题。。。。
这道题很明显是索引搜索树问题,什么是索引搜索树呢?索引搜索树是一颗可以从根节点开始搜索而得到一个组合的树,比如这样一颗树:

它可以得到的组合有:c1, c1c2, c1c3, c1c2c3, c1c2c4.这种树用在搜索字符串的组合的时候比较有效,因为只要根据一个路径就可以判断是否在这个树的组合里。并且这种树用来储存字符串的时候因为有些重复的字母可以省掉会节省内存。比如下面这组字符串:

如果我直接用数组储存它的话还是比较大的,共88个字符,但是我用索引搜索树的话:

只需储存27个字符。当然这种树的优化效果也要看字符串的组成,很多时候他的效率是还不如数组的,因为这样的结构毕竟还有内部指针那些。
关于索引搜索树的详细内容我就不说了,google一下还是有的。。
下面是我的实现代码:《代码挫勿喷》
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 using namespace std; 6 7 struct Node{ 8 bool isValue; 9 struct Node* next[10]; 10 Node() { 11 isValue = false; 12 for (int i = 0; i != 10; i++) 13 next[i] = NULL; 14 } 15 }; 16 17 Node* root = new Node; 18 19 bool matchTree(char* str) { 20 bool flag = true; 21 Node* temp = root; 22 int t; 23 while (*str) { 24 if (temp->isValue == true) { 25 flag = false; 26 break; 27 } 28 29 t = *str++ - '0'; 30 if (temp->next[t] == NULL) { 31 temp->next[t] = new Node; 32 } 33 temp = temp->next[t]; 34 } 35 //if the phone number is the same as 36 //another in the tree, we shou judge it here, 37 //because we can't get in the while ciecle 38 //anymore for *str == NULL. 39 if (temp->isValue == true) 40 flag = false; 41 temp->isValue = true; 42 return flag; 43 } 44 int main(int argc, char const *argv[]) 45 { 46 int N; 47 scanf("%d", &N); 48 int count = 0; 49 for (int i = 0; i != N; i++) { 50 //because in function matchTree 51 //the str will move to the end, 52 //so you should back to the start. 53 //but i just get a new one here. 54 char str[101]; 55 scanf("%s", str); 56 if (matchTree(str) == true) 57 count++; 58 } 59 60 printf("%d\n", count); 61 return 0; 62 }