Cut tree in two halfs (dfs implementation )
Cut the tree (dfs application)
https://www.hackerrank.com/challenges/cut-the-tree
In this question , we should cut the tree such that the difference between two halfs would be smallest
as possible .
firstly ,total weight is added as sum. after that:-
It is implemented using recursive dfs. Here each child gives his lower weight to their parents.
#include<bits/stdc++.h>
using namespace std;
int sum=0;
int a[10000000],vis[1000000];
int ans=INT_MAX;
vector<int> v[1000000];
int dfs(int node)
{
vis[node]=1;
int curr=a[node];
for(int i=0;i<v[node].size();i++)
{
if(vis[v[node][i]]==0)
curr+=dfs(v[node][i]);
}
ans=min(ans,abs(sum-curr-curr));
//cout<<curr<<" "<<ans<<endl;
return curr;
vis[node]=0;
}
int main()
{
int n,i,j,k,l,p,q;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>a[i];
sum+=a[i];
}
for(i=1;i<n;i++)
{
cin>>p>>q;
v[p].push_back(q);
v[q].push_back(p);
}
int kk=dfs(1);
cout<<ans<<endl;
return 0;
}
Comments
Post a Comment