题目链接如下:
我的代码如下:
#include <cstdio>
#include <vector>
#include <utility>
// #define debug
int n, s;
double r, maxWidth;
std::vector<int> w;
void dfs(std::vector<int> vec, double loc, std::vector<std::pair<double, double>> &range){
if (vec.size() == 1){
range.push_back({loc, loc});
return;
}
int sz = vec.size();
for (int i = 1; i < ((1 << sz) - 1); ++i){
std::vector<int> v1, v2;
for (int j = 0; j < sz; ++j){
if (i & 1 << j){
v1.push_back(vec[j]);
} else {
v2.push_back(vec[j]);
}
}
int l = 0;
int r = 0;
for (int j = 0; j < v1.size(); ++j){
l += v1[j];
}
for (int j = 0; j < v2.size(); ++j){
r += v2[j];
}
double temp = loc - 1.0 * r / (l + r);
std::vector<std::pair<double, double>> tempRangeL, tempRangeR;
dfs(v1, temp, tempRangeL);
dfs(v2, temp + 1, tempRangeR);
for (int j = 0; j < tempRangeL.size(); ++j){
for (int k = 0; k < tempRangeR.size(); ++k){
double tl = std::min(tempRangeL[j].first, tempRangeR[k].first);
double tr = std::max(tempRangeL[j].second, tempRangeR[k].second);
range.push_back({tl, tr});
}
}
}
}
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
scanf("%d", &n);
while (n--){
scanf("%lf %d", &r, &s);
w.resize(s);
for (int i = 0; i < s; ++i){
scanf("%d", &w[i]);
}
maxWidth = -1.0;
std::vector<std::pair<double, double>> vec;
dfs(w, 0, vec);
for (int i = 0; i < vec.size(); ++i){
double width = vec[i].second - vec[i].first;
if (width < r && width > maxWidth){
maxWidth = width;
}
}
if (maxWidth < 0){
printf("-1\n");
} else {
printf("%.16lf\n", maxWidth);
}
}
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}