求最短路优化Dijkstra
#include<bits/stdc++.h>
#define inf 2147483647
using namespace std;
struct edge
{
int to,cost;
edge(int a,int b):to(a),cost(b){} ;
};
typedef pair<int,int> P;
int main()
{
int n,m,s;
cin>>n>>m>>s;
vector<edge> G[n+1];
int d[n+1];
fill(d,d+n+1,inf);
for(int i=0; i<m; i++)
{
int a,b,c;
cin>>a>>b>>c;
G[a].push_back(edge(b,c));
}
priority_queue<P,vector<P>,greater<P> > q;
d[s] = 0;
q.push(P(0,s));
while(!q.empty())
{
P p = q.top();
q.pop();
int v = p.second;
if(d[v] < p.first)
continue;
for(int i=0; i<G[v].size(); i++)
{
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost)
{
d[e.to] = d[v] + e.cost;
q.push(P(d[e.to],e.to));
}
}
}
int i;
for(i=1; i<n; i++)
{
cout<<d[i]<<" ";
}
cout<<d[i]<<endl;
return 0;
}