sdut 2886 Weighted Median 结构体

来源:互联网 发布:日本校园霸凌 知乎 编辑:程序博客网 时间:2024/06/02 03:00

Weighted Median

Time Limit: 2000MS Memory limit: 65536K

题目描述

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?
 

输入

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).
 

输出

One line for each case, print a single integer number— the weighted median of the sequence.
 

示例输入

710 35 5 10 15 5 2010 35 5 10 15 5 20

示例输出

20

提示

The S which indicates the sum of all weights may be exceed a 32-bit integer. If S is 5, equals 2.5.
#include <iostream>#include<cstdio>#include<string.h>#include<algorithm>using namespace std;typedef long long LL;const int Max=1e7+2;int ans,n;struct Node{    int x,w;}node[Max];int cmp(Node a,Node b){    return a.x<b.x;}int main(){    while(~scanf("%d",&n))    {        long long sum=0;        for(int i=0; i<n; i++)            scanf("%d",&node[i].x);        for(int i=0; i<n; i++)        {            scanf("%d",&node[i].w);            sum+=node[i].w;        }        long long s=sum/2.0;        long long minn=0,maxx=0;        sort(node,node+n,cmp);        for(int i=0;i<n;i++)        {            minn+=node[i-1].w;            maxx=sum-minn-node[i].w;            if(minn<s&&maxx<=s)            {                ans=node[i].x;                break;            }        }        cout<<ans<<endl;    }    return 0;}


0 0