, . , .
, , 4, 2, 3, 1, 2, 5:
x
x x
x x x
xxx xx
xxxxxx
. 1 , 2 ..:
44444x
x3333x
x2x22x
xxx1xx
xxxxxx
, , . O(nm), n - , m - . .
. - 1, 2, 2, 3, 4, 5:
x
xx
xxx
xxxxx
xxxxxx
, :
44444x
3333xx
222xxx
1xxxxx
xxxxxx
. - .
O(n), . O(n log n). O(n log n + n) , O(nm), m .
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int requiredVolume, n;
cin >> requiredVolume >> n;
vector<int> heights;
for (int i = 0; i < n; ++i) {
int height;
cin >> height;
heights.push_back(height);
}
sort(heights.begin(), heights.end());
int volume = requiredVolume,
waterHeight = heights[0],
layerLength = 0,
pos = 0;
while (volume > 0) {
int seek = pos;
while (seek < n && heights[seek] == heights[pos]) {
++seek;
}
layerLength += seek - pos;
int needLayers = (volume + layerLength - 1) / layerLength;
int addLayers;
if (seek == n) {
addLayers = needLayers;
} else {
addLayers = min(heights[seek] - heights[pos], needLayers);
}
volume -= addLayers * layerLength;
waterHeight += addLayers;
cout << "with water at height " << waterHeight <<
", the volume is " << (requiredVolume - volume) << '\n';
pos = seek;
}
cout << "final answer:\n minimum height = " << waterHeight <<
", volume reached = " << (requiredVolume - volume) << '\n';
return 0;
}
, :
60 3
30 40 20
:
with water at height 30, the volume is 10
with water at height 40, the volume is 30
with water at height 50, the volume is 60
final answer:
minimum height = 50, volume reached = 60
11 :
11 5
4 2 3 1 2 5
:
with water at height 2, the volume is 1
with water at height 3, the volume is 4
with water at height 4, the volume is 8
with water at height 5, the volume is 13
final answer:
minimum height = 5, volume reached = 13