模板一(vector)常用:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<ll, ll>PII;
const int N = 400010;
ll w[N], a[N];
vector<PII>ed[N];
ll dist[N];
bool st[N];
int n, m;
void dij()
{
memset(dist, 127, sizeof(dist));
dist[1] = a[1];
priority_queue<PII, vector<PII>, greater<PII>>q;
q.push({dist[1], 1});
while(q.size()){
PII k = q.top();
q.pop();
ll v = k.second;
if(st[v]) continue;
st[v] = 1;
for(auto it : ed[v])
{
if(dist[it.first] > dist[v] + it.second + a[it.first])
{
dist[it.first] = dist[v] + it.second + a[it.first];
q.push({dist[it.first], it.first});
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i ++)
{
ll u, v, w;
cin >> u >> v >> w;
ed[u].push_back({v, w});
ed[v].push_back({u, w});
}
dij();
for(int i = 2; i <= n; i ++)
{
cout << dist[i] << " ";
}
cout << endl;
return 0;
}
模板二(数组模拟链表):
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 100010;
int h[N], e[N], ne[N], idx;
int w[N];
int dist[N];
bool st[N];
int n, m;
void add(int x, int y, int c)
{
w[idx] = c;
e[idx] = y;
ne[idx] = h[x];
h[x] = idx++;
}
int dijkstra()
{
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({ 0, 1 });
while(heap.size())
{
PII k = heap.top();
heap.pop();
int ver = k.second, distance = k.first;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if(dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({ dist[j], j });
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
memset(h, -1, sizeof(h));
scanf("%d%d", &n, &m);
while (m--)
{
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
add(x, y, c);
}
cout << dijkstra() << endl;
return 0;
}