题意重述
第一行输入点的数量,边的数量,起点和终点的标号。
第二行输入每条边的起终点以及每一条路的花费,除起终点外都是双向路
输出s到t最少的花费。
代码
用spfa
#include<bits/stdc++.h>
using namespace std;
const int N = 2000009, INF = 1e9;
struct node
{//node表示一条边
int to, w;
//to表示路径终点,w表示路径权值
bool operator <(const node &x) const
{
if(w == x.w) return to > x.to;
else return w > x.w;
}
};
bool v[N];//记录节点有没有被访问
int d[N];//记录每一个节点到起点最短路
int n;//节点个数
int m;//边的个数
int s, e;//起点与终点
vector <node> vec[N];
priority_queue <node> q;//优先队列
void dijkstra(int x)
{
for(int i = 1;i <= n;++ i) d[i] = INF, v[i] = false;
//一开始,所有边都不与起点连通
d[x] = 0;//起点到自己的距离为0
q.push((node){x, 0});//起点入队
while(!q.empty())//当优先队列里还有变
{
node e = q.top(), tmp; q.pop();//
v[e.to] = true;
for(int i = 0;i < vec[e.to].size();++ i)
{
tmp = vec[e.to][i];
if(v[tmp.to]) continue;
if(d[tmp.to] > d[e.to] + tmp.w)
{
d[tmp.to] = d[e.to] + tmp.w;
// cout << e.to << " " << tmp.to << " " << d[tmp.to] << endl;
q.push((node) {tmp.to, d[tmp.to]});
}
}
}
return;
}
int main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m >> s >> e;
for(int i = 1, u, v, w;i <= m;++ i)
{//u代表路径起点,v代表路径终点,w代表路径长度
cin >> u >> v >> w;
vec[u].push_back((node) {v, w});//建边
vec[v].push_back((node) {u, w});//建反边
//因为是无向图,建两条边
}
dijkstra(s);//从起点开始
cout << d[e] << endl;//输出答案
return 0;
}