fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int main() {
  5.  
  6. // V = number of vertices
  7. // E = number of edges
  8. int V, E;
  9. int x, y, w;
  10. std::cin >> V >> E;
  11. std::vector <std::vector <std::pair <int, int> > > graph_directed(V);
  12. std::vector <std::vector <std::pair <int, int> > > graph_undirected(V);
  13.  
  14. // assuming 0-based indexing of vertices
  15. for(int i = 0; i < E; i++) {
  16. std::cin >> x >> y >> w;
  17. graph_directed[x].push_back({y, w}); // adding a single edge in directed
  18.  
  19. graph_undirected[x].push_back({y, w});
  20. graph_undirected[y].push_back({x, w}); // adding both the edges in undirected
  21. }
  22.  
  23. // Printing graph (showing only undirected but the code is same for both)
  24. for(int i = 0; i < graph_undirected.size(); i++) {
  25. std::cout << i << ": ";
  26. for(int j = 0; j < graph_undirected[i].size(); j++)
  27. std::cout << "{" << graph_undirected[i][j].first << ", " << graph_undirected[i][j].second << "} ";
  28. std::cout << std::endl;
  29. }
  30. return 0;
  31. }
Success #stdin #stdout 0s 15240KB
stdin
3 3
0 1 10
1 2 15
0 2 20
stdout
0: {1, 10} {2, 20} 
1: {0, 10} {2, 15} 
2: {1, 15} {0, 20}