In this HackerEarth Optimal Connectivity problem solution, A company X has a network of N computers. There are N - 1 links in the network, each link connecting a pair of computers. Each link has a particular time lag in between the two computers. It is assured that all the computers are connected.
The engineers at X assume that the current status of the network is a bit slow and they want to improve it. So they experiment with Q computer pairs.
For each of these Q pairs, you are given new direct link's time lag between the pair of computers. If these two computers are directly connected using the new link and some old link is removed from the network, you need to check if the network become better.

A new network is better than older if the sum of all the time lags is strictly lesser in the new network than the old one and the network is still connected.


HackerEarth Optimal Connectivity problem solution


HackerEarth Optimal Connectivity problem solution.

#include<bits/stdc++.h>
#define LL long long int
#define M 1000000007
#define reset(a) memset(a,0,sizeof(a))
#define rep(i,j,k) for(i=j;i<=k;++i)
#define per(i,j,k) for(i=j;i>=k;--i)
#define print(a,start,end) for(i=start;i<=end;++i) cout<<a[i];
#define endl "\n"
LL pow(LL a,LL b,LL m){LL x=1,y=a;while(b > 0){if(b%2 == 1){x=(x*y);if(x>m) x%=m;}y = (y*y);if(y>m) y%=m;b /= 2;}return x%m;}
LL gcd(LL a,LL b){if(b==0) return a; else return gcd(b,a%b);}
LL gen(LL start,LL end){LL diff = end-start;LL temp = rand()%start;return temp+diff;}
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
}

Second solution

#include<bits/stdc++.h>
#define MAX 100005
using namespace std;
const int logN = 20;
int f[MAX][logN],mval[MAX][logN],depth[MAX];
vector<pair<int,int> >v[100005];
void dfs(int u)
{
for(int i=1;i<logN;i++)
{
f[u][i]=f[f[u][i-1]][i-1];
mval[u][i]=max(mval[u][i-1],mval[f[u][i-1]][i-1]);
}
for(auto i:v[u])
{
int ver=i.first,w=i.second;
if(!depth[ver])
{
f[ver][0]=u;
mval[ver][0]=w;
depth[ver]=depth[u]+1;
dfs(ver);
}
}
}
int lca(int x,int y)
{
if(depth[y]>depth[x])swap(x,y);
int ans=0;
for(int i=logN-1;i>=0;i--)
{
if(depth[f[x][i]]>=depth[y])
{
ans=max(ans,mval[x][i]);
x=f[x][i];
}
}
if(x==y)return ans;
for(int i=logN-1;i>=0;i--)
{
if(f[x][i]!=f[y][i])
{
ans=max(ans,max(mval[x][i],mval[y][i]));
x=f[x][i];
y=f[y][i];
}
}
return max(ans,max(mval[x][0],mval[y][0]));
}
int main()
{
int n;
assert(cin>>n);
assert(n>=1 && n<=1e5);
for(int i=1;i<n;i++)
{
int x,y,z;
assert(cin>>x>>y>>z);
assert(x>=1 && x<=n);
assert(y>=1 && y<=n);
assert(x!=y);
assert(z>=1 && z<=1e9);
v[x].push_back({y,z});
v[y].push_back({x,z});
}
depth[1]=1;
dfs(1);
for(int i=1;i<=n;i++)assert(depth[i]);
int q;
assert(cin>>q);
assert(q>=1 && q<=1e5);
while(q--)
{
int x,y,z;
assert(cin>>x>>y>>z);
assert(x>=1 && x<=n);
assert(y>=1 && y<=n);
assert(x!=y);
assert(z>=1 && z<=1e9);
int val=lca(x,y);
if(val>z)cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}