fork(1) download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main(){
  6. map<int , vector< pair<int, int > > > adjList; // Seems like torture xD
  7.  
  8. /***********Explanation************
  9.   * Abstract form of a map = map< key, value >
  10.   * Here key = int,
  11.   * Value = vector of pairs
  12.   * Key is actually a node(let's say N) of graph here and
  13.   * Value is the vector containing all the nodes which are
  14.   * connected to N directly.
  15.   * Why we need pair< d1, d2 > ?
  16.   * d2 = node connected to N directly.
  17.   * d1 = weight of edge between N and d2.
  18.   * For unweighted graph we can use only int instead of pair
  19.   * or we can keep value 0 for all edges if we use pair of
  20.   * int like shown below.
  21.   *************************************/
  22. // Suppose we are given number of edges 'n' and all the edges in form of (u, v).
  23. // So we can use a for loop to scan inputs.
  24.  
  25. int n;
  26. cin >> n;
  27. for(int i = 0 ; i < n ; i ++){
  28. int u, v;
  29. cin >> u >> v;
  30. // If graph is undirected:
  31. /* 1. */ adjList[u].push_back(make_pair(0, v));
  32. /* 2. */ adjList[v].push_back(make_pair(0, u));
  33. // If graph is directed from u to v
  34. // Then no need to write 2nd statement.
  35. }
  36.  
  37. // Print Adjacency List
  38.  
  39. for(map<int , vector< pair<int, int > > >::iterator it = adjList.begin() ; it != adjList.end() ; it++){
  40. cout << it->first << " : ";
  41. vector<pair<int, int> > neighbours = it->second;
  42. for(int i = 0 ; i < neighbours.size() ; i++){
  43. cout << "(" << neighbours[i].first << " " << neighbours[i].second << ")";
  44. }
  45. cout << endl;
  46. }
  47.  
  48.  
  49.  
  50. }
Success #stdin #stdout 0s 16064KB
stdin
7
1 5
1 2
2 5
3 4
3 2
4 5
6 4
stdout
1 : (0 5)(0 2)
2 : (0 1)(0 5)(0 3)
3 : (0 4)(0 2)
4 : (0 3)(0 5)(0 6)
5 : (0 1)(0 2)(0 4)
6 : (0 4)