Problem Link: https://cses.fi/alon/task/2138/
A directed acyclic graph consists of n nodes and m edges. The nodes are numbered 1,2,...,n.
Calculate for each node the number of nodes you can reach from that node (including the node itself).
Input
The first input line has two integers n and m: the number of nodes and edges.
Then there are m lines describing the edges. Each line has two distinct integers a and b: there is an edge from node a to node b.
Output
Print n integers: for each node the number of reachable nodes.
Constraints
- 1 <= n <= 5 * 10^4
- 1 <= m <= 10^5
Example
Input:
5 6
1 2
1 3
1 4
2 3
3 5
4 5
Output:
5 3 2 2 1
Solution
#include <iostream>
#include <bitset>
#include <vector>
using namespace std;
const int N = 50001;
bitset<N> reachable[N];
vector<vector<int>> graph;
vector<bool> visited;
void dfs(int u) {
visited[u] = true;
reachable[u][u] = 1;
for (int v : graph[u]) {
if (!visited[v]) {
dfs(v);
}
reachable[u] |= reachable[v];
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
graph.resize(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
}
visited.resize(n + 1, false);
for (int i = 1; i <= n; i++) {
if (visited[i]) continue;
dfs(i);
}
for (int i = 1; i <= n; i++) {
cout << reachable[i].count() << ' ';
}
cout << '\n';
return 0;
}
Top comments (0)