【枚举+trie+dfs】CF514 C

Problem - 514C - Codeforces

题意:

思路:

其实是trie上dfs的板题

先把字符串插入到字典树中

对于每次询问,都去字典树上dfs

注意到字符集只有3,因此如果发现有不同的字符,去枚举新的字符

Code:

cpp 复制代码
#include <bits/stdc++.h>

using i64 = long long;

using namespace std;

const int N = 4e5 + 10;
const int M = 3e6 + 10;
const int P = 131;

string s;

int tot = 0;
int tag[N];
int tr[N][30];

void insert(string x) {
	int p = 0;
	for (int i = 0; i < x.size(); i ++) {
		int u = x[i] - 'a';
		if (! tr[p][u]) {
			tr[p][u] = ++tot;
		}
		p = tr[p][u];
	}
	tag[p] = 1;
}
bool dfs(int dep, int u, int num) {
	if (s[dep]) {
		int v = s[dep] - 'a';
		if (tr[u][v]) {
			if (dfs(dep + 1, tr[u][v], num)) return true;
		}
		if (!num) {
			for (int j = 0; j < 3; j ++) {
				if (j != v && tr[u][j]) {
					if (dfs(dep + 1, tr[u][j], num + 1)) return true;
				}
			}
		}
	}
	else if (tag[u] && num) return true;
	return false;
}
void solve() {
	int n,m;
	cin >> n >> m;

	for (int i = 1; i <= n; i ++) {
		cin >> s;
		insert(s);
	}

	for (int i = 1; i <= m; i ++) {
		cin >> s;
		if (dfs(0, 0, 0)) {
			cout << "YES" << "\n";
		}else {
			cout << "NO" << "\n";
		}
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	int t = 1;
	//cin >> t;
	while(t --) {
		solve();
	}
	return 0;
}
相关推荐
理论最高的吻38 分钟前
HJ10 字符个数统计【牛客网】
c++·算法·散列表
仙人掌_lz41 分钟前
深入理解蒙特卡洛树搜索(MCTS):python从零实现
人工智能·python·算法·ai·强化学习·rl·mcts
平和男人杨争争1 小时前
山东大学计算机图形学期末复习11——CG13上
算法·图形渲染
代码小将1 小时前
Leetcode134加油站
笔记·算法
计算机毕设源码分享8888881 小时前
番茄采摘机器人的视觉系统设计
人工智能·算法·机器人
gyeolhada2 小时前
2025蓝桥杯JAVA编程题练习Day8
java·数据结构·算法·蓝桥杯
freyazzr2 小时前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
AI technophile2 小时前
OpenCV计算机视觉实战(6)——经典计算机视觉算法
opencv·算法·计算机视觉
qq_584598922 小时前
day30python打卡
开发语言·人工智能·python·算法·机器学习
zhangpeng4555479402 小时前
C++--综合应用-演讲比赛项目
开发语言·c++·算法