a575中等排序地形後逐層注水

CPE:Flooded! (UVa 815)

用已納入低地面積求水位,嚴格判定淹沒比例。

前往題目練習 →回報教學錯誤時間 O(mn log(mn)),空間 O(mn)。

解題思路

每格面積100平方公尺,水量V先除以100,換成所有格子的高度增量總和。將高度由小到大排序,假設最低k格已連通,且其高度總和為S,若水只分在這k格,水位就是 (V/100+S)/k。

逐一加入低地,檢查目前水量是否足以升到下一個高度:所需體積為100×(k×下一高度−S)。若不夠或恰好到達,水位是(V+100S)/(100k);超過才繼續納入下一格。最後以100k×高度<V+100S精確判斷淹沒,恰等於水面不算,V=0時淹沒率0。輸出將有理數直接四捨五入到百分位,避免−7.835的浮點誤差;每組末尾空一行。

Step-by-step animation

示意:三格高度0、10、20,水量1000

回報動畫錯誤
步驟 1 / 3

最低一格

升到第二格高度10需要(10−0)×100=1000。

0
10
20
水量
1000
所需
1000

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

string cents(long long numerator, long long denominator) {
    bool negative = numerator < 0;
    long long value = abs(numerator), whole = value / denominator;
    if (2 * (value % denominator) >= denominator)
        ++whole;
    ostringstream out;
    if (negative && whole)
        out << '-';
    out << whole / 100 << '.' << setw(2) << setfill('0') << whole % 100;
    return out.str();
}
int main() {
    int m, n, tc = 0;
    while (cin >> m >> n && (m || n)) {
        int total = m * n;
        vector<long long> h(total);
        for (auto &x : h)
            cin >> x;
        long long volume;
        cin >> volume;
        sort(h.begin(), h.end());
        long long sum = 0, numerator = 0;
        int wetArea = 1;
        for (int k = 1; k <= total; ++k) {
            sum += h[k - 1];
            if (k == total || 100LL * (k * h[k] - sum) >= volume) {
                // Exact level is numerator/(100*wetArea).
                numerator = volume + 100 * sum;
                wetArea = k;
                break;
            }
        }
        int under = 0;
        for (long long x : h)
            if (100 * x * wetArea < numerator)
                ++under;
        cout << "Region " << ++tc << "\nWater level is " << cents(numerator, wetArea)
             << " meters.\n";
        cout << cents(10000LL * under, total) << " percent of the region is under water.\n\n";
    }
}

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

更多