fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node{
  5. int src;
  6. node *next;
  7. };
  8.  
  9. struct Graph{
  10. int vertex;
  11. node **adj;
  12. };
  13.  
  14. int main() {
  15. int V, E;
  16. cin >> V >> E; // number of vertices and edges
  17.  
  18. Graph *g = new Graph();
  19. g->vertex = V;
  20. g->adj = new node*[V];
  21. for(int i=0; i<V; i++)
  22. g->adj[i] = NULL;
  23.  
  24. for(int i=0; i<E; i++) {
  25. int u, v;
  26. cin >> u >> v; // edge from u to v (directed graph)
  27.  
  28. node *temp = new node();
  29. temp->src = u;
  30. temp->next = g->adj[v];
  31. g->adj[v] = temp;
  32. }
  33.  
  34. for(int v=0; v<V; v++) {
  35. cout << "Edges ending at " << v << " come from : [ ";
  36. node *temp = g->adj[v];
  37. while(temp!=NULL) {
  38. cout << temp->src <<" ";
  39. temp = temp->next;
  40. }
  41. cout << "]" <<endl;
  42. }
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 15232KB
stdin
4 5
0 1
0 2
1 2
1 3
2 3
stdout
Edges ending at 0 come from : [ ]
Edges ending at 1 come from : [ 0 ]
Edges ending at 2 come from : [ 1 0 ]
Edges ending at 3 come from : [ 2 1 ]