Menu

Building Roads | CSES - Algoritmit ongelmanratkaisussa
📰

Building Roads | CSES - Algoritmit ongelmanratkaisussa

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

Problem: https://cses.fi/alon/task/1666

#include <iostream> #include <vector>

using namespace std ;

void dfs ( int u , vector < vector < int >>& graph , vector < bool >& visited ) { if ( visited [ u ] ) return ;

visited [ u ] = true ;

for ( int v : graph [ u ] ) { dfs ( v , graph , visited ) ; } }

int main ( ) { ios_base :: sync_with_stdio ( false ) ; cin . tie ( nullptr ) ;

int n , m ; cin >> n >> m ;

vector < vector < int >> graph ( n + 1 ) ; vector < bool > visited ( n + 1 ) ;

int a , b ; for ( int i = 0 ; i < m ; i ++ ) { cin >> a >> b ; graph [ a ] . push_back ( b ) ; graph [ b ] . push_back ( a ) ; }

vector < int > disconnectedNodes ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! visited [ i ] ) { disconnectedNodes . push_back ( i ) ; dfs ( i , graph , visited ) ; } }

cout << disconnectedNodes . size ( ) - 1 << '\n' ; for ( size_t i = 1 ; i < disconnectedNodes .…

Continue reading — create a free account

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