dijkstra及并查集算法更新

This commit is contained in:
2025-06-05 09:49:31 +08:00
parent 292e31bd8d
commit ef5480b44f
4 changed files with 65 additions and 65 deletions

View File

@ -2,31 +2,31 @@ 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;
for (auto& edge : edges) {
int from = edge[0], to = edge[1], dist = edge[2];
graph[from][to] = dist; // build the graph
}
vector<int> distance(n, INT_MAX/2), visited(n, 0);
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; // 不重复更新
continue; // update non-repeatedly
}
if (next_node < 0 || distance[next_node] > distance[node]) {
next_node = node; // 寻找移动路径最小的节点
next_node = node; // find the node with the smallest moving path
}
}
if (next_node < 0 || distance[next_node] == INT_MAX / 2) {
break; // 找不到节点
break; // cannot find the node
}
visited[next_node] = 1;
for (int node = 0; node < n; node++) {
// 根据最近节点路径更新其余节点移动路径
// update the moving paths of the remaining nodes based on the nearest node
distance[node] = min(distance[node], distance[next_node] + graph[next_node][node]);
}
}

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) {
iota(_pre.begin(), _pre.end(), 0);
//ranges::iota(_pre, 0);
}
int find(int x) {
return _pre[x] == x ? x : _pre[x] = find(_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;
}
};

View File

@ -1,36 +0,0 @@
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;
}
};