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;
}

Bishu and his Girlfriend

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

vector< int > adj[1001];
vector< bool >visited(1000,false);
int dsit[1001];

void dfs(int s)
{
    memset(dsit,0,sizeof(dsit));

    stack < int > st;
    st.push(s);
    dsit[s] = 0;

    while(!st.empty()){
        int u = st.top();
        st.pop();
        for(int i = 0; i < adj[u].size() ; i++){
            int v = adj[u][i];

            if(v > dsit[u]+1){
                dsit[v] = dsit[u]+1;
                st.push(v);
            }
        }
    }
}

int main()
{
    int n,m;
    cin >> n;
    for(int i = 0; i < n-1; i++){
        int x,y;
        cin >> x >> y;
        // if undirected graph
        adj[x].push_back(y);
        adj[y].push_back(x); // if directed graph not needed this line
    }
    int res = INT_MAX,q,ans=0;
    cin >> q;
    int mal;
    dfs(1);
    for(int i = 0;i < q; i++){
        cin >> mal;
        if(dsit[mal] < res){
            res = dsit[mal];
            ans = mal;
        }else if(res == dsit[mal]){
            ans = min(ans,mal);
        }
      }
    cout << ans << endl;

    return 0;
}