Party All the Time
- 题意:有一堆物品,每个有一个位置 x [ i ] ,同时具有 w [ i ] 的重量,将该物品移动 S 距离需要花费 S ^ 3 * w [ i ] 。确定一个点 X 求出最小花费。
- 三分模板:
double getsum (double s)
{
// 计算结果的函数
return ans;
}
double trisection_search (double left, double right)
{
while (right - left > eps) {
double mleft = (left +right) / 2.0;
double mright = (mleft + right) / 2.0;
if (getsum(mleft) < getsum (mright)) right = mright;
else left = mleft;
}
return getsum (left);
}
- 本题代码:
// zyc 2018/7/23
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-6;
const int maxn = 5e4 + 7;
const int M = 1e9 + 7;
int n; double x[maxn], w[maxn];
double getit (double s)
{
double ans = 0.0;
for (int i = 0; i < n; i ++) {
ans += abs(x[i] - s) * (x[i] - s) * (x[i] - s) * w[i];
}
return ans;
}
double trisection_search (double left, double right)
{
while (right - left > eps) {
double mleft = (left +right) / 2.0;
double mright = (mleft + right) / 2.0;
if (getit (mleft) < getit (mright)) right = mright;
else left = mleft;
}
return getit (left);
}
int main ()
{
int t, ccase = 1; scanf ("%d", &t);
while (t --) {
scanf ("%d", &n);
double l = 1000000.0, r = -1000000.0;
for (int i = 0; i < n; i ++) {
scanf ("%lf %lf", &x[i], &w[i]);
l = min (x[i], l);
r = max (x[i], l);
}
printf ("Case #%d: %.0lf\n", ccase++, trisection_search (l, r));
}
return 0;
}