2014山东省第五届ACM省赛 Weighted Median

来源:互联网 发布:不怎么花钱的网络手游 编辑:程序博客网 时间:2024/05/15 01:51

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.

来源

2014年山东省第五届ACM大学生程序设计竞赛


#include <iostream>#include <cstdio>#include <algorithm>using namespace std;struct ss{    long long int x;    long long int w;};int cmp(ss a,ss b){    return a.x<b.x;}const int maxn = 10000000+1;ss a[maxn];int main(){    int  n;    while(cin>>n)    {        long long sum=0,w;        for(int i=0; i<n; i++)        {            a[i].x=0;            a[i].w=0;        }        for(int i=0; i<n; i++)        {            cin>>a[i].x;        }        for(int i=0; i<n; i++)        {            cin>>w;            a[i].w=w*2;            sum+=w*2;        }        sum/=2;        sort(a,a+n,cmp);        long long int s=0;        long long int q=a[0].x;        for(int i=0; i<n; i++)        {            s+=a[i].w;            if(s>=sum)            {                q=a[i].x;                break;            }        }        cout<<q<<endl;    }    return 0;}

0 0
原创粉丝点击