单源Dijksitra板子题
题目来源问 N 到 1 的最短距离
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <utility>
#include <cstdio>
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
using namespace std;
typedef pair<int, int>pii;
const int inf = 0x3f3f3f3f;
const int N = 4e3 + 10;
const int M = 1e3 + 10;
int head[N], edge[N], ver[N], nxt[N], tot;
int t, n;
bool v[M];
int d[M];
void add(int x, int y, int v)
{
ver[++tot] = y, edge[tot] = v, nxt[tot] = head[x], head[x] = tot;
return;
}
void dijksitra()
{
memset(d, 0x3f, sizeof(d));
memset(v, 0, sizeof(v));
d[1] = 0;
priority_queue<pii>q;
q.push(make_pair(0, 1));
while (!q.empty())
{
int x = q.top().second;
q.pop();
if (v[x])
continue;
v[x] = 1;
for (int i = head[x]; i; i = nxt[i])
{
int y = ver[i], z = edge[i];
if (d[y] > d[x] + z)
{
d[y] = d[x] + z;
q.push(make_pair(-d[y], y));
}
}
}
cout << d[n] << endl;
}
int main()
{
IOS;
cin >> t >> n;
int x, y, z;
for (int i = 1; i <= t; i++)
{
cin >> x >> y >> z;
add(x, y, z), add(y, x, z);
}
dijksitra();
return 0;
}