添加字典树、并查集、Dijkstra算法

This commit is contained in:
2025-06-03 16:30:03 +08:00
parent 3015523239
commit 9a5e746691
3 changed files with 120 additions and 0 deletions

35
dijkstra.cpp Normal file
View File

@ -0,0 +1,35 @@
class Solution {
public:
int diskstra(vector<vector<int>>& edges, int n, int start, int end) {
vector<vector<int>> graph(n, vector<int>(n, INT_MAX / 2));
// === 建图 ===
for (auto& [from, to, dist]: edges) {
graph[from][to] = dist;
}
vector<int> distance(n, INT_MAX/2), visited(n, 0);
distance[start] = 0;
while (true) {
int next_node = -1;
for (int node = 0; node < n; node++) {
if (visited[node]) {
continue; // 不重复更新
}
if (next_node < 0 || distance[next_node] > distance[node]) {
next_node = node; // 寻找移动路径最小的节点
}
}
if (next_node < 0 || distance[next_node] == INT_MAX / 2) {
break; // 找不到节点
}
visited[next_node] = 1;
for (int node = 0; node < n; node++) {
// 根据最近节点路径更新其余节点移动路径
distance[node] = min(distance[node], distance[next_node] + graph[next_node][node]);
}
}
return distance[end] == INT_MAX / 2 ? -1 : distance[end];
}
};

49
trie_tree.cpp Normal file
View File

@ -0,0 +1,49 @@
class Trie
{
private:
vector<Trie*> m_children;
bool is_end;
Trie* searchPrefix(string prefix)
{
Trie* node = this;
for (char ch : prefix) {
if (node->m_children[ch - 'a'] == nullptr) {
return nullptr;
}
node = node->m_children[ch - 'a'];
}
return node;
}
public:
Trie() :
m_children(26),
is_end(false)
{
}
void insert(string word)
{
Trie* node = this;
for (char ch : word) {
if (node->m_children[ch - 'a'] == nullptr) {
node->m_children[ch - 'a'] = new Trie;
}
node = node->m_children[ch - 'a'];
}
node->is_end = true;
}
bool search(string word)
{
Trie* node = searchPrefix(word);
return node != nullptr && node->is_end;
}
bool startsWith(string prefix)
{
return searchPrefix(prefix) != nullptr;
}
};

36
union-find_sets.cpp Normal file
View File

@ -0,0 +1,36 @@
class UnionFind {
vector<int> _pre; // 代表元
vector<int> _rank; // 集合的秩
public:
UnionFind(int n) : _pre(n), _rank(n, 1), cc(n) {
// iota(fa.begin(), fa.end(), 0);
ranges::iota(fa, 0);
}
int find(int x) {
return _pre[x] == x ? x : _pre[x] = fint(_pre[x]);
}
bool same(int x, int y) {
return find(x) == find(y);
}
bool merge(int from, int to) {
int x = find(from), y = find(to);
if (x == y) {
return false; //同一集合不做合并
}
if (_rank[x] < _rank[y]) {
_pre[x] = y;
}
else if (_rank[x] > _rank[y]) {
_pre[y] = x;
}
else {
_pre[x] = y;
_rank[y]++;
}
return true;
}
};