HDU: 1247.Hat’s Words

本文介绍了一个使用C语言实现的程序,该程序利用Trie树数据结构来检查一个单词是否可以被拆分为两个存在于字典中的子串。通过构建Trie树,程序能够高效地查找和插入字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ctrl+Z结束输入

#include <stdio.h>
#include <string.h>
struct st{
	char word[100];
}w[50010];

const int maxnode = 1000000;
const int sigma_size = 26;
struct Trie {
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int sz;
    void clear( ) { sz = 1; memset ( ch[0], 0, sizeof ( ch[0] ) ); }
    int idx ( char c ) { return c - 'a'; }

    void Insert ( char *s, int v ) {
        int u = 0, n = strlen ( s );
        for ( int i = 0; i < n; ++i ) {
            int c = idx ( s[i] );
            if ( !ch[u][c] ) {
                memset ( ch[sz], 0, sizeof ( ch[sz] ) );
                val[sz] = 0;
                ch[u][c] = sz++;
            }
            u = ch[u][c];
        }
        val[u] = v;

    }
    bool find ( const char *s ) {
		int u = 0, n = strlen ( s );
		for ( int i = 0; i < n; ++i ) {
			int c = idx(s[i]);
			if ( !ch[u][c] ) return false;
			u = ch[u][c];
		}
        if ( val[u] ) return true;
        else return false;
	}
}trie;
int main ( ) {
   trie.clear ();
   int k=0,x,y,t;

    while(scanf("%s",w[k].word)!=EOF){
        trie.Insert ( w[k++].word, 1 );
    }

    for(int i=0;i<k;++i){
        t=strlen(w[i].word);

        for(int j=0;j<t;j++){
            char a[100]={},b[100]={};
            for(x=0;x<=j;++x)
                a[x]=w[i].word[x];
            for(y=0;x<t;++y,++x)
                b[y]=w[i].word[x];
           if(trie.find ( a )&&trie.find ( b )){
                printf("%s\n",w[i].word);
                break;
            }
        }
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值