UVa 10391 - Compound Words

hash存储,遍历每个单词的所有拆分,看是否都存在。

#include <stdio.h>
  #include <stdlib.h>
  #include <math.h>
  #include <string.h>
  #include <stack>
  #include <queue>
  #include <iostream>
  #include <algorithm>
  
  using namespace std;
  
  #define MAXN  120100
  #define INF 1e8
  #define NEGINF -1e8
  
  
  const int HASHSIZE = 121000;
  int head[HASHSIZE], next[MAXN];
  
  char str[MAXN][100];
  int cnt[MAXN];
  
  
  int hash(char s[])
  {    
      unsigned int seed = 131;
      unsigned int hash = 0;    
  	
  	int i;
  	int len = strlen(s);
  	for( i = 0; i < len; i++ )
  		hash = hash * seed + s[i];  
      return (hash & 0x7FFFFFFF) % HASHSIZE;    
  }
  
  
  void add_hash(int s) {
    int h = hash(str[s]);
    next[s] = head[h];
    head[h] = s;
  }
  
  int search(char *p) {
  	int h = hash(p);
  	int u = head[h];
  	while(u) {
  		if( !strcmp(str[u],p) ) return u;
  		u = next[u];
  	}
  	return -1;
  }
  
  int main() {
  	#ifndef ONLINE_JUDGE
  		freopen("data.in","r",stdin);
  		//freopen("data.out","w",stdout);
  	#endif
  	
  	
  	memset(head,0,sizeof(head));
  	memset(next,0,sizeof(next));
  	memset(cnt,0,sizeof(cnt));
  	int ix = 1;
  	int len;
  	while( gets(str[ix]) != NULL ) {		/*hash*/
  		len = strlen(str[ix]);
  		cnt[len] = 1;
  		add_hash(ix);					
  		ix++;
  	}
  
  	int i,j,k;
  	
  	char s1[1000],s2[1000];
  	for( i = 1; i < ix; i++ ) {
  		len = strlen(str[i]);
  		
  
  		for( j = 0; j < len - 1; j++ ) {	/*遍历所有子拆分*/
  			int v1 = 0,v2 = 0;
  			for( k = 0; k <= j; k++ )
  				s1[v1++] = str[i][k];
  			s1[v1] = '\0';
  			for( k = j+1; k < len; k++ )
  				s2[v2++] = str[i][k];
  			s2[v2] = '\0';
  			if( cnt[v1] && cnt[v2] ) {		/* 如果无此长度则不用搜索,优化后没多少效果。。*/
  				if( search(s1) != -1 && search(s2) != -1 ) {
  					printf("%s\n",str[i]);
  					break;
  				}
  			}
  		}
  	}
  
  	return 0;
  }
  
  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值