Menu

Reachable Nodes | CSES - Algoritmit ongelmanratkaisussa
📰

Reachable Nodes | CSES - Algoritmit ongelmanratkaisussa

DEV Community: cpp·Guhan M·6 days ago
#j9cDjJhY
#devtocpp#devto#dev#include#node
Long article (395 words) — no AI summary yet.
Reading 0:00
15s threshold

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 ( !…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.