Codeforces Round #291 (Div. 2) C. Watto and Mechanism Trie字典樹+dfs

思路:由於字符串長度上限爲6*10^5,直接比較十分耗時。而只有a,b,c三種字符,所以使用trie查找相差一位的字符串。

給定字符串s,到達trie上某一個Node時,s[i]可以選擇改或者不改,而更改與否影響到了後續的處理,所以在trie上dfs即可。

代碼如下:

#include <cstdio>
#include <cstring>
using namespace std;
#define N 600005
struct Node{
	bool fin;
	Node* next[3];
	Node(): fin(false) {
		for(int i = 0; i < 3; ++i)
            next[i] = 0;
	}
};
char s[N];
Node* root = 0;

void insert(const char* str){
	if(!root)
		root = new Node();
	Node* cur = root;
	while(*str){
		int idx = *str - 'a';
		if(!cur->next[idx]){
			Node* next = new Node();
			cur->next[idx] = next;
		}
		++str;
		cur = cur->next[idx];
	}
	cur->fin = true;
}

bool query(const Node* pos, const char* str, bool diff){
	if((*str) == 0){
		if(pos->fin && diff)
			return true;
		return false;
	}
	const Node* cur = pos;
	if(diff){
		while(*str){
			int idx = *str - 'a';
			if(!cur->next[idx])
				return false;
			++str;
			cur = cur->next[idx];
		}
		return cur->fin;
	}
	else{
		int idx = *str - 'a';
		const char* next_char = ++str;
		for(int i = 0; i < 3; ++i){
			Node* tmp = cur->next[i];
			if(!tmp)
				continue;
			if(query(tmp, next_char, !(i == idx)))
				return true;
		}
		return false;
	}
}

int main(){
	int n, m;
	scanf("%d %d", &n, &m);
	for(int i = 0; i < n; ++i)
		scanf("%s", s), insert(s);
	for(int i = 0; i < m; ++i){
		scanf("%s", s);
		if(query(root, s, false))
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章