Raslboyy

219

Sep 14th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <list>
  5. #include <string>
  6. #include <functional>
  7. #include <algorithm>
  8. #include <climits>
  9.  
  10. using namespace std;
  11.  
  12. int main() {
  13.     ifstream fin("input.txt");
  14.     ofstream fout("output.txt");
  15.  
  16.     int n;
  17.     fin >> n;
  18.     vector<list<int>> vec(n);
  19.     vector<int> cost(n);
  20.     vector<bool> used(n);
  21.     vector<vector<int>> dp(2, vector<int>(n, INT_MAX));
  22.     string str;
  23.     getline(fin, str);
  24.     for (int i = 0; i < n; i++) {
  25.         getline(fin, str);
  26.         int a; int prev = 0;
  27.         for (int j = 0; j < str.size(); j++)
  28.             if (str[j] == ' ' || j == str.size() - 1) {
  29.                 vec[i].emplace_back(atoi(str.substr(prev, 2*str.size() - prev - j).c_str())-1);
  30.                 prev = j + 1;
  31.             }
  32.        
  33.     }
  34.     for (int i = 0; i < n; i++) fin >> cost[i];
  35.  
  36.     function<void(int)> dfs = [&](int curV) {
  37.         used[curV] = 1;
  38.         int sum0 = 0, sum1 = 0;
  39.         for (int to : vec[curV])
  40.             if (!used[to]) {
  41.                 dfs(to);
  42.                 sum0 += dp[1][to];
  43.                 sum1 += min(dp[1][to], dp[0][to]);
  44.             }
  45.                
  46.         dp[0][curV] = min(dp[0][curV], sum0);
  47.         dp[1][curV] = min(dp[1][curV], sum1 + cost[curV]);
  48.     };
  49.     dfs(0);
  50.     fout << min(dp[0][0], dp[1][0]) << endl;
  51.     for (int i = 0; i < n; i++)
  52.         if (dp[1][i] < dp[0][i])
  53.             fout << i+1 << " ";
  54.  
  55.     fin.close();
  56.     fout.close();
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment