Hat’s Words HDU - 1247 (字典树)

短命女 2023-08-17 15:41 223阅读 0赞

Hat’s Words HDU - 1247

题目链接:https://vjudge.net/problem/HDU-1247

题目:

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.

InputStandard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
OutputYour output should contain all the hat’s words, one per line, in alphabetical order.Sample Input

  1. a
  2. ahat
  3. hat
  4. hatword
  5. hziee
  6. word

Sample Output

  1. ahat
  2. hatword
  3. 题意:就是给你一个单词列表,然后单词可以从中间拆成任意两部分,只要这两部分都是单词列表里的就把这个单词输出,否则不输出
  4. 思路:利用字典树将所有单词插入字典树中,单词个数均赋予1,然后后面处理的时候再利用strncpy函数将单词分开,分别存入s1,s2中,注意末尾要赋予“\0
  5. 才可使用,然后就利用字典树开始找,当find(s1)+find(s2)为2时,说明都找到了,此时将字符串输出即可;
  6. //
  7. // Created by HJYL on 2019/8/21.
  8. //
  9. #include <iostream>
  10. #include <vector>
  11. #include <map>
  12. #include <string>
  13. #include <queue>
  14. #include <stack>
  15. #include <set>
  16. #include <algorithm>
  17. #include <cstdio>
  18. #include <cstring>
  19. #include <cmath>
  20. #include <cstdlib>
  21. using namespace std;
  22. typedef long long ll;
  23. const int maxn=1e6+10;
  24. struct trie{
  25. int sum;
  26. trie* next[26];
  27. trie(){
  28. for(int i=0;i<26;i++)
  29. next[i]=NULL;
  30. sum=0;
  31. }
  32. }root;
  33. void insert(char* s)
  34. {
  35. trie* p=&root;
  36. for(int i=0;s[i];i++)
  37. {
  38. if(p->next[s[i]-'a']==NULL)
  39. p->next[s[i]-'a']=new trie;
  40. //else
  41. p=p->next[s[i]-'a'];
  42. }
  43. p->sum=1;//单词存在就是1
  44. }
  45. int find(char* s)
  46. {
  47. trie* p=&root;
  48. for(int i=0;s[i];i++)
  49. {
  50. if(p->next[s[i]-'a']==NULL)
  51. return 0;
  52. else
  53. p=p->next[s[i]-'a'];
  54. }
  55. return p->sum;
  56. }
  57. int main()
  58. {
  59. //freopen("C:\\Users\\asus567767\\CLionProjects\\untitled\\text", "r", stdin);
  60. char str[50007][30];
  61. char s1[200],s2[200];
  62. int n=0;
  63. while(~scanf("%s",str[n]))
  64. {
  65. insert(str[n]);
  66. //cout<<str[n]<<endl;
  67. n++;
  68. }
  69. int len;
  70. int ans;
  71. for(int i=0;i<n;i++)
  72. {
  73. len=strlen(str[i]);
  74. for(int j=1;j<=len-1;j++){
  75. strncpy(s1,str[i],j);
  76. s1[j]='\0';//!
  77. strncpy(s2,str[i]+j,len-j);
  78. s2[len-j]='\0';//!
  79. ///cout<<s1<<" "<<s2<<endl;
  80. ans=find(s1)+find(s2);
  81. if(ans==2)
  82. {
  83. printf("%s\n",str[i]);
  84. break;
  85. }
  86. }
  87. }
  88. return 0;
  89. }

转载于:https://www.cnblogs.com/Vampire6/p/11386549.html

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HDU 1298(字典+dfs)

    题意:给一个T,表示输入数据的组数。给一个n,表示字典的大小。接下来有n行,每行有一个字符串和一个数字,数字表示为这个字符串的权值。接下来给一个m,表示手机按键的串号,结尾1表

    相关 HDU1247(字典)

    题意:给定一排字符串组成一个字典,求在字典中自否存在由字典中另外两个字符串组成的字符串。   include <iostream> include <st