Advertisement
MohammedShoaib

Fancy Antiques

Jun 26th, 2020
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     ios_base::sync_with_stdio(false);
  7.     cin.tie(0);
  8.    
  9.     int n, m, k, e = 0;
  10.     cin >> n >> m >> k;
  11.  
  12.     vector<int> save(m);
  13.     vector<bool> mark(m);
  14.     vector<vector<int>> adj(m);
  15.    
  16.     for (int i = 0; i < n; i++) {
  17.         int a, p, b, q;
  18.         cin >> a >> p >> b >> q;
  19.         a--, b--;
  20.         adj[a].push_back(b);
  21.         adj[b].push_back(a);
  22.         e += max(p, q);
  23.         if (p < q)
  24.             save[a] += q - p;
  25.         else
  26.             save[b] += p - q;
  27.     }
  28.  
  29.     // helper function
  30.     function<int(int, int, int)> state = [&](int i, int cnt, int savings) -> int {
  31.         // base cases
  32.         if (cnt > k)
  33.             return -1;
  34.         else if (i == m) {
  35.             if (cnt == k)
  36.                 return savings;
  37.             else
  38.                 return -1;
  39.         }
  40.         else if (mark[i])
  41.             return state(i + 1, cnt, savings);
  42.  
  43.         int max_s = -1;
  44.  
  45.         // pick it
  46.         mark[i] = true;
  47.         max_s = state(i + 1, cnt + 1, savings + save[i]);
  48.  
  49.         // don't pick it
  50.         mark[i] = false;
  51.         vector<int> done;
  52.         for (int& u: adj[i])
  53.             if (!mark[u]) {
  54.                 cnt++;
  55.                 mark[u] = true;
  56.                 savings += save[u];
  57.                 done.push_back(u);
  58.             }
  59.        
  60.         max_s = max(state(i + 1, cnt, savings), max_s);
  61.         for (int& u: done)
  62.             mark[u] = false;
  63.  
  64.         return max_s;
  65.     };
  66.    
  67.     int res = state(0, 0, 0);
  68.     if (res == -1)
  69.         cout << -1;
  70.     else
  71.         cout << e - res;
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement