题解 CF1535F String Distance
link
题意:
给出
n 个长度为m 的串s_i 。对于两个串S,T ,选取其中一个串中的一个区间进行排序称为一次操作,f(S,T) 表示使得S,T 相同的最少操作次数。求\sum_{i=1}^n\sum_{j=i+1}^nf(s_i,s_j) 。
介绍一个比较优雅的严格
首先只有字符种类的数量相同的两个串,才能通过若干次操作变得相同,所以我们把这些串分成若干个集合分别处理。
然后我们想同一集合里的两个串
- 一般情况只需要对两个串的
[l,r] 区间分别排序,操作次数最多为2 ; - 如果其中一个串的
[l,r] 区间原本就是有序的,操作次数为1 ; - 如果
S=T ,不存在这样的区间,操作次数为0 。
只需要统计第二、三种情况的数量就可以得到答案。
入手点在于第二种,我们固定一个串
首先将集合内所有串排序为
- 两两相邻的点求
\operatorname{LCP} ,那么任意两个串的\operatorname{LCP} 就是区间最小值; - 对于区间
[1,l-1] 相同的若干个串,[l,r] 有序的串一定排在前面。
对于固定的串
而
对于单调栈每个元素代表的区间
那么怎么统计
考虑 Trie 树,将所有串
code
#include <bits/stdc++.h>
using i64 = long long;
struct Trie {
int tot;
std::vector<std::vector<int>> id;
std::vector<std::array<int, 26>> ch;
Trie() {}
Trie(int n) : tot(1), id(n), ch(n, std::array<int, 26>{}) {}
std::vector<int> rev_insert(std::string &s, int k) {
int n = s.length();
std::vector<int> pos(n + 1);
int p = 1;
id[1].push_back(k);
pos[n] = 1;
for (int i = n - 1; ~i; --i) {
int c = s[i] - 'a';
if (!ch[p][c])
ch[p][c] = ++tot;
p = ch[p][c];
id[p].push_back(k);
pos[i] = p;
}
return pos;
}
int query(int p, int l, int r) {
return std::lower_bound(id[p].begin(), id[p].end(), r) -
std::lower_bound(id[p].begin(), id[p].end(), l);
}
};
i64 solve(std::vector<std::string> a) {
int n = a.size();
int m = a[0].length();
std::sort(a.begin(), a.end());
Trie tr(n * m + 2);
std::vector<std::vector<int>> pos(n);
for (int i = 0; i < n; ++i)
pos[i] = tr.rev_insert(a[i], i);
std::vector<int> lcp(n);
for (int i = 1; i < n; ++i) {
int j = 0;
while (j < m && a[i][j] == a[i - 1][j])
++j;
lcp[i] = j;
}
std::vector<std::vector<int>> dec(n); // 极大有序子区间的分界点
for (int i = 0; i < n; ++i) {
for (int j = 1; j < m; ++j)
if (a[i][j] < a[i][j - 1])
dec[i].push_back(j);
dec[i].push_back(m);
}
i64 res = (i64) n * (n - 1);
std::vector<std::pair<int, int>> stk;
stk.emplace_back(n, -1);
for (int i = n - 1; ~i; --i) {
for (int j = 1; j < int(stk.size()); ++j) {
int l = stk[j].first, r = stk[j - 1].first;
int p = stk[j].second;
if (p < m) {
p = *std::upper_bound(dec[i].begin(), dec[i].end(), p);
res -= tr.query(pos[i][p], l, r);
}
else res -= (r - l) * 2; // S = T
}
while (stk.back().second >= lcp[i])
stk.pop_back();
stk.emplace_back(i, lcp[i]);
}
return res;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::map<std::string, std::vector<std::string>> map;
for (int i = 0; i < n; ++i) {
std::string s;
std::cin >> s;
std::string t = s;
std::sort(t.begin(), t.end());
map[t].push_back(s);
}
int pre_sum = 0;
i64 ans = 0;
for (auto i : map) {
auto &a = i.second;
ans += (i64) a.size() * pre_sum * 1337;
ans += solve(a);
pre_sum += a.size();
}
std::cout << ans << '\n';
return 0;
}