山东省第五届省赛J题 Weighted Median(思维题 sort给结构体排序)

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?

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

**【题意】:**给你n个数然后第一行是这些数xi,第二行是他们分别对应的权值wi。s是权值总和。然后让你找一个数xk满足公式,(x1xk)求和>s/2,(xkxn)求和小于等于s/2;可看题目中的公式因为两边求和都不存在xk的权值,则只要找到一半小于s/2则另一半一定小于等于s/2。

**【思路】:**将其存在一个结构体中,然后按x的大小进行排序(代码按降序排序),然后开一个变量ans=0遍历排完序的序列,当ans>=s/2时,记录下标k跳出循环即可,最后输出k所对应的x即可。

【注】:这里的数据量很大 所以结构体数组要开到1e7+10
并且 下面求和的两个变量都需要开long long 或double 不然会RE

【代码】:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
const int N=1e7+10;
struct F
{
  int x;
  int w;
}a[N];

bool cmp(struct F aa,struct F bb)
{
   return aa.x>bb.x;
}

int main()
{
    ios::sync_with_stdio(false);
    int n;
    while(cin>>n)
    {
       long long s=0;
       for(int i=1;i<=n;i++)
       {
           cin>>a[i].x;
       }
       for(int i=1;i<=n;i++)
       {
           cin>>a[i].w;
           s+=a[i].w;
       }
       s/=2;
       sort(a+1,a+n+1,cmp);
       long long ans=0;
       int k=0;
       for(int i=1;i<=n;i++)
       {
           ans+=a[i].w;
           if(ans>=s)//寻找xk
           {
               k=i;
               break;
           }
       }
       cout<<a[k].x<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值