給定 n (≤107) 個元素 xi 及權重 wi。加權中位數 xk 滿足:
∑xi
多測試案例,輸出中位數對應的 x 值。S 可能超 32 位。
pref,對於位置 i,左側權重 = pref - w[i],右側權重 = S - pref左側 < S/2 且 右側 ≤ S/2 的元素#include#include using namespace std; const int MAXN = 10000000 + 5; struct Node { int x, w; } a[MAXN]; bool cmp(Node a, Node b) { return a.x < b.x; } int main() { int n; while (~scanf("%d", &n)) { long long S = 0; for (int i = 0; i < n; ++i) scanf("%d", &a[i].x); for (int i = 0; i < n; ++i) { scanf("%d", &a[i].w); S += a[i].w; } sort(a, a + n, cmp); long double half = S * 0.5L; long long pref = 0; int ans = 0; for (int i = 0; i < n; ++i) { long long left = pref; long long right = S - pref - a[i].w; if (left < half && right <= half) { ans = a[i].x; break; } pref += a[i].w; } printf("%d\n", ans); } return 0; }
left 為嚴格小於 xk 的權重和,right 為嚴格大於的權重和long double 存 half 避免精度問題輸入: 7 10 35 5 10 15 5 20 10 35 5 10 15 5 20 輸出: 20
此題考察加權中位數定義理解與線性掃描實現,排序後單趟遍歷即可。