Advertisement
wurdalak007

ДП

Dec 11th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. class Tree{
  9. public:
  10. Tree( int n );
  11. void insert( int first, int second );
  12. int distance( int pos );
  13. int restore_vertex_sum ( int pos );
  14. void update_dist( int pos );
  15. int count_of_child( int pos );
  16. void restore_dist( int parent_pos );
  17.  
  18. private:
  19.  
  20. struct Node{
  21. vector <Node*> children;
  22. int i;
  23. int depth = 0;
  24. int count_of_child = 0;
  25. };
  26.  
  27. vector<Node> root;
  28. };
  29.  
  30. int Tree::count_of_child( int pos ) {
  31. for (int i = 0; i < root[pos].children.size() ; i++) {
  32. root[pos].count_of_child += 1 + count_of_child( root[pos].children[i]->i );
  33. }
  34. return root[pos].count_of_child;
  35. }
  36.  
  37. void Tree::restore_dist( int parent_pos ) {
  38. queue< pair<int,int> > q;
  39.  
  40. for (int i = 0; i < root[parent_pos].children.size(); i++ ) {
  41. q.push(make_pair(parent_pos, root[parent_pos].children[i]->i));
  42. }
  43.  
  44. while( !q.empty() ) {
  45. pair<int, int> elem = q.front();
  46. q.pop();
  47. for (int i = 0; i < root[elem.second].children.size(); i++ ) {
  48. q.push(make_pair(elem.second, root[elem.second].children[i]->i));
  49. }
  50. root[elem.second].depth = root[elem.first].depth - 2*root[elem.second].count_of_child + root[elem.first].count_of_child - 1;
  51. root[elem.second].count_of_child += root[elem.first].count_of_child - root[elem.second].count_of_child;
  52. }
  53.  
  54. for (int i = 0; i < root.size(); i++) {
  55. cout << root[i].depth << endl;
  56. }
  57.  
  58. }
  59.  
  60. int Tree::restore_vertex_sum( int pos ) {
  61. root[pos].depth = 0;
  62. for( int i = 0; i < root[pos].children.size(); i++ ) {
  63. root[pos].depth += 1 + restore_vertex_sum(root[pos].children[i]->i) + root[pos].children[i]->count_of_child;
  64. }
  65. return root[pos].depth;
  66. }
  67.  
  68. void Tree::insert( int first, int second ) {
  69. root[min(first,second)].children.push_back(&root[max(first,second)]);
  70. }
  71.  
  72. Tree::Tree( int n ) :
  73. root(n)
  74. {
  75. for( int i = 0; i < n; i++ ) {
  76. root[i].i = i;
  77. }
  78. }
  79.  
  80. int main() {
  81. int n = 0;
  82. cin >> n;
  83. Tree tree(n);
  84.  
  85. for( int i = 0; i < n - 1; i++ ) {
  86. int x = 0;
  87. int y = 0;
  88. cin >> x >> y;
  89. tree.insert(x, y);
  90. }
  91. tree.count_of_child( 0 );
  92. tree.restore_vertex_sum( 0 );
  93. tree.restore_dist(0);
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement