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
**【题意】:**给你n个数然后第一行是这些数xi,第二行是他们分别对应的权值wi。s是权值总和。然后让你找一个数xk满足公式,(x1xk)求和>s/2,(xkxn)求和小于等于s/2;可看题目中的公式因为两边求和都不存在xk的权值,则只要找到一半小于s/2则另一半一定小于等于s/2。
**【思路】:**将其存在一个结构体中,然后按x的大小进行排序(代码按降序排序),然后开一个变量ans=0遍历排完序的序列,当ans>=s/2时,记录下标k跳出循环即可,最后输出k所对应的x即可。
【注】:这里的数据量很大 所以结构体数组要开到1e7+10
并且 下面求和的两个变量都需要开long long 或double 不然会RE
【代码】:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
const int N=1e7+10;
struct F
{
int x;
int w;
}a[N];
bool cmp(struct F aa,struct F bb)
{
return aa.x>bb.x;
}
int main()
{
ios::sync_with_stdio(false);
int n;
while(cin>>n)
{
long long s=0;
for(int i=1;i<=n;i++)
{
cin>>a[i].x;
}
for(int i=1;i<=n;i++)
{
cin>>a[i].w;
s+=a[i].w;
}
s/=2;
sort(a+1,a+n+1,cmp);
long long ans=0;
int k=0;
for(int i=1;i<=n;i++)
{
ans+=a[i].w;
if(ans>=s)//寻找xk
{
k=i;
break;
}
}
cout<<a[k].x<<endl;
}
return 0;
}