二分答案,如果中位数m已经确定,那么可以如下判断
把人分3份,工资一定小于m的mi个,一定>m的ma个,可以是m的cnt个
所有人尽量选小的,看会不会超s
还要注意人数够不够
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#define int long long
using namespace std;
typedef long long LL;
struct E {
LL x,y;
void init() {
scanf("%I64d%I64d",&x,&y);
}
}a[210010],st[210010];
int n;
LL s;
bool cmp(const E &a,const E &b) {
return a.x<b.x;
}
bool pd(LL m) {
int mi = 0,ma = 0,cnt = 0;
LL sum = 0;
for (int i = 1; i <= n; i++) {
if (a[i].y < m) {mi++;sum+=a[i].x;}
else if (a[i].x > m) {ma++,sum+=a[i].x;}
else st[++cnt] = a[i];
}
sort(st+1,st+cnt+1,cmp);
if (cnt+mi <= n/2) return 1;
if (cnt+ma <= n/2) return 0;
for (int i = 1; i <= n/2-mi; i++) {
sum += st[i].x;
}
return sum <= s-m*(n/2-ma+1);
}
/*
1
3 26
10 12
1 4
10 11
*/
signed main() {
int T;
scanf("%I64d",&T);
while(T--) {
scanf("%I64d%I64d",&n,&s);
int tmpa = 0,tmpi;
for (int i = 1; i <= n; i++) {
a[i].init();
tmpa = max(tmpa,a[i].y);
if (i==1) tmpi = a[i].x;
else tmpi = min(tmpi,a[i].x);
}
for (LL l = tmpi,r = tmpa; ; ) {
if (r-l <= 1) {
printf("%I64d\n",pd(r)?r:l);
break;
}
LL m = (l+r)>>1;
pd(m) ? l=m : r=m;
}
}
return 0;
}
You are the head of a large enterprise. people work at you, and is odd (i. e. is not divisible by
).
You have to distribute salaries to your employees. Initially, you have
dollars for it, and the -th employee should get a salary from todollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
is
- the median of the sequence
- ,
- the median of the sequence
- is
- .
It is guaranteed that you have enough money to pay the minimum salary, i.e
.
Note that you don't have to spend all your
dollars on salaries.
You have to answer
test cases.
Input
The first line contains one integer
() — the number of test cases.
The first line of each query contains two integers
and ( , ) — the number of employees and the amount of money you have. The value is not divisible by.
The following
lines of each query contain the information about employees. The -th line contains two integers and ().
It is guaranteed that the sum of all
over all queries does not exceed.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e.
.
Output
For each test case print one integer — the maximum median salary that you can obtain.