请编写程序求给定正权有向图的单源最短路径长度。图中包含n个顶点,编号为0至n-1,以顶点0作为源点。
输入格式:
输入第一行为两个正整数n和e,分别表示图的顶点数和边数,其中n不超过20000,e不超过1000。接下来e行表示每条边的信息,每行为3个非负整数a、b、c,其中a和b表示该边的端点编号,c表示权值。各边并非按端点编号顺序排列。
输出格式:
输出为一行整数,为按顶点编号顺序排列的源点0到各顶点的最短路径长度(不含源点到源点),每个整数后一个空格。如源点到某顶点无最短路径,则不输出该条路径长度。
输入样例:
4 4
0 1 1
0 3 1
1 3 1
2 0 1
输出样例:
1 1
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> pII;
const int N=2e4+2;
const int INF=0x3f3f3f3f;
vector<pII> g[N];
priority_queue<pII,vector<pII>,greater<pII> >q;
int n,m;
int dist[N];
bool vis[N];
void dij(int s)
{
for(int i=0;i<n;i++)
{
dist[i]=INF;
}
dist[s]=0;
q.push({0,s});
while (!q.empty())
{
int w=q.top().first;
int u=q.top().second;
q.pop();
if(vis[u]) continue;
vis[u]=true;
for(int i=0;i<g[u].size();i++)
{
pII temp=g[u][i];
if(dist[temp.first]>(w+temp.second))
{
dist[temp.first]=(w+temp.second);
q.push({dist[temp.first],temp.first});
}
}
}
}
int main()
{
int u,v,w;
cin>>n>>m;
for(int i=0;i<m;i++)
{
cin>>u>>v>>w;
g[u].push_back({v,w});
}
dij(0);
for(int i=1;i<n;i++)
{
if(dist[i] !=INF)
{
cout<<dist[i]<<" ";
}
}
return 0;
}