fork(15) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(void){
  4. int n,m,u,v,w;
  5. list<pair<int, int> > adj[100];
  6. cin>>n>>m;
  7. for(int i=0; i<m; i++){
  8. cin>>u>>v>>w;
  9. adj[u].push_back(make_pair(v,w));
  10. adj[v].push_back(make_pair(u,w));
  11. }
  12. bool inMst[n];
  13. int keys[n],parent[n];
  14. for(int i=0; i<n; i++){
  15. inMst[i]=false;
  16. keys[i]=INT_MAX;
  17. parent[i]=-1;
  18. }
  19. priority_queue<pair<int, int> , vector<pair<int, int> >, greater<pair<int, int> > >pq;
  20. int src=0;
  21. pq.push(make_pair(0,src));
  22. keys[src]=0;
  23. while(!pq.empty()){
  24. int U = pq.top().second;
  25. pq.pop();
  26. inMst[U]=true;
  27. for(auto it=adj[U].begin(); it!=adj[U].end(); it++){
  28. int V = it->first;
  29. int weight = it->second;
  30. if(inMst[V]==false && keys[V]>weight){
  31. keys[V]=weight;
  32. pq.push(make_pair(keys[V],V));
  33. parent[V]=U;
  34. }
  35. }
  36. }
  37. for(int i=1; i<n; i++){
  38. cout<<parent[i]<<" "<<i<<" "<<keys[i]<<endl;
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0s 3476KB
stdin
9 13
0 1 4
0 7 8
1 2 8
1 7 11
2 3 7
2 8 2
2 5 4
3 4 9
3 5 14
4 5 10
5 6 2
6 7 1
6 8 6
7 8 7
stdout
0 1 4
1 2 8
2 3 7
3 4 9
2 5 4
5 6 2
6 7 1
2 8 2