a522困難連續區間枚舉與有理誤差比較
CPE:Pool Filling (UVa 13242)
精確比較加權溫度誤差,保留最早的最佳區間。
解題思路
固定起點l後向右延伸,累加水量V與偏差熱量E=Σvolume·(temperature−target)。混合溫度與目標的距離正好是|E|/V;只評估ceil(capacity/2)≤V≤capacity的區間,並要求誤差≤5。水量非負,因此加入前若jar.volume>capacity−V,就停止此起點的延伸,不先做可能溢位的加法。
最多3000罐,O(N²)枚舉可行。按l遞增、r遞增掃描,只在誤差嚴格改善時更新,所以同誤差自然保留較小起點再較小終點。Python用任意精度整數交叉乘;C++的偏差熱量用GNU擴充的有號__int128,先提升溫度再相減,分數比較用unsigned __int128的商餘數與倒數交替比較,不做交叉乘。沒有有效方案輸出Not possible;零水量區間不能定義溫度,略過。
C++版本的輸入契約為容量1到2^63−1、每罐水量0到2^63−1,目標與各罐溫度介於−2^63到2^63−1。加入前的容量檢查確保累積水量≤capacity;溫差絕對值≤2^64−1,因此每個前綴的|E|≤capacity×最大溫差<2^127,連取負值求絕對值也安全,並不需要假設熱量能放進64位元。__int128是固定128位元的GNU編譯器擴充,不是任意精度;Python整數沒有此固定位寬限制。
Step-by-step animation
示意:容量10、目標20,水罐(3,10)、(3,30)、(4,20)
步驟 1 / 3
只取罐0
V=3、E=−30,水量不足半滿。
0:(3,10)
1:(3,30)
2:(4,20)
- V
- 3
- E
- −30
#include <iostream>
#include <vector>
#include <utility>
#include <cstdlib>
using namespace std;
using Wide = __int128;
using UWide = unsigned __int128;
bool lessFraction(UWide a, UWide b, UWide c, UWide d) {
bool reversed = false;
while (true) {
if (a / b != c / d)
return reversed ? a / b > c / d : a / b < c / d;
auto r = a % b, s = c % d;
if (!r || !s) {
if (!r && !s)
return false;
return reversed ? r != 0 : r == 0;
}
a = b;
b = r;
c = d;
d = s;
reversed = !reversed;
}
}
int main() {
int T;
cin >> T;
while (T--) {
long long capacity, target;
int n;
cin >> capacity >> target >> n;
vector<pair<long long, long long>> jars(n);
for (auto &jar : jars)
cin >> jar.first >> jar.second;
int left = -1, right = -1;
UWide bestError = 0, bestVolume = 1;
for (int l = 0; l < n; ++l) {
long long volume = 0;
Wide error = 0;
for (int r = l; r < n; ++r) {
// Nonnegative volumes; never add beyond the signed-64-bit capacity.
if (jars[r].first > capacity - volume)
break;
volume += jars[r].first;
Wide delta = static_cast<Wide>(jars[r].second) - static_cast<Wide>(target);
error += static_cast<Wide>(jars[r].first) * delta;
if (volume <= 0 || volume < capacity / 2 + capacity % 2)
continue;
UWide e = error < 0 ? static_cast<UWide>(-error) : static_cast<UWide>(error);
UWide v = static_cast<UWide>(volume);
if (e / v > 5 || (e / v == 5 && e % v))
continue;
if (left < 0 || lessFraction(e, v, bestError, bestVolume)) {
left = l;
right = r;
bestError = e;
bestVolume = v;
}
}
}
if (left < 0)
cout << "Not possible\n";
else
cout << left << ' ' << right << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。