Hat’s Words hdu 1247(字典树 map)

/*
 搞了一个早上,终于搞出来了。一开始以为字典树的hash很简单,
 可是一写才发现有很多的细节要注意
*/
#include<iostream>//2561185 2010-06-28 11:41:12 Accepted 1247 31MS 7364K 1977 B C++ 悔惜晟
#include<cstdio>
#include<cstring>
using namespace std;

struct node
{
 struct node *child[26];
 bool hash;
};
struct node *root;
char str[50005][100], str1[100], str2[100];

void insert(char *str)
{
 int i, j, len;
 struct node *newroot, *now;
 len = strlen(str);
 newroot = root;
 for( i = 0; i < len; i++)
 {
  if(newroot->child[str[i] - 'a'] != NULL)
  {
   if(i == len - 1)
   {
    
    newroot = newroot->child[str[i] - 'a'];
    newroot->hash = true;//这个hash写在这里
    break;
   }
   else
    newroot = newroot->child[str[i] - 'a'];
  }
  else
  {
   now =(struct node *) malloc(sizeof(struct node));
   for(j = 0; j < 26; j++)
   {
    now->child[j] = NULL;
    now->hash = false;
   }
   if(i == len - 1)
   {
    
    newroot->child[str[i] - 'a'] = now;
    newroot = now;
    newroot->hash = true;
   }
   else
   {
    newroot->child[str[i] - 'a'] = now;
    newroot = now;
   }
  }
 }

}

bool find(char *str)
{
 struct node *now;
 now = root;
 int i, len;
 len = strlen(str);
 for(i = 0; i < len; i++)
 {
  if(now->child[str[i] - 'a'] != NULL)
  {
   if(i == len - 1)
   {
    now = now->child[str[i] - 'a'];
    return now->hash;
   }
   else
   {
    now = now->child[str[i] - 'a'];
   }
  }
  else
   return false;
 }
}
int main()
{
 
 int len = 0;
 int i, j, k, len1;
 root = (struct node *)malloc(sizeof(struct node));
 for(i = 0; i < 26; i++)
 {
  root->child[i] = NULL;
  root->hash = false;
 }
 while(scanf("%s", str[len]) != EOF)
 {
  insert(str[len]);
  len++;
 }
 
 for(i = 0; i < len; i++)
 {
  int len1 = strlen(str[i]);
  for(j = 1; j < len1 ; j++)
  {
   for(k = 0; k < j; k++)
   {
    str1[k] = str[i][k];
   }
   str1[k] = '/0';
   int t = 0;
   for(k = j; k < len1; k++)
   {
    str2[t++] = str[i][k];
   }
   str2[t] = '/0';
   if(find(str1) && find(str2))
   {
    printf("%s/n", str[i]);
    break;
   }
  }
 }
}

 

#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string, int> hash;
string str[50005];
int main()
{
 
 int i = 0;
 int j, k, t;
 //while(scanf("%s", str[i]) != EOF)
 while(cin>>str[i])
 {
  hash[str[i]] = 1;
  i++;
 }
 string ss, ss1;
 for(j = 0; j < i; j++)
 {
  
  int len = str[j].length();
  for(k = 1; k < len ; k++)
  {
   ss = "";
   ss1 = "";
   for(t = 0; t < k; t++)
   {
    ss += str[j][t];
   }
   for(t = k; t < len; t++)
   {
    ss1 += str[j][t];
   }
   if(hash[ss] == 1 && hash[ss1] == 1)
   {
    cout<<str[j]<<endl;
    break;//讨厌的break
   }
  }
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值