蒟蒻求助,全WA了
查看原帖
蒟蒻求助,全WA了
911978
2328wangyibo楼主2023/7/17 17:15

以下是错误C++代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iomanip>

double calculate_max_water_level(int n, int k, int p, std::vector<int>& heights) {
    int max_height = *std::max_element(heights.begin(), heights.end());
    int min_height = *std::min_element(heights.begin(), heights.end());
    
    double left = 0;
    double right = max_height - min_height;
    
    while (left <= right) {
        double mid = (left + right) / 2;
        double sum_diff = 0;
        int count = 0;
        
        for (int height : heights) {
            if (height < min_height + mid) {
                sum_diff += min_height + mid - height;
                count++;
            } else if (height > min_height + mid + p) {
                sum_diff += height - (min_height + mid + p);
                count++;
            }
        }
        
        if (count <= k) {
            left = mid + 0.00000001;
        } else {
            right = mid - 0.00000001;
        }
    }
    
    return min_height + right;
}

int main() {
    int n, k, p;
    std::cin >> n >> k >> p;
    
    std::vector<int> heights(n);
    for (int i = 0; i < n; i++) {
        std::cin >> heights[i];
    }
    
    double result = calculate_max_water_level(n, k, p, heights);
    std::cout << std::fixed << std::setprecision(10) << result << std::endl;
    
    return 0;
}

个人WA的思路如下:根据最小和最大高度计算出左边界和右边界,并使用二分查找来逼近最大水位。在每次迭代中,我们计算当前水位下每个高度与水位之间的差值,并将其累加到sum_diff中。同时,我们使用count变量来记录超过水位的高度数量。如果count小于等于k,说明当前水位下可以满足要求,此时我们将左边界移动到中间值加上一个微小的偏移量;否则,我们将右边界移动到中间值减去一个微小的偏移量。

最后,将结果设置为最小高度加上右边界,并使用std::fixed和std::setprecision来设置输出精度为10位小数。

请大佬帮忙调一下,感谢 (格式不好,请谅解QwQ)

2023/7/17 17:15
加载中...