邻接表代码c++语言
时间: 2023-11-24 09:52:33 浏览: 74
以下是C++语言中邻接表的基本代码实现:
```c++
#include <iostream>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
vector<pair<int, int>> graph[MAXN]; // 邻接表{from, {to, dis}} (即pair<int, int> = {to, dis})
struct cmp{
bool operator()(pair<int, int>& a, pair<int, int>& b) {
return a.second > b.second; // 以pair中的第二个元素,即edg{Vk, Vm}的大小来判断在堆中的位置
}
};
int dijkstra(int start, int end) {
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q;
vector<int> dis(MAXN, INF);
vector<bool> vis(MAXN, false);
dis[start] = 0;
q.push({start, 0});
while (!q.empty()) {
int u = q.top().first;
q.pop();
if (vis[u]) continue;
vis[u] = true;
for (auto& edg : graph[u]) {
int v = edg.first, w = edg.second;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
q.push({v, dis[v]});
}
}
}
return dis[end];
}
int main() {
int n, m, s, t;
cin >> n >> m >> s >> t;
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
graph[v].push_back({u, w}); // 无向图
}
int ans = dijkstra(s, t);
cout << ans << endl;
return 0;
}
```
阅读全文