a313困難字典序相鄰 LCP・單調堆疊求區間最小值總和

TOI 2023/04 潛力組:姓名分析

不用建立百萬個字典節點,也能累加每個姓名與其他姓名的共同開頭長度。

前往題目練習 →回報教學錯誤令 S≤10⁶ 為總字元數。字典序排序保守計 O(S log N) 字元比較;相鄰 LCP 與兩趟堆疊 O(S+N),空間 O(S+N)。姓名長度可達 3000,程式不使用遞迴。

解題思路

將姓名依字典序排序,記錄相鄰姓名的 LCP 長度 l[i]。排序後第 i 到第 j 個姓名的共同開頭長度恰為 l[i+1..j] 的最小值:共同前綴形成連續區間,所以中途任何一對斷掉的地方就是整段的限制。重複姓名仍保存不同的原始編號。

向右掃描 l,維護以目前位置結尾的所有區間最小值總和。堆疊節點存(最小值、代表的起點數);加入 x 時把頂端≥x 的群組合併,從總和扣掉舊貢獻再加 x×群組大小。得到每個姓名與左邊所有人的 LCP 和;反向再做一次得到右邊貢獻,兩者相加後按原始編號輸出,不會包含自己。

Step-by-step animation

公開範例排序後:CAR、CART、CAT、DOG

回報動畫錯誤
步驟 1 / 3

加入 CART

CAR 與 CART 的 LCP 為 3。

CAR
CART
堆疊
(3,1)
CART 左和
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<pair<string, int>> names(n);
    for (int i = 0; i < n; ++i) {
        cin >> names[i].first;
        names[i].second = i;
    }
    sort(names.begin(), names.end());
    vector<int> lcp(n, 0);
    for (int i = 1; i < n; ++i) {
        auto &a = names[i - 1].first;
        auto &b = names[i].first;
        while (lcp[i] < (int)min(a.size(), b.size()) && a[lcp[i]] == b[lcp[i]])
            ++lcp[i];
    }
    vector<long long> ans(n);
    vector<pair<int, int>> st;
    long long sum = 0;
    for (int i = 1; i < n; ++i) {
        int x = lcp[i], count = 1;
        while (!st.empty() && st.back().first >= x) {
            sum -= 1LL * st.back().first * st.back().second;
            count += st.back().second;
            st.pop_back();
        }
        st.push_back({x, count});
        sum += 1LL * x * count;
        ans[names[i].second] += sum;
    }
    st.clear();
    sum = 0;
    for (int i = n - 2; i >= 0; --i) {
        int x = lcp[i + 1], count = 1;
        while (!st.empty() && st.back().first >= x) {
            sum -= 1LL * st.back().first * st.back().second;
            count += st.back().second;
            st.pop_back();
        }
        st.push_back({x, count});
        sum += 1LL * x * count;
        ans[names[i].second] += sum;
    }
    for (auto x : ans)
        cout << x << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多