Problem:
Given a tree with n nodes we have to find the number of nodes under each sub-tree
The root is 1.
Solution:
we can solve this with dynamic programming
- Determine the bottom nodes of the tree (with no children)
- Assign "weight" 1 to each of the bottom nodes
- Build your way up the tree calculating the "weight" of each node (for example a node with 2 children has "weight" 3)
- That's your answer....
Related Problem:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
vector < int > v[105]; | |
bool visited[105]; | |
int c[105]; | |
int dfs( int x , int par){ | |
visited[x]=true; | |
if(v[x].size()==1 && v[x][0]==par){ ///is leaf node | |
return c[x]; | |
} | |
bool s = false; | |
for(int i=0;i<v[x].size();i++){ | |
int xx = v[x][i]; | |
if(visited[xx]==false){ /// not parent | |
int re = dfs(xx,x); /// get the number of all nodes under xx | |
if(re!=0){ | |
c[x]=c[x]+re; | |
s=true; | |
} | |
} | |
} | |
if(s==true){ | |
return c[x]; | |
} | |
else return 0; | |
} | |
int main(){ | |
int n, m,a,b; | |
cin >> n >> m; | |
for( int i = 0; i < m; i++ ){ | |
cin >> a >> b ; | |
v[a].push_back( b ); | |
v[b].push_back( a ); | |
} | |
for(int i=1;i<=n;i++){ | |
c[i] = 1; | |
} | |
int k = dfs(1,0); | |
k = 0; | |
for(int i=1;i<=n;i++){ | |
cout<<c[i]-1<<"\n"; | |
} | |
return 0; | |
} |
Pragmatic Play brings US online slot machines to NJ - KTNH
ReplyDeleteThe partnership 대전광역 출장샵 will 춘천 출장샵 see Pragmatic 원주 출장마사지 Play bring a 당진 출장샵 suite of online slot machines to to the state of New Jersey, 용인 출장마사지 according to a release from