ProgramAlgTrain/20240919/CSP常考算法模板/最短路径/单源最短路径SPFA(有负边).cpp
2024-09-19 11:11:59 +08:00

62 lines
1009 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
int dis[2501];
bool exist[2501];//标记每个点是否在queue中
struct point
{
int to;
int w;
};
int n,m,s,t;
vector<point> graph[2501];
void SPFA()
{
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0; // 注意起 始点是s
queue<int> q;
q.push(s);
exist[s]=1;
while(q.size()>0)
{
int from=q.front();
q.pop();
exist[from]=0;
for(int i=0;i<graph[from].size();i++)
{
// for(int temp:graph[from])
int to=graph[from][i].to;
int w=graph[from][i].w;
if(dis[from]+w<dis[to])
{
dis[to]=dis[from]+w;
if(exist[to]==0)
{
q.push(to);
exist[to]=1;
}
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> s >> t;
for (int i = 1; i <=m ; i++) {
int a,b,c;
cin >> a >> b >> c;
graph[a].push_back({b,c});
graph[b].push_back({a,c});
}
SPFA();
cout << dis[t] << endl;
return 0;
}