Weighted Median Time Limit: 2000 ms memory limit: 65536 k any questions? Click Here ^_^ Question 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? Enter 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. Example Input
710 35 5 10 15 5 2010 35 5 10 15 5 20
Sample output
20
Tip the s which indicates the sum of all weights may be exceed a 32-bit integer. If S is 5, equals 2. 5. Source: The fifth ACM College Student Program Design Competition in Shandong province in 2014
Solution:
At that time, three people did not think about how to do it in the last half an hour. Now they have solved the problem after reading this question for more than ten minutes... The mentality at the scene is really too important, and it is easy to be blank when you are in a panic...
Code:
#include <iostream>#include <algorithm>#include <stdio.h>using namespace std;const int maxn=1e7+2;int n;struct Node{ int x,w;}node[maxn];bool cmp(Node a,Node b){ if(a.x<b.x) return true; return false;}int main(){ while(scanf("%d",&n)!=EOF) { long long sum=0; for(int i=1;i<=n;i++) scanf("%d",&node[i].x); for(int i=1;i<=n;i++) { scanf("%d",&node[i].w); sum+=node[i].w; } long double S=sum*0.5; sort(node+1,node+1+n,cmp); long long xiao=0,da=0; int ans; for(int i=1;i<=n-1;i++) { xiao+=node[i].w; da=sum-xiao-node[i+1].w; if(xiao<S&&da<=S) { ans=node[i+1].x; break; } } cout<<ans<<endl; } return 0;}
[ACM] sdut 2886 Weighted Median)