[51Nod 1110 距离之和最小 V3]三分
分类:三分
1. 题目链接
2. 题意描述
X轴上有N个点,每个点除了包括一个位置数据X[i],还包括一个权值W[i]。点P到点P[i]的带权距离 = 实际距离 * P[i]的权值。求X轴上一点使它到这N个点的带权距离之和最小,输出这个最小的带权距离之和。
Input
第1行:点的数量N。(2 <= N <= 10000)
第2 - N + 1行:每行2个数,中间用空格分隔,分别是点的位置及权值。(-10^5 <= X[i] <= 10^5,1 <= W[i] <= 10^5)
Output
输出最小的带权距离之和。
3. 解题思路
对所有的点按照坐标位置排序。可以发现,带权距离之和关于坐标是先递减后递增的。那么三分一下,就可以求出极值(最值)了。
4. 实现代码
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <ctime>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <string>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef unsigned int uint;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<LB, LB> PLB;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const LL INFL = 0x3f3f3f3f3f3f3f3fLL;
const long double PI = acos(-1.0);
const long double eps = 1e-4;
void debug() { cout << endl; }
template<typename T, typename ...R> void debug (T f, R ...r) { cout << "[" << f << "]"; debug (r...); }
template<typename T> inline void umax(T &a, T b) { a = max(a, b); }
template<typename T> inline void umin(T &a, T b) { a = min(a, b); }
template <typename T> inline bool scan_d (T &ret) {
char c; int sgn;
if (c = getchar(), c == EOF) return 0; //EOF
while (c != '-' && (c < '0' || c > '9') ) if((c = getchar()) == EOF) return 0;
sgn = (c == '-') ? -1 : 1;
ret = (c == '-') ? 0 : (c - '0');
while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0');
ret *= sgn;
return 1;
}
template<typename T> void print(T x) {
static char s[33], *s1; s1 = s;
if (!x) *s1++ = '0';
if (x < 0) putchar('-'), x = -x;
while(x) *s1++ = (x % 10 + '0'), x /= 10;
while(s1-- != s) putchar(*s1);
}
template<typename T> void println(T x) { print(x); putchar('\n'); }
template<typename T> T randIntv(T a, T b) { return rand() % (b - a + 1) + a; } /*[a, b]*/
const int MAXN = 10005;
LL n;
struct Node {
LL x, w;
bool operator < (const Node& e) const {
return x < e.x;
}
} nd[MAXN];
LL calc(LL x) {
LL sum = 0;
for(int i = 1; i <= n; ++i) {
sum += (LL)abs(x - nd[i].x) * nd[i].w;
}
return sum;
}
int main() {
#ifdef ___LOCAL_WONZY___
freopen ("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
while(scan_d(n)) {
for(int i = 1; i <= n; ++i) scan_d(nd[i].x), scan_d(nd[i].w);
sort(nd + 1, nd + n + 1);
LL ans = 0; LL lb = nd[1].x, ub = nd[n].x, lmid, rmid, lval, rval;
while(lb <= ub) {
lmid = (lb + ub) >> 1; rmid = (lmid + ub) >> 1;
lval = calc(lmid), rval = calc(rmid);
if(lval == rval) lb = lmid + 1, ub = rmid - 1, ans = lval;
else if(lval < rval) ub = rmid, ans = lval;
else lb = lmid, ans = rval;
}
println(ans);
}
#ifdef ___LOCAL_WONZY___
cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif // ___LOCAL_WONZY___
return 0;
}