diff --git a/dijkstra.cpp b/dijkstra.cpp new file mode 100644 index 0000000..3a1e872 --- /dev/null +++ b/dijkstra.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int diskstra(vector>& edges, int n, int start, int end) { + vector> graph(n, vector(n, INT_MAX / 2)); + // === 建图 === + for (auto& [from, to, dist]: edges) { + graph[from][to] = dist; + } + + vector 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]; + } +}; \ No newline at end of file diff --git a/trie_tree.cpp b/trie_tree.cpp new file mode 100644 index 0000000..f8b8b8a --- /dev/null +++ b/trie_tree.cpp @@ -0,0 +1,49 @@ +class Trie +{ +private: + vector 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; + } +}; \ No newline at end of file diff --git a/union-find_sets.cpp b/union-find_sets.cpp new file mode 100644 index 0000000..c578c7d --- /dev/null +++ b/union-find_sets.cpp @@ -0,0 +1,36 @@ +class UnionFind { + vector _pre; // 代表元 + vector _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; + } +};