|
| 1 | +// Delete Duplicate Folders in System |
| 2 | +#define ALL(x) (x).begin(), (x).end() |
| 3 | +#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++) |
| 4 | +#define REP(i, n) FOR(i, 0, n) |
| 5 | + |
| 6 | +class Solution { |
| 7 | +public: |
| 8 | + static const long P = 1000000007; |
| 9 | + long inv(long x) { |
| 10 | + long s = 1; |
| 11 | + for (; x > 1; x = P%x) |
| 12 | + s = s*(P-P/x)%P; |
| 13 | + return s; |
| 14 | + } |
| 15 | + vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) { |
| 16 | + sort(ALL(paths)); |
| 17 | + unordered_map<string, int> code; |
| 18 | + unordered_map<int, string> name; |
| 19 | + vector<int> a, cur; |
| 20 | + vector<pair<int, int>> ranges; |
| 21 | + for (auto &path: paths) { |
| 22 | + auto res = code.try_emplace(path.back(), code.size()+1); |
| 23 | + int tail = res.first->second; |
| 24 | + if (res.second) |
| 25 | + name.try_emplace(tail, path.back()); |
| 26 | + for (; cur.size() && (cur.size() > path.size() || cur.size() == path.size() && a[cur.back()] != tail); cur.pop_back()) { |
| 27 | + a.push_back(0); |
| 28 | + ranges.emplace_back(cur.back(), a.size()); |
| 29 | + } |
| 30 | + cur.emplace_back(a.size()); |
| 31 | + a.push_back(tail); |
| 32 | + } |
| 33 | + for (; cur.size(); cur.pop_back()) { |
| 34 | + a.push_back(0); |
| 35 | + ranges.emplace_back(cur.back(), a.size()); |
| 36 | + } |
| 37 | + |
| 38 | + long k = code.size()+1, pow = 1; |
| 39 | + vector<long> h(a.size()+1), pw(a.size()); |
| 40 | + REP(i, a.size()) { |
| 41 | + pw[i] = pow; |
| 42 | + h[i+1] = (h[i]+pow*a[i]) % P; |
| 43 | + pow = pow*k % P; |
| 44 | + } |
| 45 | + unordered_map<long, pair<int, int>> seen; |
| 46 | + cur.assign(a.size()+1, 0); |
| 47 | + for (auto [l, r]: ranges) { |
| 48 | + if (r-l == 2) continue; |
| 49 | + long v = (h[r-1]-h[l+1]+P)*inv(pw[l+1]) % P; |
| 50 | + auto res = seen.try_emplace(v, pair<int, int>{l, r}); |
| 51 | + if (!res.second) { |
| 52 | + cur[l]++; |
| 53 | + cur[r]--; |
| 54 | + cur[res.first->second.first]++; |
| 55 | + cur[res.first->second.second]--; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + int acc = 0; |
| 60 | + vector<string> path; |
| 61 | + vector<vector<string>> ans; |
| 62 | + REP(i, a.size()) { |
| 63 | + acc += cur[i]; |
| 64 | + if (a[i]) { |
| 65 | + path.push_back(name[a[i]]); |
| 66 | + if (!acc) |
| 67 | + ans.push_back(path); |
| 68 | + } else |
| 69 | + path.pop_back(); |
| 70 | + } |
| 71 | + return ans; |
| 72 | + } |
| 73 | +}; |
0 commit comments