In: Computer Science
#include<bits/stdc++.h>
using namespace std;
vector< pair<int,int> > adj[1010];
int main(){
int n, m, s;
cin>>n>>m>>s;
for(int i=0; i<m; i++)
{
int x, y, c;
cin>>x>>y>>c;
adj[x].push_back({y,c});
}
priority_queue< pair<int,int> , vector< pair<int,int> > , greater< pair<int,int> > > pq;
vector<int> dist(n, INT_MAX);
vector<int> visited(n+1, 0);
pq.push({0,s});
dist[s] = 0;
while(!pq.empty())
{
int node = pq.top().second;
pq.pop();
for(vector< pair<int,int> >::iterator it = adj[node].begin(); it!=adj[node].end(); it++)
{
int v = (*it).first;
int weight = (*it).second;
if(dist[v] > dist[node] + weight)
{
dist[v] = dist[node] + weight;
pq.push({dist[v], v});
}
}
}
for(int i=1; i<=n; i++)
{
if(dist[i] == INT_MAX)
cout<<-1<<"\n";
else
cout<<dist[i]<<"\n";
}
return 0;
}
SAMPLE INPUT (content of input-x.txt)
9 14 9
9 1 4
9 7 8
1 2 8
1 7 11
2 3 7
8 2 2
2 5 4
3 4 9
3 5 14
4 5 10
5 6 2
6 7 1
8 6 6
8 7 7
SAMPLE OUTPUT (content of output-x.txt)
4
12
19
28
16
18
8
-1
0