HDU1247 Hat‘s Words 字典树

一道折磨了我两个小时的字典树发现原来是字符串拆分…
HDU传送门
Vjudgge传送门

题目 Hat’s Words

Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input

a
ahat
hat
hatword
hziee
word

Sample Output

ahat
hatword

题目大意

按照字典序给你一堆字符串。
如果其中有一个字符串可以由另外两个串组成,输出那个被组成的串。
输出要字典序输出。

代码

//#include<bits/stdc++.h>杭电不能用万能头,可恶啊。
#include<iostream>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<vector>
using namespace std;
#define IOS ios::sync_with_stdio(false)
const int N = 1e5 + 10;
int tr[N][26], tot = 0, End[N]; 
vector<string>t, ans;
//数据结构^.^
void insert(string s) {
	int pos = 0, len = s.length();
	for (int i = 0; i < len; i++) {
		int c = s[i] - 'a';
		if (tr[pos][c] == 0) {
			tr[pos][c] = ++tot;
		}
		pos = tr[pos][c];
	}
	End[pos] = 1;
}
int query(string s) {
	int pos = 0, len = s.length();
	for (int i = 0; i < len; i++) {
		int c = s[i] - 'a';
		if (tr[pos][c] == 0) return 0;
		pos = tr[pos][c];
	}
	return End[pos];
}
int main(int argc, char** argv) {
	string str;
	while(cin >> str) {
		insert(str);
		t.push_back(str);
	}
	for(int i = 0; i < t.size(); i++){
		for(int j = 0; j < t[i].length(); j++){
			string a = t[i].substr(0, j+1); 
			string b = t[i].substr(j+1);
			//这里拆分字符串~
			//其中空串是不会在字典树里面找到的所以->
			//不用担心一个单词由他本身与空串这样的组合可以被找到。
			if(query(a) && query(b)){
				ans.push_back(t[i]);
				break;
			}
		}
	}
	sort(ans.begin(), ans.end());//字典序输出,排个序。
	for(int i = 0; i < ans.size(); i++) cout << ans[i] << endl;
	return 0;
}

至此。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Raoxiaomi.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值