hdu 1251统计难题

做了几道Trie了,这个题做过之后,让我对Trie又有的许多新的认识,真正的理解了插入和查询的整个过程。


// File Name: hdu1251.cpp
// Author: Toy
// Created Time: 2013年05月08日 星期三 09时17分28秒

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <utility>
#include <bitset>
#define L(x) x << 1
#define R(x) x << 1 | 1

using namespace std;

const int sigma_size = 26;
const int maxnode = 10 * 50000 + 10;
string s, tt;
bool flag;

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++;
	    }
	    val[u]++;
	    u = ch[u][c];
	}
	val[u]++;
    }
    void find ( string s ) {
	flag = 1;
	int u = 0, n = s.length ();
	for ( int i = 0; i < n; ++i ) {
	    if ( s[i] == '\0' ) {
		flag = 0;
		break;
	    }
	    int c = idx ( s[i] );
	    if ( !ch[u][c] ) {
		flag = 0;
	        break;
	    }
	    u = ch[u][c];
	}
	if ( flag ) cout << val[u] << endl;
	else cout << "0" << endl;
    }
}trie;

int main ( ) {
    trie.clear();
    while ( getline ( cin, s ) ) {
	if ( s != "" ) trie.insert ( s, 1 );
	else {
	    while ( getline ( cin, tt ) ) {
		trie.find ( tt );
	    }
	}
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值