hdu 1247 Hat’s Words

做的第一个Trie。

 

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>

using namespace std;

const int maxnode = 50000 * 10 + 10;
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 ( string s, int v ) {
        int u = 0, n = s.length ( );
        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 ( string s ) {
        int u = 0, n = s.length ();
        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] != 0 ) return true;
        else return false;
    }
}trie;

int main ( ) {
    //freopen ( "input.txt", "r", stdin );
    string s[50005];
    int cnt = 1;
    trie.clear();
    while ( cin >> s[cnt] ) {
        trie.insert ( s[cnt], cnt );
        cnt++;
    }
    for ( int i = 1; i <= cnt; ++i )
        for ( int j = 1; j < s[i].size (); ++j )  {
           string s1 ( s[i], 0, j );
           string s2 ( s[i], j, s[i].size() - 1 );
           //cout << s1 << " " << s2 << endl;
           if ( trie.find ( s1 ) && trie.find( s2 ) ) {
                cout << s[i] << endl;
                break;
           }
        }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值