題目描述
有一個 nn 個點 mm 條邊的無向圖,請求出從 ss 到 tt 的最短路長度。
輸入格式
第一行四個正整數 n,m,s,tn,m,s,t。 接下來 mm 行,每行三個正整數 u,v,wu,v,w,表示一條連接 u,vu,v,長爲ww 的邊。
輸出格式
輸出一行一個整數,表示答案。
輸入輸出樣例
輸入
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
輸出
7
說明/提示
【數據範圍】 對於 100%100% 的數據,1\le n \le 25001≤n≤2500,1\le m \le
62001≤m≤6200,1\le w \le 10001≤w≤1000。【樣例說明】 5 \to 6 \to 1 \to 45→6→1→4 爲最短路,長度爲 3+1+3 = 73+1+3=7。
代碼實現(模板)
#include<bits/stdc++.h>
using namespace std;
const int MAXV = 3000;
const int INF = 0x3f3f3f3f;
int n, m, s, t;
struct edge{
int u;
int v;
int w;
edge(int _v, int _w): v(_v), w(_w) {}
edge(){}
};
struct node{
int v;
int d;
friend bool operator < (const node &a, const node &b) //重載<號,定義優先隊列的堆排序方式
{
return a.d > b.d;
}
node(int _v, int _d): v(_v), d(_d) {}
node() {}
};
vector<edge> G[MAXV]; //鄰接表存每條邊
priority_queue<node> pq;
int d[MAXV];
bool vis[MAXV];
void dijkstra()
{
fill(d, d+MAXV, INF);
fill(vis, vis+MAXV, false);
pq.push(node(s,0));
d[s] = 0;
while(!pq.empty())
{
int u = pq.top().v;
pq.pop();
if(vis[u])
continue;
vis[u] = true;
if(u == t)
{
printf("%d",d[t]);
break;
}
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i].v;
int l = G[u][i].w;
if(d[u]+l < d[v])
{
d[v] = d[u]+l;
pq.push(node(v, d[v]));
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &s, &t);
for(int i = 1; i <= m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(edge(b, c));
G[b].push_back(edge(a, c));
}
dijkstra();
return 0;
}