HDU 1247 Hat's words(Trie)

HDU 1247 Hat's words(Trie)

ACM

题目地址: 
HDU 1247 Hat's words

题意: 
给些单词,问每个单词是否能用另外两个单词拼出。

分析: 
直接保存到trie里面,然后暴力切割查询即可。

代码

/*
*  Author:      illuz <iilluzen[at]gmail.com>
*  File:        1247.cpp
*  Create Date: 2014-09-24 11:04:11
*  Descripton:   
*/

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

#define repf(i,a,b) for(int i=(a);i<=(b);i++)
typedef long long ll;

const int N = 50010;
const int MAXNODE = 1000010;
const int MAXSON = 26;

// array index
struct ATrie {
	int ch[MAXNODE][MAXSON];
	int val[MAXNODE];
	int sz;		// num of nodes
	ATrie() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
	void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
	inline int idx(char c) { return c ? c - 'a' : 0; }

	void insert(char *s, int v = 1) {
		int u = 0, len = strlen(s);
		repf (i, 0, len - 1) {
			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;
	}

	// if s in trie return the value, else return 0
	int find(char *s) {
		int u = 0, len = strlen(s);
		repf (i, 0, len - 1) {
			int c = idx(s[i]);
			if (ch[u][c])
				u = ch[u][c];
			else
				return 0;
		}
		return val[u];
	}
} trie;

char wd[N][110], a[110], b[110];
int n;

int main() {
	// ios_base::sync_with_stdio(0);
	while (gets(wd[n])) {
		trie.insert(wd[n++]);
	}
	repf (i, 0, n - 1) {
		int len = strlen(wd[i]);
		repf (j, 1, len - 1) {
			strncpy(a, wd[i], j);
			a[j] = 0;
			strcpy(b, wd[i] + j);
			// cout << a << ' ' << b << endl;
			if (trie.find(a) && trie.find(b)) {
				printf("%s\n", wd[i]);
				break;
			}
		}
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值