Hackerearth Bishu and his Girlfriend

/*
Lionel Messi is such a player that you may catch him, you may touch him, you may feel him
and definitely you may Love him.
Lionel Messi is Messi. A little Magician in this World.

*/

// Accepted

#include<bits/stdc++.h>

using namespace std;

#define fast ios_base::sync_with_stdio(0)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define nl puts("")
#define psb push_back
#define loop0(n) for(int i=0; i<n; i++)
#define loop1(n) for(int i=1; i<=n; i++)
#define mpair(x , y) make_pair(x , y)
#define all(x) x.begin(), x.end()
#define pi acos(-1.0)
#define psb push_back

typedef unsigned long long ull;
typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;
typedef vector<string>vs;
typedef map<int, int>mpii;
typedef map<string, int>mpsi;
typedef map<char, int>mpci;
typedef map<LL, LL>mpll;

const int mod = 1000007;
const int high = 10003;


struct printf
{
    void ek(int n){cout << n << "\n";}
    void dui(int x , int y) { cout << x << " " << y << "\n"; }
    void tin(int x , int y , int z) { cout << x << " " << y << " " << z << "\n"; }
}tp;

struct sieve
{
    int prm[high], plen=0;
    bitset<high>bs;
    void get_prime()
    {
        LL i , j;
        bs.set();
        bs[0]=bs[1]=0;
        for(i=2; i<=high; i++)
        {
            if(bs[i])
            {
                prm[plen++] = i;

                for(j=i*i; j<=high; j+=i) bs[j] = 0;
            }
        }
    }
    void pprm(){ for(int i=0; i<100; i++) cout << prm[i] << "; "; }
}prime;

vii adj[high];
bool visited[high];
int par[high];

void dfs(int s)
{
    visited[s] = true;

    //int dif = 0 , sum=0;

    for(int i=0; i<adj[s].size(); i++)
    {
        if(!visited[adj[s][i]])
        {
            //sum += abs(1 - adj[s][i]);

            par[adj[s][i]] = s;

            visited[adj[s][i]] = true;

            dfs(adj[s][i]);
        }
    }

   // return sum;
}

int main()
{
    fast;

    int dif , n , i ,  id=0 , u , v , m  , x , mn=high;

    while(cin >> n)
    {
        m = n-1;

        mn = high;

        memset(visited , false , sizeof visited);
        memset(par , 0 , sizeof par);

        loop0(m)
        {
            cin >> u >> v;

            adj[u].psb(v);
            adj[v].psb(u);
        }

        dfs(1);

        //for(i=1; i<=n; i++) cout << par[i] << "; ";

        int q;
        cin >> q;

        while(q--)
        {
            cin >> x;
            //cout << dfs(1 , x) << "\n";
            dif = abs(1 - par[x]) + abs(x - par[x]);

            if(dif < mn)
            {
                mn = dif;
                id = x;
            }

            else if(dif == mn)
            {
                id = min(id , x);
            }
        }

        outn(id);
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

Uva 10650 - Determinate Prime