b206中等

100 彰雲嘉區資訊學科能力競賽(2011)|導彈攔截

計算每顆導彈到兩系統的平方距離(d1,d2),按d1排序。

解題思路

計算每顆導彈到兩系統的平方距離(d1,d2),按d1排序。

若系統1覆蓋排序前i顆,它最小需半徑平方d1[i-1];剩餘導彈全由系統2覆蓋,需要其d2最大值。

預先求d2後綴最大值,枚舉i=0到M取兩者和最小。任何最優第一半徑都可縮到某個導彈距離,故這些候選完整。

時間 O(M log M),空間 O(M),大座標採任意精度。

Step-by-step animation

教學小例:一方半徑排序與另一方後綴最大值

回報動畫錯誤
步驟 1 / 3

系統(0,0),(10,0),導彈(1,0),(9,0)

距離對(1,81),(81,1)

距離對(1,81),(81,1)
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
int main() {
    int t;
    cin >> t;
    while (t--) {
        cpp_int x1, y1, x2, y2;
        int m;
        cin >> x1 >> y1 >> x2 >> y2 >> m;
        vector<pair<cpp_int, cpp_int>> a;
        for (int i = 0; i < m; i++) {
            cpp_int x, y;
            cin >> x >> y;
            cpp_int u = x - x1, v = y - y1, r = x - x2, s = y - y2;
            a.push_back({u * u + v * v, r * r + s * s});
        }
        sort(a.begin(), a.end());
        vector<cpp_int> s(m + 1);
        for (int i = m - 1; i >= 0; i--)
            s[i] = max(s[i + 1], a[i].second);
        cpp_int ans = s[0];
        for (int i = 1; i <= m; i++) {
            cpp_int c = a[i - 1].first + s[i];
            if (c < ans)
                ans = c;
        }
        cout << ans << '\n';
    }
}

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

更多