2024. 2. 15. 19:00ใCoding Test/BOJ
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐จ๐ปํ์ด ๊ณผ์
๋ฉ์ดํ์คํ ๋ฆฌ ๊ฐ๋ฏธ๊ตด์ด ์๊ฐ๋๋ ๋ฌธ์ ์์ต๋๋ค. ํธ๋ผ์ด(Trie) ์๋ฃ๊ตฌ์กฐ๋ฅผ ํ์ฉํด์ ํ ์ ์์๋๋ฐ, ํธ๋ผ์ด์ ๊ด๋ จ๋ ์ฝ๋๋ฅผ ์์ฑํ๋ ๊ฒ ์ต์ํ์ง ์์ ์กฐ๊ธ ์ค๋ ๊ฑธ๋ ธ์ต๋๋ค. ๊ฐ์ ์ธต์ ์ฌ๋ฌ ๊ฐ์ ๋ฐฉ์ด ์์ ๊ฒฝ์ฐ์๋ ์ฌ์ ์์ผ๋ก ๋จน์ด ์ ๋ณด๋ฅผ ์ถ๋ ฅํด์ผ ํ๊ธฐ์ map์ ํ์ฉํ์ฌ ํธ๋ผ์ด๋ฅผ ๊ตฌํํ์์ต๋๋ค.
class Trie
{
public:
Trie(int depth) : depth(depth) { }
~Trie();
void Insert(const vector<string>& foodNames, int index);
void Show();
private:
int depth;
map<string, Trie*> foods;
};
๋์ ํ ๋น์ผ๋ก ํธ๋ผ์ด ๊ฐ์ฒด๋ฅผ ์์ฑํด์ค ๊ฒ์ด๊ธฐ ๋๋ฌธ์, ์๋ฉธ์์์ ๋ฉ๋ชจ๋ฆฌ ํด์ ์ฝ๋๋ฅผ ์์ฑํด์ค๋๋ค.
Trie::~Trie()
{
for (auto& food : foods)
if (food.second != nullptr)
delete food.second;
}
๋ก๋ด ๊ฐ๋ฏธ๊ฐ ๋ฐฉ์ ๋ค์ด๊ฐ ์์๋๋ก ์ ๋ ฅ์ ์ฃผ๊ธฐ ๋๋ฌธ์, ์ด๋ฅผ ๋ฐฐ์ด์ ๋ฐ์์ ์ฌ๊ท ํํ๋ก ํธ๋ผ์ด์ ๋ฃ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ์์ต๋๋ค.
void Trie::Insert(const vector<string>& foodNames, int index)
{
if (index >= foodNames.size())
return;
auto findIt = foods.find(foodNames[index]);
if (findIt == foods.end())
{
Trie* newFood = new Trie(depth + 1);
foods.insert(make_pair(foodNames[index], newFood));
newFood->Insert(foodNames, index + 1);
return;
}
Trie* nextFood = findIt->second;
nextFood->Insert(foodNames, index + 1);
}
์ถ๋ ฅํ๋ ์ฝ๋ ๋ํ, ํ์ฌ ๊น์ด(depth) * 2์ ํด๋นํ๋ ๊ฐ์๋งํผ "-"์ ๋จผ์ ์ถ๋ ฅํด์ฃผ๊ณ , DFS ๋ฐฉ์์ผ๋ก ์ถ๋ ฅํด์ฃผ๋ฉด ๋ฉ๋๋ค.
void Trie::Show()
{
string line(2 * depth, '-');
for (const auto& food : foods)
{
cout << line << food.first << "\n";
food.second->Show();
}
}
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
class Trie
{
public:
Trie(int depth) : depth(depth) { }
~Trie();
void Insert(const vector<string>& foodNames, int index);
void Show();
private:
int depth;
map<string, Trie*> foods;
};
Trie::~Trie()
{
for (auto& food : foods)
if (food.second != nullptr)
delete food.second;
}
void Trie::Insert(const vector<string>& foodNames, int index)
{
if (index >= foodNames.size())
return;
auto findIt = foods.find(foodNames[index]);
if (findIt == foods.end())
{
Trie* newFood = new Trie(depth + 1);
foods.insert(make_pair(foodNames[index], newFood));
newFood->Insert(foodNames, index + 1);
return;
}
Trie* nextFood = findIt->second;
nextFood->Insert(foodNames, index + 1);
}
void Trie::Show()
{
string line(2 * depth, '-');
for (const auto& food : foods)
{
cout << line << food.first << "\n";
food.second->Show();
}
}
int main()
{
ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
int numOfData;
cin >> numOfData;
Trie* root = new Trie(0);
while (numOfData--)
{
int N;
cin >> N;
vector<string> foods(N);
for (int i = 0; i < N; i++) cin >> foods[i];
root->Insert(foods, 0);
}
root->Show();
delete root;
return 0;
}
'Coding Test > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 2636๋ฒ | ์น์ฆ (C++) (1) | 2024.03.22 |
---|---|
[BOJ] 14499๋ฒ | ์ฃผ์ฌ์ ๊ตด๋ฆฌ๊ธฐ (C++) (1) | 2024.03.17 |
[BOJ] 1644๋ฒ | ์์์ ์ฐ์ํฉ (C++) (1) | 2024.02.07 |
[BOJ] 13904๋ฒ | ๊ณผ์ (C++) (1) | 2024.02.06 |
[BOJ] 2638๋ฒ | ์น์ฆ (C++) (0) | 2024.02.01 |