P4952 [USACO04MAR] Financial Aid 题解
模拟赛考到的题,放到第二题的位置我不是很理解。
解法
一眼二分。因为我们要使中位数最大,所以满足单调性,大答案比小答案更优,可以二分答案。注意到中位数的特点,我们只需要保证在 n n n 个数中,有 ⌊ n 2 ⌋ \lfloor \dfrac{n}{2} \rfloor ⌊2n⌋ 个数比中位数小, ⌊ n 2 ⌋ \lfloor \dfrac{n}{2} \rfloor ⌊2n⌋ 个数比中位数大就可以了。所以我们按照每头奶牛的分数从小到大排序,二分这个中位数是什么,假设这个中位数对应的奶牛是 x x x,我们把 1 , 2 ⋯ x − 1 1,2 \cdots x-1 1,2⋯x−1 这些位置的奶牛拿出来,把 x + 1 , x + 2 ⋯ c x+1,x+2 \cdots c x+1,x+2⋯c 这些位置的奶牛拿出来,在两部分里分别选取 ⌊ n 2 ⌋ \lfloor \dfrac{n}{2} \rfloor ⌊2n⌋ 个所需奖学金最少的奶牛,加起来看这 n n n 头奶牛所需奖学金是否不超过 f f f。
为什么要取所需奖学金最少的奶牛?我们只需考虑中位数为 x x x 的情况是否存在,如果设取所需奖学金最少的奶牛时奖学金总数为 w w w,如果 w ≤ f w \le f w≤f,则中位数为 x x x 的情况存在,反之,中位数为 x x x 的情况不存在。
如果不这样做,我们任意选了 n n n 头奶牛奖学金总数为 q q q,这里有 w ≤ q w \le q w≤q,如果 q ≤ f q \le f q≤f,则中位数为 x x x 的情况存在,反之,则并不说明中位数为 x x x 的情况不存在。因为如果 q > f q > f q>f,不能说明 w > f w > f w>f。
所以我们要取所需奖学金最少的奶牛。
无解条件特判一下就可以了。
代码
int n,c,f,l,r,mid,ans;
struct cow
{
int score,money;
inline bool operator<(const cow &rhs) const
{
return money<rhs.money;
}
};
cow a[100010],tmp[100010];
inline bool cmp(const cow &lhs,const cow &rhs)
{
return lhs.score<rhs.score;
}
inline bool judge(int x)
{
int sum=a[x].money;
for(int i=1;i<=x;i++) tmp[i]=a[i];
sort(tmp+1,tmp+x);
for(int i=1;i<=n/2;i++) sum+=tmp[i].money;
for(int i=x+1;i<=c;i++) tmp[i-x]=a[i];
sort(tmp+1,tmp+c-x+1);
for(int i=1;i<=n/2;i++) sum+=tmp[i].money;
if(sum>f) return false;
return true;
}
int main()
{
read(n),read(c),read(f),l=n/2+1,r=c-n/2;
for(int i=1;i<=c;i++) read(a[i].score),read(a[i].money);
sort(a+1,a+c+1);
for(int i=1,sum=0;i<=n;i++)
{
sum+=a[i].money;
if(sum>f)
{
cout<<-1;
return 0;
}
}
sort(a+1,a+c+1,cmp);
while(l<=r)
{
mid=(l+r)/2;
if(judge(mid)) ans=mid,l=mid+1;
else r=mid-1;
}
cout<<a[ans].score;
return 0;
}