fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n, e; // n = number of nodes, e = number of edges
  6. cin >> n >> e;
  7.  
  8. // Create an adjacency list of size n+1 (1-based indexing)
  9. vector<vector<int>> adjList(n + 1);
  10.  
  11. // Read edges and fill adjacency list
  12. for (int i = 0; i < e; i++) {
  13. int u, v;
  14. cin >> u >> v;
  15. adjList[u].push_back(v); // edge from u to v
  16. adjList[v].push_back(u); // for undirected graph
  17. }
  18.  
  19. // Print adjacency list
  20. cout << "Adjacency List:\n";
  21. for (int i = 1; i <= n; i++) {
  22. cout << i << " -> ";
  23. for (int neighbor : adjList[i]) {
  24. cout << neighbor << " ";
  25. }
  26. cout << endl;
  27. }
  28. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Adjacency List: