Heat Wave G
Luogu P1339 [USACO09OCT] Heat Wave G
题目描述
有一个 \(n\) 个点 \(m\) 条边的无向图,请求出从 \(s\) 到 \(t\) 的最短路长度。
输入格式
第一行四个正整数 \(n,m,s,t\)。
接下来 \(m\) 行,每行三个正整数 \(u,v,w\),表示一条连接 \(u,v\),长为 \(w\) 的边。
输出格式
输出一行一个整数,表示答案。
输入输出样例 #1
输入 #1
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
输出 #1
7
说明/提示
【数据范围】
对于 \(100\%\) 的数据,\(1\le n \le 2500\),\(1\le m \le 6200\),\(1\le w \le 1000\)。
【样例说明】
\(5 \to 6 \to 1 \to 4\) 为最短路,长度为 \(3+1+3 = 7\)。
Code
神秘模板题
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
int n, m, s, t, cnt, head[2501], to[12401], nxt[12401], w[12401], dist[2501];
void add(int u, int v, int x)
{
to[++cnt] = v;
w[cnt] = x;
nxt[cnt] = head[u];
head[u] = cnt;
}
void dijkstra()
{
fill(dist, dist + n + 1, inf);
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
dist[s] = 0;
pq.push(make_pair(0, s));
while (!pq.empty())
{
pair<int, int> tp = pq.top();
pq.pop();
int d = tp.first, u = tp.second;
if (d > dist[u])
{
continue;
}
if (u == t)
{
return;
}
for (int i = head[u]; i; i = nxt[i])
{
int v = to[i], nd = d + w[i];
if (nd < dist[v])
{
dist[v] = nd;
pq.push(make_pair(nd, v));
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> s >> t;
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
dijkstra();
cout << dist[t];
return 0;
}

浙公网安备 33010602011771号