A social network has n people and m friendships. Print how many friends each person has.
What to build
Store the graph as vector<vector<int>> adj(n + 1). For each friendship a b, push b into adj[a] and a into adj[b]. The number of friends of person i is adj[i].size().
Requirements
- Use an adjacency list
- Print the degrees of the vertices 1 to n on one line
Input
The first line has n and m. Each of the next m lines has two different vertices a b; no pair appears twice.
Output
n numbers: the degree of vertex 1, 2, ..., n.
Constraints
1 ≤ n ≤ 100,000. 0 ≤ m ≤ 200,000.
Example
Input:
5 4
1 2
1 3
1 4
4 5
Output:
3 1 1 2 1
Why it works
An undirected edge adds one neighbour to each end, so the size of each list is the number of edges at that vertex. The cost is O(n + m).
Examples
5 4 1 2 1 3 1 4 4 5
3 1 1 2 1
3 0
0 0 0
Hints
Hint 1
vector<vector<int>> adj(n + 1);
Hint 2
For each edge: adj[a].push_back(b); adj[b].push_back(a);
Hint 3
Print adj[i].size() for i from 1 to n.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int> > adj(n + 1);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 1; i <= n; i++) cout << adj[i].size() << " ";
cout << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step