b622簡單

CSES 3420|相異元素的子陣列(Distinct Values Subarrays)

能以最後出現位置與不重複視窗計數推導答案,並說明狀態與邊界處理。

解題思路

從左到右掃描,維護最小合法左端 L,以及每個值上次出現的位置。新值出現在 R 時,若之前在 p 出現,左端必須至少移到 p+1,故更新 L=max(L,p+1)。

更新後 [L,R] 恰是以 R 結尾、最長且無重複的區間。所有起點 L..R 都合法,起點小於 L 必含重複,故新增 R-L+1 個子陣列;按右端分類恰好各計一次。

期望時間 O(n),空間 O(n);n≤2×10^5。Python 全部輸入、整數與最後位置表 O(n)。答案最大 n(n+1)/2,C++ 用 long long。

Step-by-step animation

以下為獨立教學例子;每一步呈現實際狀態。

回報動畫錯誤
步驟 1 / 3

步驟 1:讀入第一個 1

讀入第一個 1

1
L
0
答案
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll P = 1000000007;
ll pw(ll a, ll b, ll p = P) {
    ll r = 1;
    for (; b; b >>= 1, a = a * a % p)
        if (b & 1)
            r = r * a % p;
    return r;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, x, L = 0;
    cin >> n;
    unordered_map<int, int> last;
    ll ans = 0;
    for (int r = 0; r < n; r++) {
        cin >> x;
        if (last.count(x))
            L = max(L, last[x] + 1);
        last[x] = r;
        ans += r - L + 1;
    }
    cout << ans << "\n";
}

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

更多