Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- FILE*f1;
- FILE*f2;
- const int N = 520;
- struct Forest{
- int weight;
- int root;
- };
- struct Tree{
- int left;
- int right;
- int parent;
- Tree(): left(-1), right(-1), parent(-1) {}
- };
- Tree tree[N];
- Forest forest[256];
- int chast[256];
- int size_forest;
- int size_tree;
- void mini (Forest f[N], int sz, int & min1, int & min2) {
- if (f[0].weight < f[1].weight) {
- min1 = 0;
- min2 = 1;
- } else {
- min1 = 1;
- min2 = 0;
- }
- for (int i = 2; i < sz; i++) {
- if (f[i].weight < f[min1].weight) {
- min2 = min1;
- min1 = i;
- } else {
- if (f[i].weight < f[min2].weight) min2 = i;
- }
- }
- }
- int main() {
- f1 = fopen("input.txt", "rb");
- //f2 = fopen("input.hfm", "wb");
- char ch;
- while(fscanf(f1, "%c", &ch) != -1) {
- chast[ch]++;
- }
- for(int i = 0; i < N; i++) {
- if(chast[i] > 0) {
- forest[size_forest].weight = chast[i];
- forest[size_forest].root = size_forest;
- size_forest++;
- }
- }
- size_tree = size_forest;
- for(int i = size_forest; i > 0; i--) {
- int min1, min2;
- mini(forest, i, min1, min2);
- min1++;
- min2++;
- size_tree++;
- tree[size_tree].left = forest[min1].root;
- tree[size_tree].right = forest[min2].root;
- tree[forest[min1].root].parent = size_tree;
- tree[forest[min2].root].parent = size_tree;
- forest[min1].weight = forest[min1].weight + forest[min2].weight;
- forest[min1].root = size_tree;
- swap(forest[min2], forest[i]);
- }
- cout << endl;
- for(int i = 0; i <= 2 * size_tree; i++) {
- cout << i << ' ' << tree[i].parent << ' ' ;
- cout << tree[i].left << ' ' << tree[i].right << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement