a629困難兩數和配對與互異索引檢查
CPE:Sumsets (UVa 10125)
用 a+b=d−c 將四數搜尋降成二次規模。
解題思路
先排序 S,列出所有 i<j 的兩數和。再由大到小枚舉 d,並枚舉不同於它的 c,在已排序的兩數和中二分搜尋 d−c。只要對應配對的兩個索引都與 c、d 不同,就得到合法 a+b+c=d;第一個成功的 d 即最大。
同一和可能有許多配對,但元素互異時,每個索引對固定目標和最多出現在一個配對中,所以 c、d 合計最多排除兩個配對。只檢查該和的前三個配對就足夠判斷是否存在合法配對,避免重複和造成三次方掃描。程式把和加偏移後與配對索引打包成一個 64 位整數排序,Python 也能降低 tuple 記憶體。n=0 結束,無解印 no solution。
Step-by-step animation
示意:S={2,3,5,7,12}
步驟 1 / 3
先測最大 d
先選 d=12,嘗試 c=7,需要兩數和 5。
d=12
c=7
目標 5
- d−c
- 5
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
const long long bias = 1LL << 30;
while (cin >> n && n) {
vector<long long> a(n);
for (auto &x : a)
cin >> x;
sort(a.begin(), a.end());
long long base = 1LL * n * n;
vector<long long> pairs;
pairs.reserve(n * (n - 1) / 2);
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pairs.push_back((a[i] + a[j] + bias) * base + i * n + j);
sort(pairs.begin(), pairs.end());
bool found = false;
long long answer = 0;
for (int d = n - 1; d >= 0 && !found; --d)
for (int c = 0; c < n && !found; ++c)
if (c != d) {
long long key = (a[d] - a[c] + bias) * base;
auto it = lower_bound(pairs.begin(), pairs.end(), key);
for (int k = 0; k < 3 && it != pairs.end() && *it < key + base; ++k, ++it) {
long long code = *it % base;
int i = code / n, j = code % n;
if (i != c && i != d && j != c && j != d) {
found = true;
answer = a[d];
break;
}
}
}
if (found)
cout << answer << '\n';
else
cout << "no solution\n";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。