In this HackerEarth Finding pairs problem solution You are given a rooted tree with N nodes and node 1 as a root. There is a unique path between any two nodes. Here, d(i,j) is defined as a number of edges in a unique path between nodes i and j.

You have to find the number of pairs (i,j) such that and d(i,j) = d(i,1) - d(j,1).


HackerEarth Finding pairs problem solution


HackerEarth Finding pairs problem solution.

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

#define FAST ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,lessl<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define int long long
#define double long double

#define all(a) (a).begin(),(a).end()
#define sz(x) (int)x.size()

#define ff first
#define ss second
#define mp make_pair

#define pb push_back
#define endl "\n"

#define f(i,l,r) for(int i=l;i<=r;i++)
#define rf(i,r,l) for(int i=r;i>=l;i--)

#define bp __builtin_popcountll
#define inf 1e18

const int N=1e5+5;
const int M=1e9+7;
vector<int> v[N];
vector<int> lvl(N,0);
void dfs(int x,int p)
{
for(auto X:v[x])
{
if(X==p) continue;
lvl[X]=lvl[x]+1;
dfs(X,x);
}
}
void solve()
{
int n;
cin>>n;
for(int i=1;i<n;i++)
{
int t1,t2;
cin>>t1>>t2;
v[t1].pb(t2);
v[t2].pb(t1);
}
lvl[1]=1;
dfs(1,0);
int ans=0;
for(int i=1;i<=n;i++)
ans+=lvl[i];

cout<<ans<<endl;
}

signed main()
{
FAST

int t=1;
// cin>>t;
for(int tc=1;tc<=t;tc++)
{
// cout<<"Case #"<<tc<<": ";
solve();
}
}

Second solution

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

#define FAST ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,lessl<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define int long long
#define double long double

#define all(a) (a).begin(),(a).end()
#define sz(x) (int)x.size()

#define ff first
#define ss second
#define mp make_pair

#define pb push_back
#define endl "\n"

#define f(i,l,r) for(int i=l;i<=r;i++)
#define rf(i,r,l) for(int i=r;i>=l;i--)

#define bp __builtin_popcountll
#define inf 1e18

const int N=1e5+5;
const int M=1e9+7;
vector<int> v[N];
vector<int> lvl(N,0);
void dfs(int x,int p)
{
for(auto X:v[x])
{
if(X==p) continue;
lvl[X]=lvl[x]+1;
dfs(X,x);
}
}
void solve()
{
int n;
cin>>n;
for(int i=1;i<n;i++)
{
int t1,t2;
cin>>t1>>t2;
v[t1].pb(t2);
v[t2].pb(t1);
}
lvl[1]=1;
dfs(1,0);
int ans=0;
for(int i=1;i<=n;i++)
ans+=lvl[i];

cout<<ans<<endl;


}

signed main()
{
FAST

int t=1;
// cin>>t;
for(int tc=1;tc<=t;tc++)
{
// cout<<"Case #"<<tc<<": ";
solve();
}
}