Wednesday, February 28, 2018

Happy Vertices

/*                             Name : Arif Khan
                                Date : 1/3/18
                                Problem Title: Happy Vertices
Problem Link : https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/happy-vertices/

*/

#include< bits/stdc++.h >
using namespace std;

vector < int >adj[100001];
vector < int > visited(100001,0);
int ans = 0;

void dfs(int u){

    for(int i = 0; i < adj[u].size() ; i++){
        int v = adj[u][i];
        if(visited[v] == 0){
                visited[v] = adj[v].size() - 1;
            if(visited[v] > visited[u]) ans++;
            dfs(v);
        }
    }
}

int main()
{
    int n , m , x , y;
    cin >> n >> m;
    for(int i = 1; i <= m ; i++){
        cin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    for(int i = 1; i <= n; i++){
        if(visited[i] == 0){
            visited[i] = adj[i].size();
            dfs(i);
        }
    }
    cout << ans << endl;
    return 0;
}

No comments: