a360中等區間計數・排序與二分搜尋

APCS 2026/03:觀光旅遊 (ZeroJudge s180)

把總場次改成逐個表演計算區間內旅行團數。

前往題目練習 →回報教學錯誤時間 O(N log N+M log N),空間 O(N);答案最大 N·M=10¹⁰,C++ 使用 long long。

這題在學什麼

每一筆『旅行團抵達日在表演期間內』都貢獻一場。因此可以交換加總順序:不逐天模擬,也不逐團檢查全部表演,而是對每個表演 [s,e] 計算有幾個抵達日落在其中。

將抵達日排序。lower_bound(s) 找到第一個不小於 s 的位置,upper_bound(e) 找到第一個大於 e 的位置;兩者差就是包含首尾的旅行團數。排序保留重複日期,所以同日不同團仍各算一次。所有區間的計數相加,恰好把每個可觀看的團與表演配對計算一次。

Step-by-step animation

第一個公開範例:抵達日排序為 5、7、10

回報動畫錯誤
步驟 1 / 3

處理 [2,5]

只有日期 5 落在包含首尾的區間。

5
7
10
貢獻
1
累計
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    vector<int> t(n);
    for (int &x : t)
        cin >> x;
    sort(t.begin(), t.end());
    long long ans = 0;
    for (int i = 0, s, e; i < m; i++) {
        cin >> s >> e;
        ans += upper_bound(t.begin(), t.end(), e) - lower_bound(t.begin(), t.end(), s);
    }
    cout << ans << '\n';
}

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

更多