Weighted Median
For n elements x1, x2, ..., xn with positive integer weights w1, w2, ..., wn. The weighted median is the element xk satisfying
and
, S indicates



Can you compute the weighted median in O(n) worst-case?
Input
There are several test cases. For each case, the first line contains one integer n(1 ≤ n ≤ 10^7) — the number of elements in the sequence. The following line contains n integer numbers xi (0 ≤ xi ≤ 10^9). The last line contains n integer numbers wi (0 < wi < 10^9).
Output
One line for each case, print a single integer number— the weighted median of the sequence.
Sample Input
7 10 35 5 10 15 5 20 10 35 5 10 15 5 20
Sample Output
20
Hint
The S which indicates the sum of all weights may be exceed a 32-bit integer. If S is 5,
equals 2.5.

这是一道山东省省赛的题,英语不好的我看了以后一脸懵逼,最后花了好长时间才看懂,原来很是简单
题目意思:
给一些数x和它们对应的权值w,按照如图所示公式,s是所有权值w的总和。
求一个xk,使得满足前两个公式。
解题思路:
用结构体保存元素值和权值,先升序排列,累计xk之前的权值和,直到该权值大于s。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include<stdio.h> #include<algorithm> using namespace std; struct message{ int x; int w; }a[10000010]; int my_cmp(message a,message b) { if (a.x<b.x) return 1; else return 0; } int main() { int n,i; double s,y; while ( scanf ( "%d" ,&n)!=EOF) { s=0; for (i=0;i<n;i++) scanf ( "%d" ,&a[i].x); for (i=0;i<n;i++) { scanf ( "%d" ,&a[i].w); s=s+a[i].w; } s=s/2.0; y=0; sort(a,a+n,my_cmp); for (i=0;i<n;i++) { y=y+a[i].w; if (y>s) { printf ( "%d\n" ,a[i].x); break ; } } } return 0; } |
本文作者:王陸
本文链接:https://www.cnblogs.com/wkfvawl/p/8665970.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步