nikunjsoni

943-1

May 23rd, 2021
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. class Solution {
  2.     inline static char dp[1 << 12][12];
  3.     inline static char parent[1 << 12][12];
  4.     inline static char olap[12][12];
  5.     inline static char pre[42];
  6.     int overlap(const string& s1, const string& s2) {
  7.         auto s = s2 + "_" + s1;
  8.         int N = s.length();
  9.         memset(pre, 0, sizeof(pre));
  10.         for (int i = 0, j = 1; j < N;) {
  11.             if (s[i] == s[j])
  12.                 pre[++j] = ++i;
  13.             else if (i)
  14.                 i = pre[i];
  15.             else
  16.                 ++j;
  17.         }
  18.         return pre[N];
  19.     }
  20. public:
  21.     string shortestSuperstring(vector<string>& words) {
  22.         int N = words.size();
  23.         memset(dp, 0, sizeof(dp));
  24.         memset(parent, -1, sizeof(parent));
  25.         memset(olap, 0, sizeof(olap));
  26.         for (int i = 0; i < N; ++i)
  27.             for (int j = 0; j < N; ++j)
  28.                 olap[i][j] = overlap(words[i], words[j]);
  29.  
  30.         for (int i = 1; i < 1 << N; ++i) {
  31.             for (int j = 0; j < N; ++j) {
  32.                 int next = i | 1 << j;
  33.                 if (next == i)
  34.                     continue;
  35.                 for (int k = 0; k < N; ++k) {
  36.                     if (!(i & 1 << k))
  37.                         continue;
  38.                     int o = dp[i][k] + olap[k][j];
  39.                     if (o >= dp[next][j]) {
  40.                         dp[next][j] = o;
  41.                         parent[next][j] = k;
  42.                     }
  43.                 }
  44.             }
  45.         }
  46.                
  47.         int best = 0;
  48.         int cur = -1;
  49.         for (int j = 0; j < N; ++j)
  50.             if (dp[(1 << N) - 1][j] >= best) {
  51.                 cur = j;
  52.                 best = dp[(1 << N) - 1][j];
  53.             }
  54.         stack<int> path;
  55.         for (int mask = (1 << N) - 1, prev; cur != -1; ) {
  56.             path.emplace(cur);
  57.             prev = parent[mask][cur];
  58.             mask &= ~(1 << cur);
  59.             cur = prev;
  60.         }
  61.         string result;
  62.         for (int prev = -1, next; !path.empty(); prev = next) {
  63.             next = path.top(), path.pop();
  64.             result += words[next].substr(prev == -1 ? 0 : olap[prev][next]);
  65.         }
  66.         return result;
  67.     }
  68. };
Advertisement
Add Comment
Please, Sign In to add comment