a667中等排序兩數和,二分查詢最近鄰

CPE:Closest Sums (UVa 10487)

預算所有不同位置的兩數和,讓每次查詢只檢查相鄰候選。

前往題目練習 →回報教學錯誤預處理 O(n² log n),每個查詢 O(log n),空間 O(n²)。

解題思路

列舉 i<j,將 a[i]+a[j] 存成陣列後排序。這個條件保證使用兩個不同元素,不會拿同一格兩次。排序後對查詢 q,二分找到第一個 ≥q 的和,所有更右側數都不會更接近 q。

另一個可能最佳值是該位置左鄰,因為它是所有 <q 的和中最大者。因此只需比較這兩個候選,並處理查詢落在範圍外的情形。題目保證沒有最近答案平手。N=0 結束,每組先印 Case k:,每個查詢句子最後加句點。

Step-by-step animation

示意:集合 3,12,17,查詢 q=27

回報動畫錯誤
步驟 1 / 3

列舉

三種不同位置配對得到 15、20、29。

3+12=15
3+17=20
12+17=29
和數量
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
    int n, tc = 0;
    while (cin >> n && n) {
        vector<long long> a(n), sums;
        for (auto &x : a)
            cin >> x;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                sums.push_back(a[i] + a[j]);
        sort(sums.begin(), sums.end());
        int m;
        cin >> m;
        cout << "Case " << ++tc << ":\n";
        while (m--) {
            long long q;
            cin >> q;
            auto it = lower_bound(sums.begin(), sums.end(), q);
            long long answer = it == sums.end() ? sums.back() : *it;
            if (it != sums.begin() && llabs(*(it - 1) - q) < llabs(answer - q))
                answer = *(it - 1);
            cout << "Closest sum to " << q << " is " << answer << ".\n";
        }
    }
}

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

更多