題目網址

解題說明:

題目是要找出有幾 a + b + c + d 為 0 的組合有幾個,可以先把 a 跟 b 相加的組合儲存在變數 ab 裡,然後對她 sort , 之後再對 -c 跟 -d 的合的組合一一列出,然後找出在變數 ab 裡的 upper_bound 跟 lower_bound,相減的合及為答案。

範例code:

#include <bits/stdc++.h>
using namespace std;
const int INF = 40001;
int main(int argc, char const *argv[]){
    int nc;
    int a[INF], b[INF], c[INF], d[INF], ab[16000000];
    cin >> nc;
    while (nc--){
        int n;
        cin >> n;
        for (int i = 0; i < n; i++)
            cin >> a[i] >> b[i] >> c[i] >> d[i];
        int t = 0;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                // 紀錄 a 跟 b 所有的合
                ab[t++] = a[i] + b[j];
            }
        }
        int ans = 0;
        sort(ab, ab + t);
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                ans += (upper_bound(ab, ab + t, -c[i] - d[j]) - lower_bound(ab, ab + t, -c[i] - d[j]));
            }
        }
        cout << ans << endl;
        if (nc)
            cout << endl;
    }
    return 0;
}