int main(int argc, char **argv) { char *file_input = NULL; int c; Node node; Nodes nodes; struct Summary summary; memset(&summary, 0, sizeof(struct Summary)); // options while ((c = getopt(argc, argv, "i:")) != -1) { switch (c) { case 'i': file_input = optarg; break; default: break; } } if (!file_input) { printf("Usage: ./build_tree -i inputs.txt\n"); exit(EXIT_SUCCESS); } // read input file std::ifstream fin(file_input); if (!fin.is_open()) { std::cerr << "open file failure: " << file_input << std::endl; exit(EXIT_FAILURE); } while (!fin.eof()) { std::string uid; std::string balance; if (!std::getline(fin, uid, '\t') || !std::getline(fin, balance, '\n')) { break; } make_user_node(uid.c_str(), atoll(balance.c_str()), &node); nodes.push_back(node); summary.sum += node.sum; } fin.close(); summary.user_count = nodes.size(); // nodes at level 0 should be sorted std::sort(nodes.begin(), nodes.end()); int idx = 0; Nodes parents; parents.reserve(nodes.size()%2 + 1); while (nodes.size() > 1) { if (nodes.size() % 2 == 1) { summary.padding_sum += nodes[nodes.size()-1].sum; nodes.push_back(nodes[nodes.size()-1]); } for (Nodes::iterator it = nodes.begin(); it != nodes.end(); it++) { std::cout << idx++ << "\t" << summary.level << "\t" << it->sum << "\t"; dump_hex(it->hash, 8); std::cout << std::endl; } parents.resize(0); build_parent_nodes(&nodes, &parents); nodes = parents; summary.level++; } std::cout << idx++ << "\t" << summary.level << "\t" << nodes[0].sum << "\t"; dump_hex(nodes[0].hash, 8); std::cout << std::endl; std::cout << "summary:\t" << summary.user_count << "\t" << summary.sum << "\t" << summary.padding_sum << "\t" << summary.level << std::endl; return 0; }