a562中等最早完成區間的線性貪心

CPE:Interesting Sequences (UVa 12385)

一旦找到重複值就選取區間,保留共同端點。

前往題目練習 →回報教學錯誤期望時間 O(N),空間 O(min(N,V)),V為值域。

解題思路

由左往右掃描,seen 保存上次已選區間終點以後出現過的值。若目前值 x 不在 seen,就加入;若 x 已出現,就找到一段以目前位置結束的有趣區間,立即選取,計數加一。

這是最早結束區間的貪心:任何尚未選擇的第一段都不會比目前找到的區間更早結束,以這段替換不會減少後續可選數量。選完要清空舊seen,再放入當前 x,因為下一段允許與本段共用終點;若全部清掉,會漏算 x,x,x 形成的兩段。

Step-by-step animation

示意:1、2、1、3、1

回報動畫錯誤
步驟 1 / 3

掃到位置2

seen含1與2,尚未重複。

1
2
已選
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        unordered_set<int> seen;
        int ans = 0;
        while (n--) {
            int x;
            cin >> x;
            if (seen.count(x)) {
                ++ans;
                seen.clear();
            }
            seen.insert(x);
        }
        cout << ans << '\n';
    }
}

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

更多