zoukankan      html  css  js  c++  java
  • Weighted Median

    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

    Hint

    The S which indicates the sum of all weights may be exceed a 32-bit integer. If S is 5,  equals 2.5.
     
    这是一道山东省省赛的题,英语不好的我看了以后一脸懵逼,最后花了好长时间才看懂,原来很是简单

    题目意思:
    给一些数x和它们对应的权值w,按照如图所示公式,s是所有权值w的总和。
    求一个xk,使得满足前两个公式。

    解题思路:
    用结构体保存元素值和权值,先升序排列,累计xk之前的权值和,直到该权值大于s。

    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    struct message{
    int x;
    int w;
    }a[10000010];
    int my_cmp(message a,message b)
    {
        if(a.x<b.x)
            return 1;
        else
            return 0;
    }
    int main()
    {
        int n,i;
        double s,y;
        while(scanf("%d",&n)!=EOF)
        {
            s=0;
            for(i=0;i<n;i++)
            scanf("%d",&a[i].x);
            for(i=0;i<n;i++)
            {
                scanf("%d",&a[i].w);
                s=s+a[i].w;
            }
            s=s/2.0;
            y=0;
            sort(a,a+n,my_cmp);
            for(i=0;i<n;i++)
            {
                y=y+a[i].w;
                if(y>s)
                {
                    printf("%d
    ",a[i].x);
                    break;
                }
            }
        }
        return 0;
    }
    

      

  • 相关阅读:
    谈谈jQuery之绑定事件
    手机移动端WEB资源整合
    2016移动端web5分钟速成(适合新手)
    日常整理的一些网址
    web服务器页面错误代码集
    jQuery事件绑定的最佳实践
    前端体系
    js刷新页面的几种方法
    JAVA的静态变量、静态方法、静态类
    在Hadoop集群中添加机器和删除机器
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/8665970.html
Copyright © 2011-2022 走看看