自己本身接触这种题的次数并不是很多,一开始也很懵,于是去查了一下加权一类的定义。
权重表示在评价过程中,是被评价对象的不同侧面的重要程度的定量分配,对各评价因子在总体评价中的作用进行区别对待.事实上,没有重点的评价就不算是客观的评价.
举例
打个比方说,一件事情,你给它打100分,你的老板给它打60分,如果平均,则是(100+60)/2=80分.但因为老板说的话分量比你重,假如老板的权重是2,你是1,这时求平均值就是加权平均了,结果是(100*1 + 60*2)/(1+2)=73.3分,显然向你的老板那里倾斜了.假如老板权重是1,你的权重是3,结果是(100*3+60*1)/(1+3)=90.这就是根据权重的不同进行的平均数的计算,所以又叫加权平均数.
emmmm,我觉得根据以上网友的的一段解释应该能够比较轻松的理解一下本题的加权中位数:
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
首先要求一下权重的总和sum,求他的一半s,将结构体按照z.x排序,依次把权相加,如果大于s,就输出当下的z.x。
只要理解了题意,还是比较简单的。
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Z
{
int x;
int w;
} z[1000007];
bool cmp(Z a,Z b)
{
if(a.x<b.x)
return true;
return false;
}
int main()
{
long long int n,sum=0,i,j,k,ans;
double s,s1,s2;
while(scanf("%lld",&n)!=EOF)
{
sum=0;s=0;s1=0;s2=0;
for(i=1; i<=n; i++)
scanf("%d",&z[i].x);
for(i=1; i<=n; i++)
{
scanf("%d",&z[i].w);
sum+=z[i].w;
}
s=sum*0.5;
sort(z+1,z+1+n,cmp);
for(i=1; i<=n-1; i++)
{
s1+=z[i].w;
s2=sum-s1-z[i+1].w;
if(s1<s&&s2<=s)
{
ans=z[i+1].x;
break;
}
}
printf("%d\n",ans);
}
return 0;
}