๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป DEV/Algorithms & Data Structure

[์•Œ๊ณ ๋ฆฌ์ฆ˜][C++] ํŠธ๋ผ์ด (Trie)

by vodkassi 2024. 3. 13.
728x90

๋ฐฑ์ค€ 14425: ๋ฌธ์ž์—ด ์ง‘ํ•ฉ

https://www.acmicpc.net/problem/14425

 

14425๋ฒˆ: ๋ฌธ์ž์—ด ์ง‘ํ•ฉ

์ฒซ์งธ ์ค„์— ๋ฌธ์ž์—ด์˜ ๊ฐœ์ˆ˜ N๊ณผ M (1 ≤ N ≤ 10,000, 1 ≤ M ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค.  ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ์ง‘ํ•ฉ S์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋ฌธ์ž์—ด๋“ค์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฒ€์‚ฌํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ž์—ด๋“ค์ด ์ฃผ์–ด

www.acmicpc.net

 

์ ‘๊ทผ ๋ฐฉํ–ฅ ๋ฐ ๋””๋ฒ„๊น…

 

ํŠธ๋ผ์ด ๊ตฌํ˜„

- find ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ํ›จ์”ฌ ์‹œ๊ฐ„๋„ ๋น ๋ฅด๊ณ  ๊ตฌํ˜„๋„ ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์ด๋‚˜, ํŠธ๋ผ์ด ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ•™์Šตํ•˜๋Š” ์ฐจ์›์—์„œ ํŠธ๋ผ์ด๋กœ ๊ตฌํ˜„

- ๊ฐœ๋ณ„ ๋…ธ๋“œ๋ฅผ ๋‹ด๋‹นํ•  struct ๋ฅผ ๊ตฌ์„ฑํ•˜๊ณ , ๋‹จ์–ด๊ฐ€ ์ž…๋ ฅ๋  ๋•Œ๋งˆ๋‹ค ๊ฐ ๊ธ€์ž๋ฅผ ํŠธ๋ฆฌ ํ˜•ํƒœ๋กœ ํ˜•์„ฑ

- ๋‹จ์–ด๊ฐ€ ์ง‘ํ•ฉ์— ์กด์žฌํ•˜๋Š”์ง€ ์ฐพ์„ ๋•Œ๋Š” ๊ตฌ์„ฑ๋œ ํŠธ๋ฆฌ๋ฅผ ํƒ์ƒ‰

- ์ค‘์š”ํ•œ ์ ์€, ํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑํ•  ๋•Œ ๋‹จ์–ด๊ฐ€ ๋๋‚˜๋Š” ์ง€์ ์„ ๋ช…ํ™•ํ•˜๊ฒŒ ํ‘œ์‹œํ•ด์ฃผ์–ด์•ผ ๊ฒ€์ƒ‰์ด ์ •ํ™•ํ•˜๊ฒŒ ๋œ๋‹ค๋Š” ์ ! 

 

์ฝ”๋“œ

/* 1091816KB 1680ms */
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>

using namespace std;

struct trie {
	int val;
	trie * children[26];

	trie() {
		memset(children, NULL, sizeof(children));
		//for (int i = 0; i < 26; i++) {
		//	children[i] = NULL;
		//}
	}
};

int main() {

	freopen("input.txt", "r", stdin);

	int N, M;
	cin >> N >> M;
	
	trie t = * new trie;
	for (int i = 0; i < N; i++) {
		string str;
		cin >> str;
		
		trie * tmp = &t;
		for (int j = 0; j < str.size(); j++) {

			int letter = (int)str[j] - 97;
			if (tmp->children[letter] == NULL) {
				tmp->children[letter] = new trie;
			}
			tmp = tmp->children[letter];
		}
		tmp->val = 1;
	}

	int cnt = 0;
	for (int i = 0; i < M; i++) {
		string str;
		cin >> str;

		bool flag = true;
		trie * tmp = &t;
		for (int j = 0; j < str.size(); j++) {

			int letter = (int)str[j] - 97;
			if (tmp->children[letter] == NULL) {
				flag = false;
				break;
			}
			tmp = tmp->children[letter];
		}

		if (flag && tmp->val) {
			cnt++;
		}
	} 

	cout << cnt;
	return 0;
}

 

 

๋ฐฐ์šด ์ 

- a ~ z ๋ฅผ 0 ~ 26 ์˜ ์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” %97 ์—ฐ์‚ฐ ์™ธ์—๋„ (int)str - 97 ๋˜๋Š” (int)str - 'a' ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค

๋Œ“๊ธ€