short-path problem (Spfa) 分类: ACM TYPE 2014-09-02 00:30 103人阅读 评论(0) 收藏

时间:2023-03-08 16:35:06

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
#define INF 0x7fffffff
struct edge
{
int t;
long long d;
}; vector<edge> g[20005];
int n, m, p, q; void Spfa(int x)
{
int minn = 0; queue<int>q;
long long dis[20005];
bool vis[20005];
memset(vis,false,sizeof(vis)); for(int i = 0; i <= n; i++)
dis[i] = INF; vis[x] = true;
dis[x] = 0;
q.push(x); while(q.size())
{
int tmp = q.front();
q.pop();
vis[tmp] = false; for(int i = 0; i < g[tmp].size(); ++i)
{
if(dis[g[tmp][i].t] > dis[tmp] + g[tmp][i].d)
{
dis[g[tmp][i].t] = dis[tmp] + g[tmp][i].d;
if(vis[g[tmp][i].t] == false)
{
q.push(g[tmp][i].t);
vis[g[tmp][i].t] = true;
}
}
}
} for(int i = 2; i <= n; ++i)
{
cout<<dis[i]<<endl;
} } int main()
{
memset(g,0,sizeof(g)); cin>>n>>m; q = 1; for(int i = 0; i < m; ++i)
{
int x, y, s;
edge e;
cin>>x>>y>>s;
e.t = y;
e.d = s;
g[x].push_back(e);
} Spfa(q); return 0;
}

算法训练 最短路

版权声明:本文为博主原创文章,未经博主允许不得转载。