2022安徽省合肥市经开区初中组T4-最短的路(short)
题目描述
牛牛被邀请参加安徽省田径爱好者聚会,是在城市n,而牛牛当前所处的城市为1,附近还有很多城市2~n-1,有些城市之间没有直接相连的路,有些城市之间有直接相连的路,这些路都是双向的,当然也可能有多条。现在给出直接相邻城市的路长度,牛牛想知道从城市1到城市n,最短多少距离。
输入格式
输入n, m,表示n个城市和m条路;接下来m行,每行a b c, 表示城市a与城市b有长度为c的路。
1≤n≤2000。 1≤m≤10000。 0≤c≤10000。
输出格式
输出1到n的最短路。如果1到达不了n,就输出-1。
输入输出样例
输入样例1:
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
画写样例1:90
【耗时限制】1000ms 【内存限制】128MB
很明显一道模板dijstra
唯一需要注意的地方就是他可能有重边
不过没有多大影响
废话不多说,上代码
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int N=2005,INF=0x3F3F3F3F;
bool vis[N];
int n,dis[N];
struct Vex{
int v,d;
bool operator < (const Vex& rhs) const {
return d> rhs.d;
}
} vex;
vector<Vex> G[N];
void djs(int u) {
memset(dis,0x3F,sizeof(dis));
memset(vis,0,sizeof(vis));
dis[u]=0;
priority_queue<Vex> pq;
vex.v=u,vex.d=0;
pq.push(vex);
while(!pq.empty()) {
vex = pq.top(); pq.pop();
int v = vex.v, d = vex.d;
if(vis[v]) continue; vis[v] = true;
for(int i=0; i<G[v].size(); i++) {
int j = G[v][i].v;
if(!vis[j] && dis[v] + G[v][i].d < dis[j]) {
dis[j] = dis[v] + G[v][i].d;
vex.v = j, vex.d = dis[j];
pq.push(vex);
}
}
}
}
int main() {
int m, u, v, w,s;
cin >> n >> m;
for(int i=1; i<=m; i++) {
cin >> u >> v >> w;
vex.v = v, vex.d = w;
G[u].push_back(vex);
vex.v = u;
G[v].push_back(vex);
}
djs(1);
if(dis[n]==0x3f3f3f3f) cout<<-1;
else cout<<dis[n];
return 0;
}