Advertisement
tien_noob

DP bitmask - COCI - LQDOJ - Vjestica

Oct 22nd, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. //Make CSP great again
  2. //You're as beautiful as the day I lost you
  3. #include <bits/stdc++.h>
  4. #define TASK "TESTCODE"
  5. using namespace std;
  6. const int N = 16;
  7. int cnt[N][26];
  8. int dp[1 << N], n;
  9. void read()
  10. {
  11.     cin >> n;
  12.     for (int i = 0; i < n; ++ i)
  13.     {
  14.         string s;
  15.         cin >> s;
  16.         for (char c : s)
  17.         {
  18.             ++cnt[i][c - 'a'];
  19.         }
  20.     }
  21. }
  22. int prefix(int mask)
  23. {
  24.     int h[26];
  25.     fill(h, h + 26, 1e9);
  26.     for (int i = 0; i < n; ++ i)
  27.     {
  28.         if (mask & (1 << i))
  29.         {
  30.             for (int j = 0; j < 26; ++ j)
  31.             {
  32.                 h[j] = min(h[j], cnt[i][j]);
  33.             }
  34.         }
  35.     }
  36.     int ret = 0;
  37.     for (int i = 0; i < 26; ++ i)
  38.     {
  39.         ret += h[i];
  40.     }
  41.     return ret;
  42. }
  43. int f(int mask)
  44. {
  45.     if (mask == 0)
  46.     {
  47.         return 0;
  48.     }
  49.     int &res = dp[mask];
  50.     if (res != -1)
  51.     {
  52.         return res;
  53.     }
  54.     int pre = prefix(mask);
  55.     if (__builtin_popcount(mask) == 1)
  56.     {
  57.         return res = pre;
  58.     }
  59.     res = 1e9;
  60.     for (int i = (mask - 1) & mask; i > 0; i = (i - 1) & mask)
  61.     {
  62.         res = min(res, f(i) + f(mask ^ i) - pre);
  63.     }
  64.     return res;
  65. }
  66. void solve()
  67. {
  68.     memset(dp, -1, sizeof(dp));
  69.     cout << f((1 << n) - 1) + 1;
  70. }
  71. int main()
  72. {
  73.     ios_base::sync_with_stdio(false);
  74.     cin.tie(nullptr);
  75.     if (fopen(TASK".INP", "r"))
  76.     {
  77.         freopen(TASK".INP", "r", stdin);
  78.         //freopen(TASK".OUT", "w", stdout);
  79.     }
  80.     int t = 1;
  81.     bool typetest = false;
  82.     if (typetest)
  83.     {
  84.         cin >> t;
  85.     }
  86.     for (int __ = 1; __ <= t; ++ __)
  87.     {
  88.         //cout << "Case " << __ << ": ";
  89.         read();
  90.         solve();
  91.     }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement