给一个 n(1≤n≤2500) 个点 mm(1≤m≤6200) 条边的无向图,求 s 到 t 的最短路。
输入格式
第一行四个由空格隔开的整数 n、m、s、t。
之后的 m 行,每行三个正整数 si、ti、wi wi(1≤wi≤109),表示一条从 si 到 ti 长度为 wi 的边。输出格式
一个整数表示从 s 到 t 的最短路长度。数据保证至少存在一条道路。
样例
Inputcopy Outputcopy
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
#include <bitset>
#include <iostream>
#include <cstring>
#include <utility>
#include <queue>
#include <cmath>
#include <string>
using namespace std;
constexpr int N=3000,M=200000;
int n,m,s,tt;
int dist[N],tot;
struct node{
int nex,to,w;
}edge[M];
int head[M];
bitset<N>vis=0;
vector<pair<int,int>>adj[M];
int spfa(){
memset(dist,0x3f,sizeof(dist));
dist[s]=0;
queue<int>q;
q.push(s);
vis[s]= 1;
while(!q.empty()){
int z=q.front();
q.pop();
vis[z]=0;
for(const auto &[j,w]:adj[z]){
if(dist[j]>dist[z]+w) {
dist[j] = dist[z]+w;
if (vis[j] == 0) {
q.push(j);
vis[j] = 1;
}
}
}
}
return dist[tt];
}
int main(){
memset(head,-1,sizeof(head));
scanf("%d%d%d%d",&n,&m,&s,&tt);
for(int i=1;i<=m;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
adj[u].push_back(make_pair(v,w));
adj[v].push_back(make_pair(u,w));
}
printf("%d", spfa());
}