Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- int label;
- int* d;
- int n;
- int result = 0;
- int waiting = 0;
- vector<int> arr[222222];
- vector<int> ans[222222];
- void dfs(int vertex, vector<int>* arr) {
- d[vertex - 1] = 0;
- if (arr[vertex - 1].size() > 0) {
- for (auto i = arr[vertex - 1].begin(); i != arr[vertex - 1].end(); ++i) {
- d[vertex - 1]++;
- dfs(*i, arr);
- d[vertex - 1] += d[*i - 1];
- }
- }
- }
- vector<int> main_dfs(int vertex, vector<int>* array, int ind) {
- vector<vector<int>> V;
- if (array[vertex - 1].size() > 0) {
- for (int i = 0; i < array[vertex - 1].size(); ++i) {
- V.push_back(main_dfs(array[vertex - 1][i], array, ind - 1));
- }
- }
- else {
- vector<int> labels(n);
- labels[ind] = vertex;
- V.push_back(labels);
- }
- sort(V.begin(), V.end());
- vector<int> res(n);
- int I = ind;
- for (int i = V.size() - 1; i >= 0;i--) {
- for (int j = V[i].size() - 1; j >= 0;j--) {
- if (V[i][j] != 0)
- res[I--]=V[i][j];
- }
- }
- return res;
- }
- bool comp(const int& a, const int& b) {
- if (d[a - 1] < d[b - 1]) {
- return true;
- }
- else if (d[a - 1] == d[b - 1] && a > b) {
- return true;
- }
- else return false;
- }
- int main() {
- ifstream in("input.txt");
- int root;
- in >> n >> root;
- string str = "";
- int index = 0, amount = 0;
- getline(in, str);
- while (!in.eof()) {
- getline(in, str);
- str += ":";
- int ind1, ind2;
- ind1 = str.find(":");
- int index = atoi(str.substr(0, ind1).c_str());
- ind2 = str.find(":", ind1 + 1);
- int amount = atoi(str.substr(ind1 + 1, ind2).c_str());
- ind1 = ind2;
- ind2 = str.find(":", ind1 + 1);
- while (ind2 != string::npos) {
- arr[index - 1].push_back(atoi(str.substr(ind1 + 1, ind2).c_str()));
- ind1 = ind2;
- ind2 = str.find(":", ind1 + 1);
- }
- }
- in.close();
- label = n;
- vector<int> labels(n);
- d = new int[n];
- dfs(root, arr);
- for (int i = 0; i < n; i++) {
- sort(arr[i].begin(), arr[i].end(), comp);
- }
- vector<int> answer = main_dfs(root, arr, n - 1);
- for (int i = 0; i < n; i++) {
- result += waiting;
- waiting -= arr[labels[i] - 1].size();
- waiting++;
- }
- ofstream out("output.txt");
- out << result << endl;
- for (int i = 0; i < n - 1; i++) {
- out << labels[i] << " ";
- }
- out << labels[n - 1];
- out.close();
- //system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement