码迷,mamicode.com
首页 > 其他好文 > 详细

[ACM] SDUT 2886 Weighted Median (省赛最悲剧的一道题)

时间:2014-11-04 22:51:14      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:acm

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
bubuko.com,布布扣 and bubuko.com,布布扣 , S indicates bubuko.com,布布扣
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.
 

示例输入

7
10 35 5 10 15 5 20
10 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, bubuko.com,布布扣 equals 2.5.

来源

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


解题思路:

当时最后半个多小时三个人死活没想出来怎么做,现在拿出这道题一看十几分钟就解决了。。。现场的时候心态实在是太重要了,一慌脑子就容易空白。。。

代码:

#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 (省赛最悲剧的一道题)

标签:acm

原文地址:http://blog.csdn.net/sr_19930829/article/details/40793715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!