Description
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
题意:
给一个数你,第一行是数xi(0<i<n),第二行是xi分别对应的权值wi。sum是权值总和。然后让你找一个数xk满足公式,(x1~xk)求和>sum/2,(xk~xn)求和小于等于sum/2;可看题目中的公式因为两边求和都不存在xk的权值,则只要找到一半小于sum/2则另一半一定小于等于sum/2。
题解:
将xi和对应的wi存在一个结构体中,然后按x的大小进行排序(代码按降序排序),然后开一个变量s=0遍历排完序的序列,当s>=sum/2时,输出xi-1,跳出循环即可。(因为数据量很大,而且数据值很大,所以sum和s要定义为long long)
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N=1e7+10;
struct P
{
int x;
int w;
} m[N];
bool cmp(P a,P b)
{
return a.x>b.x;
}
int main()
{
int n;
while (~scanf("%d",&n))
{
for (int i=0; i<n; i++)
scanf("%d",&m[i].x);
long long sum=0;
for (int i=0; i<n; i++)
{
scanf("%d",&m[i].w);
sum+=m[i].w;
}
sum/=2;
sort(m,m+n,cmp);
long long s=0;
for (int i=0; i<n; i++)
{
if (s<sum)
s+=m[i].w;
else
{
printf("%d\n",m[i-1].x);
break;
}
}
}
return 0;
}