Wednesday, February 28, 2018

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

No comments: