Header Ad

HackerEarth Round Table Meeting problem solution

In this HackerEarth Round Table Meeting problem solution, There are N students in a round table meeting. Each student belongs to a university given in the array A[i], which denotes the university that the ith student belongs to.
There are Q queries of the form x y, denoting two universities. The answer to each query is the minimum time taken by any one of the student from these universities to meet each other.


HackerEarth Round Table Meeting problem solution


HackerEarth Round Table Meeting problem solution.

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define modu 1000000007
#define pb push_back
vector<int> v[1000001];
int bs(int numElems,int b,int target)
{
int low = 0, high = numElems;
while (low != high)
{
int mid = (low + high) / 2;
if (v[b][mid] <= target)
{
low = mid + 1;
}
else
{
high = mid;
}
}
return high;
}
int mod(int a)
{
if(a<0)
return -a;
else
return a;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,q;
cin>>n>>q;
int A[200005];
for(int i=0;i<n;i++)
{
cin>>A[i];
}
for(int i=n;i<2*n;i++)
{
A[i]=A[i-n];
}
for(int i=0;i<2*n;i++)
{
v[A[i]].pb(i);
}
while(q--)
{
int mindiff=200000;
int a,b;
cin>>a>>b;
for(int i=0;i<v[a].size();i++)
{
int y=bs(v[b].size(),b,v[a][i]);
int val=(v[b][y]-v[a][i]);
mindiff=min(mindiff,mod(val));
if(y!=0)
mindiff=min(mindiff,mod(v[a][i]-v[b][y-1]));
}
cout<<mindiff/2<<endl;
}
}


Post a Comment

0 Comments