hdu 1251 统计难题

这是字典树的入门题,很经典,也很容易,代码比较简单易懂,所以我就不解释了。不会字典树的同学请先上网搜索相关知识~~~

/* THE PROGRAM IS MADE BY PYY */ /*----------------------------------------------------------------------------// Copyright (c) 2011 panyanyany All rights reserved. URL : http://acm.hdu.edu.cn/showproblem.php?pid=1251 Name : 统计难题 Date : Thursday, May 5, 2011 Time Stage : 2 hours around Result: 3910551 2011-05-05 01:45:27 Accepted 1251 93MS 43784K 1423 B C++ pyy Test Data: Review: 初级题目,果然一次就AC了…… //----------------------------------------------------------------------------*/ #include <iostream> #include <conio.h> #include <stdio.h> #include <string.h> using namespace std; struct node { int cnt; node *childs[26]; node() { cnt = 0; memset(childs, 0, sizeof(childs)); } }; node *root = new node; int i, j, k, index; node *current, *newnode; void insert( char * str ) { current = root; for( i = 0; str[i] != '/0'; ++i ) { index = str[i] - 'a'; if( current->childs[index] != NULL ) { current = current->childs[index]; ++current->cnt; } else { newnode = new node; ++newnode->cnt; current->childs[index] = newnode; current = newnode; } } } int is_find( char *str ) { current = root; for( i = 0; str[i] != '/0'; ++i ) { index = str[i] - 'a'; if( current->childs[index] == NULL ) return 0; current = current->childs[index]; } return current->cnt; } int main() { char str[20]; while( gets(str), strcmp(str, "") ) insert( str ); while( gets(str) != NULL ) printf( "%d/n", is_find(str) ); return 0; }

你可能感兴趣的:(hdu 1251 统计难题)