Cod sursa(job #2969825)

Utilizator sandry24Grosu Alexandru sandry24 Data 23 ianuarie 2023 19:18:07
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second

vector<vi> adj(100001);
vector<bool> visited(100001);

void dfs(int x){
    visited[x] = 1;
    for(auto i : adj[x]){
        if(!visited[i])
            dfs(i);
    }
}
 
void solve(){
    int n, m;
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        int a, b;
        cin >> a >> b;
        adj[a].pb(b);
    }
    int ans = 0;
    for(int i = 1; i <= n; i++){
        if(!visited[i]){
            ans++;
            dfs(i);
        }
    }
    cout << ans << '\n';
}  
 
int main(){
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    ios::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}