hdu2072-单词数 字典树、STL

  • Post author:
  • Post category:其他


单词数




Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 54748    Accepted Submission(s): 13623







Problem Description
lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。


Input
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。


Output
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。


Sample Input
  
  
you are my friend #


Sample Output
  
  
4


Author
Lily


Source
解题思路:(1)我们可以对单词进行字典树插入存储,如果没有在树中就插入, 否则就将单词数量加1。
(2)我们可以利用STL中的set容器,将字符串存入,统计不同字符串个数即可。
ac代码:
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;

set<string> temp;

int main()
{
	string row,input;

	while( getline(cin,row) && row!="#" )
	{
		temp.clear();

		stringstream str(row);

		while(str>>input)
			temp.insert(input);

		cout<<temp.size()<<endl;

	}

	return 0;
}

#include <cstdio> 
#include <iostream>
#include <cstring>
using namespace std;
#define maxn 100000
struct node
{
	int count;
	node *childs[26];
	node()
	{
		count=0;
		int i;
		for(i=0;i<26;i++)
		childs[i]=NULL;
	}
};
node *root=new node;

node *current,*newnode;
void insert(char *str)//插入 
{
	int i,m;
    current=root;
    for(int i=0;i<strlen(str);i++)
    {
       m=str[i]-'a';
        if(current->childs[m]==NULL)
        current->childs[m]=new node;
        current=current->childs[m];
		 current->count++;
    }
   
}
int search(char *str)//查找 
{
	int i,m;
    current=root;
	for(i=0;i<strlen(str);i++)
	{
	    m=str[i]-'a';
		if(current->childs[m]==NULL)
		return 0;
		current=current->childs[m];
	}
	return current->count;
}
int main()
{
	char str[maxn];
	int sum;
	while(~scanf("%s",str))
	{
		sum = 0;
	   if(str[0]=='#') break;
	   if(search(str)==0)
	   {
	     sum++;
	     insert(str);
	   }
	}
	printf("%d\n",sum);
	return 0;
}

题目链接:

点击打开链接http://acm.hdu.edu.cn/showproblem.php?pid=2072



版权声明:本文为wang_heng199原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。