Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. FILE*f1;
  6. FILE*f2;
  7.  
  8. const int N = 520;
  9.  
  10. struct Forest{
  11. int weight;
  12. int root;
  13. };
  14.  
  15. struct Tree{
  16. int left;
  17. int right;
  18. int parent;
  19. Tree(): left(-1), right(-1), parent(-1) {}
  20. };
  21.  
  22. Tree tree[N];
  23. Forest forest[256];
  24. int chast[256];
  25. int size_forest;
  26. int size_tree;
  27.  
  28. void mini (Forest f[N], int sz, int & min1, int & min2) {
  29. if (f[0].weight < f[1].weight) {
  30. min1 = 0;
  31. min2 = 1;
  32. } else {
  33. min1 = 1;
  34. min2 = 0;
  35. }
  36.  
  37. for (int i = 2; i < sz; i++) {
  38. if (f[i].weight < f[min1].weight) {
  39. min2 = min1;
  40. min1 = i;
  41. } else {
  42. if (f[i].weight < f[min2].weight) min2 = i;
  43. }
  44. }
  45. }
  46.  
  47. int main() {
  48. f1 = fopen("input.txt", "rb");
  49. //f2 = fopen("input.hfm", "wb");
  50. char ch;
  51.  
  52. while(fscanf(f1, "%c", &ch) != -1) {
  53. chast[ch]++;
  54. }
  55.  
  56.  
  57. for(int i = 0; i < N; i++) {
  58. if(chast[i] > 0) {
  59. forest[size_forest].weight = chast[i];
  60. forest[size_forest].root = size_forest;
  61. size_forest++;
  62. }
  63. }
  64. size_tree = size_forest;
  65. for(int i = size_forest; i > 0; i--) {
  66. int min1, min2;
  67. mini(forest, i, min1, min2);
  68. min1++;
  69. min2++;
  70. size_tree++;
  71. tree[size_tree].left = forest[min1].root;
  72. tree[size_tree].right = forest[min2].root;
  73. tree[forest[min1].root].parent = size_tree;
  74. tree[forest[min2].root].parent = size_tree;
  75. forest[min1].weight = forest[min1].weight + forest[min2].weight;
  76. forest[min1].root = size_tree;
  77. swap(forest[min2], forest[i]);
  78.  
  79. }
  80. cout << endl;
  81. for(int i = 0; i <= 2 * size_tree; i++) {
  82. cout << i << ' ' << tree[i].parent << ' ' ;
  83. cout << tree[i].left << ' ' << tree[i].right << endl;
  84. }
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement