Advertisement
MohammedShoaib

Fancy Antiques

Jun 26th, 2020
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 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 (i == m || cnt > k)
  33.             return -1;
  34.         else if (cnt == k) {
  35.             // check if valid vertex cover
  36.             for (int j = 0; j < m; j++)
  37.                 if (!mark[j])
  38.                     for (int& u: adj[j])
  39.                         if (!mark[u])
  40.                             return -1;
  41.             return savings;
  42.         }
  43.         else if (mark[i])
  44.             return state(i + 1, cnt, savings);
  45.  
  46.         int max_s = -1;
  47.         // pick it
  48.         mark[i] = true;
  49.         max_s = state(i + 1, cnt + 1, savings + save[i]);
  50.  
  51.         // don't pick it
  52.         mark[i] = false;
  53.         for (int& u: adj[i])
  54.             if (!mark[u]) {
  55.                 cnt++;
  56.                 mark[u] = true;
  57.                 savings += save[u];
  58.             }
  59.        
  60.         max_s = max(state(i + 1, cnt, savings), max_s);
  61.  
  62.         return max_s;
  63.     };
  64.    
  65.     int res = state(0, 0, 0);
  66.     if (res == -1)
  67.         cout << -1;
  68.     else
  69.         cout << e - res;
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement