Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void __read(T& a) {
cin >> a;
}
template <typename T, typename... Args>
void __read(T& a, Args&... args) {
cin >> a;
__read(args...);
}
constexpr long long M7 = 1000000007ll;
constexpr long long M9 = 1000000009ll;
constexpr long long MFFT = 998244353ll;
template <class T>
void outv(T& a) {
for (auto& x : a) cout << x << ' ';
}
mt19937 rnd(static_cast<unsigned>(
chrono::steady_clock::now().time_since_epoch().count()));
template <class T>
void random_shuffle(T s, T e) {
shuffle(s, e, rnd);
};
static auto __super_speed__ = (ios_base::sync_with_stdio(0), cin.tie(0));
int32_t main() {
long long t;
__read(t);
while (t--) {
long long n, s;
__read(n, s);
vector<pair<long long, long long> > a(n);
for (signed i = 0; i < (n); i++) cin >> a[i].first >> a[i].second;
sort((a).begin(), (a).end());
long long l = 0, r = 1000000000;
while (l < r) {
long long mid = (l + r + 1) / 2;
long long cnt = 0;
vector<pair<long long, long long> > b;
for (long long i = 0; i < n; ++i) {
if (a[i].second < mid)
cnt += a[i].first;
else
b.push_back(a[i]);
}
long long d = b.size() - (n + 1) / 2;
if (d < 0) {
r = mid - 1;
continue;
}
for (long long i = 0; i < d; ++i) cnt += b[i].first;
for (long long i = d; i < b.size(); ++i) cnt += max(mid, b[i].first);
if (cnt <= s)
l = mid;
else
r = mid - 1;
}
cout << l << '\n';
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int dr8[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dc8[] = {1, -1, 0, 0, -1, 1, -1, 1};
int dr4[] = {0, 1, -1, 0};
int dc4[] = {1, 0, 0, -1};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--) {
long long int n, s;
cin >> n >> s;
long long int r[n][2];
vector<pair<pair<long long int, long long int>, long long int> > v;
for (int i = 0; i < n; i++) {
cin >> r[i][0] >> r[i][1];
v.push_back({{r[i][1], r[i][0]}, i});
}
sort(v.begin(), v.end());
long long int an, l = 1, h = 1000000000;
while (l <= h) {
long long int m = (l + h) / 2;
vector<long long int> vv, less;
long long int cn = 0, mx = 0, sm = 0, gr = 0;
for (int i = 0; i < n; i++) {
if (r[i][1] < m) {
less.push_back(r[i][0]);
} else
vv.push_back(r[i][0]);
if (r[i][0] <= m) {
cn++;
mx = max(mx, r[i][0]);
}
if (r[i][1] >= m) gr++;
sm += r[i][0];
}
if (cn < (n + 1) / 2) {
l = m + 1;
continue;
} else if (gr < (n + 1) / 2) {
h = m - 1;
continue;
}
sort(less.begin(), less.end());
sort(vv.begin(), vv.end());
long long int sz = less.size();
sm = 0;
for (int i = 0; i < min(n / 2, sz); i++) sm += less[i];
int i = 0;
for (; i < (n / 2) - less.size(); i++) {
sm += vv[i];
}
sm += m;
i++;
for (; i < vv.size(); i++) sm += max(m, vv[i]);
{
if (sm <= s) {
an = m;
l = m + 1;
} else
h = m - 1;
}
}
cout << an << "\n";
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class Main {
void run() throws IOException {
int t = nextInt();
for (int j = 0; j < t; j++) {
int n = nextInt();
long s = nextLong();
long[][] a = new long[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = nextInt();
a[i][1] = nextInt();
}
long l = 0;
long r = (long) 2e14 + 1;
while (l + 1 < r) {
long m = (l + r) / 2;
int count_more = 0;
int count_mid = 0;
long max = 0;
long sum = 0;
ArrayList<Long> al = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i][1] < m) sum += a[i][0];
else if (m <= a[i][0]) {
count_more++;
sum += a[i][0];
} else {
max = max(max, a[i][0]);
count_mid++;
al.add(a[i][0]);
}
}
int rem = max(0, (n + 1) / 2 - count_more);
if (rem > count_mid) {
r = m;
continue;
}
Collections.sort(al);
for (int i = 0; i < al.size(); i++) {
if (i < al.size() - rem) sum += al.get(i);
else sum += m;
}
if (sum > s) r = m;
else l = m;
}
pw.println(l);
}
pw.close();
}
class Triple {
long time;
int type, num;
public Triple(long a, int b, int c) {
time = a;
type = b;
num = c;
}
}
class PointComp implements Comparator<Triple> {
@Override
public int compare(Triple o1, Triple o2) {
if (o1.time == o2.time && o1.type == o2.type) return Integer.compare(o1.num, o2.num);
if (o1.time == o2.time) return -Integer.compare(o1.type, o2.type);
return Long.compare(o1.time, o2.time);
}
}
long mod = (long) 1e9 + 7;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader br = new BufferedReader(new FileReader("qual.in"));
StringTokenizer st = new StringTokenizer("");
PrintWriter pw = new PrintWriter(System.out);
//PrintWriter pw = new PrintWriter("qual.out");
int nextInt() throws IOException {
return Integer.parseInt(next());
}
String next() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public Main() throws FileNotFoundException {
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 2 * 1e5 + 1;
struct Emp {
int l, r;
} emp[N];
bool search(int m, int n, long long s) {
long long sum = 0, cnt = 0;
for (int i = n - 1; i >= 0; i--) {
if (emp[i].l >= m)
cnt++;
else if (emp[i].l <= m && emp[i].r >= m && cnt <= n / 2) {
sum += m - emp[i].l;
cnt++;
}
}
return sum <= s && cnt > n / 2;
}
void solve() {
int n;
long long s;
cin >> n >> s;
for (int i = 0; i < n; i++) {
int l, r;
cin >> l >> r;
emp[i].l = l;
emp[i].r = r;
s -= l;
}
sort(emp, emp + n, [](const Emp &x, const Emp &y) { return x.l < y.l; });
int l = 0, r = 1e9 + 1;
while (l < r - 1) {
int m = l + (r - l) / 2;
bool f = search(m, n, s);
if (f)
l = m;
else
r = m;
}
cout << l << "\n";
}
int t;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
cin >> t;
while (t--) solve();
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class D1251 {
static int n;
static Seg[] arr;
public static void main(String[] args){
int t;
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- > 0){
n = sc.nextInt();
Long s;
s = sc.nextLong();
arr = new Seg[n];
for(int i = 0; i < n; i++){
arr[i] = new Seg();
arr[i].l = sc.nextInt();
arr[i].r = sc.nextInt();
}
int l = 1;
int r = 1000000000;
int ans = 1;
while(l <= r){
int mid = (l + r)/2;
//System.out.println(l + " " + mid + " " + r);
if(check(mid, s)){
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
System.out.println(ans);
}
}
static class Seg {
int l;
int r;
}
static boolean check(int mid, Long s){
int countMore = 0;
int countLess = 0;
ArrayList<Seg> ls = new ArrayList<>();
ArrayList<Seg> gt = new ArrayList<>();
ArrayList<Seg> md = new ArrayList<>();
for(int i = 0; i < n; i++){
if(arr[i].l > mid){
countMore += 1;
gt.add(arr[i]);
}
else if(arr[i].r < mid){
countLess += 1;
ls.add(arr[i]);
}
else {
md.add(arr[i]);
}
}
if(countMore > n/2) return true;
if(countLess > n/2) return false;
Long cursum = 0L;
for(int i = 0; i < ls.size(); i++){
cursum += ls.get(i).l;
//System.out.println("cursum: " + cursum);
}
for(int i = 0; i < gt.size(); i++){
cursum += gt.get(i).l;
//System.out.println("cursum: " + cursum);
}
Collections.sort(md, new SortByLeft());
int req = n/2 - ls.size();
for(int i = 0; i < req; i++){
cursum += md.get(i).l;
}
for(int i = req; i < md.size(); i++){
cursum += mid;
}
if(cursum <= s) return true;
else return false;
}
static class SortByLeft implements Comparator<Seg> {
public int compare(Seg a, Seg b){
return a.l - b.l;
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int n;
int T, l, r, ans, mid;
pair<int, int> a[maxn];
int todo[maxn], top;
long long s;
bool check(int mid) {
long long ss = s;
int tot = 0, top = 0;
for (int i = 0; i < n; i++) {
if (a[i].second >= mid) {
if (a[i].first >= mid)
tot++;
else
todo[top++] = mid - a[i].first;
}
}
sort(todo, todo + top);
for (int i = 0; i < top && ss >= todo[i]; i++) {
tot++;
ss -= todo[i];
}
return tot * 2 > n;
}
int main() {
cin >> T;
while (T--) {
cin >> n >> s;
for (int i = 0; i < n; i++) {
scanf("%d%d", &l, &r);
a[i] = pair<int, int>(l, r);
s -= l;
}
l = 0, r = 1e9;
ans = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (check(mid))
ans = mid, l = mid + 1;
else
r = mid - 1;
}
cout << ans << endl;
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long n, second;
long long minS = 0;
vector<int> ptats;
vector<pair<int, int>> lr;
bool check(long long median) {
long long excess = 0;
int it = upper_bound(ptats.begin(), ptats.end(), median) - ptats.begin() - 1;
int left = it;
int right = (n - it - 1);
if (left < right) {
return false;
}
int cnt = (left - right) / 2 + 1;
for (int i = it; i >= 0 && cnt; i--) {
if (lr[i].second >= median) {
excess += (median - lr[i].first);
cnt--;
}
}
return excess + minS <= second && cnt == 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) {
ptats.clear();
lr.clear();
minS = 0;
cin >> n >> second;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
lr.push_back({x, y});
minS += x;
}
ptats.resize(n);
sort(lr.begin(), lr.end());
for (int i = 0; i < n; i++) {
ptats[i] = lr[i].first;
}
int l = lr[n / 2].first;
long long r = 1e15;
while (l < r) {
long long mid = l + (r - l + 1) / 2;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
cout << l << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long add(long long a, long long b, long long mod) {
return (a % mod + b % mod) % mod;
}
long long sub(long long a, long long b, long long mod) {
return (a % mod - b % mod + mod) % mod;
}
long long mul(long long a, long long b, long long mod) {
return ((a % mod) * (b % mod)) % mod;
}
long long sumodd(long long num, long long mod) { return mul(num, num, mod); }
long long sumeven(long long num, long long mod) {
return mul(num, num + 1, mod);
}
long long sum_any_range(long long st, long long en, long long num) {
return (num * (st + en) / 2);
}
long long gcd(long long a, long long b) {
while (b != 0) {
long long a2 = a;
a = b;
b = a2 % b;
}
return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
string makeitbinary(long long n) {
string s;
while (n) {
s = s + (char)((n % 2) + '0');
n /= 2;
}
reverse(s.begin(), s.end());
return s;
}
bool bit(int num, int i) { return ((num >> i) & 1); }
long long fastpowermod(long long b, long long p, long long mod) {
long long ans = 1;
while (p) {
if (p % 2) {
ans = mul(ans, b, mod);
}
b = mul(b, b, mod);
p /= 2;
}
return ans;
}
long long fastpower(long long b, long long p) {
long long ans = 1;
while (p) {
if (p % 2) {
ans = ans * b;
}
b = b * b;
p /= 2;
}
return ans;
}
double fastpower_double(double b, long long p) {
double ans = 1;
while (p) {
if (p % 2) {
ans = ans * b;
}
b = b * b;
p /= 2;
}
return ans;
}
long long summation_formula(long long n) { return (n * (n + 1) / 2); }
bool lower_vowel(char c) {
return (c == 'i' || c == 'o' || c == 'u' || c == 'a' || c == 'e');
}
string bigint_mini(string s1, string s2) {
if (s1.size() > s2.size()) {
return s2;
} else if (s2.size() > s1.size()) {
return s1;
}
for (int i = 0; i < s1.size(); i++) {
if ((s1[i] - '0') > (s2[i] - '0')) {
return s2;
} else if ((s2[i] - '0') > (s1[i] - '0')) {
return s1;
}
}
return s1;
}
double polygon_area(int n, vector<double> X, vector<double> Y) {
double area = 0.0;
int j = n - 1;
for (int i = 0; i < n; i++) {
area += (X[j] + X[i]) * (Y[j] - Y[i]);
j = i;
}
return abs(area / 2.0);
}
long long sum_of_digits(string s) {
long long sum = 0;
for (int i = 0; i < s.size(); i++) {
sum += s[i] - '0';
}
return sum;
}
string makeitbase(long long num, long long base) {
string s;
while (num) {
long long mod = num % base;
s += (mod + '0');
num /= base;
}
reverse(s.begin(), s.end());
return s;
}
bool intersect(long long l1, long long r1, long long l2, long long r2) {
return (max(l1, l2) <= min(r1, r2));
}
pair<long long, long long> find_intersection(long long l1, long long r1,
long long l2, long long r2) {
return {max(l1, l2), min(r1, r2)};
}
long long sum_ranges(long long l, long long r) {
return summation_formula(r) - summation_formula(l);
}
double power_2(double num) { return num * num; }
bool isPowerOfTwo(int x) { return (x && !(x & (x - 1))); }
long long modInverse(long long A, long long M) {
return fastpowermod(A, M - 2, M);
}
long long num_inrange(long long l, long long r) {
l = min(l, r);
r = max(l, r);
return r - l + 1;
}
long long how_many_factor(long long num, long long t) {
long long cnt = 0;
while (num != 0 && num % t == 0) {
num /= t;
cnt++;
}
return cnt;
}
pair<pair<long long, long long>, pair<long long, long long> >
formula_rotate_left_(long long x, long long y, long long row_len,
long long col_len) {
long long nx = col_len - y - 1;
long long ny = x;
return {{nx, ny}, {col_len, row_len}};
}
pair<pair<long long, long long>, pair<long long, long long> >
formula_rotate_right_(long long x, long long y, long long row_len,
long long col_len) {
long long nx = y;
long long ny = row_len - x - 1;
return {{nx, ny}, {col_len, row_len}};
}
pair<pair<long long, long long>, pair<long long, long long> > horizontal_rotate(
long long x, long long y, long long row_len, long long col_len) {
long long nx = x;
long long ny = col_len - y - 1;
return {{nx, ny}, {row_len, col_len}};
}
long long mod_big_integer(string s, long long M) {
long long num = 0;
for (long long i = 0; i < s.size(); i++) {
num = add(mul(num, 10, M), (s[i] - '0'), M);
}
return num;
}
struct Point {
long long x, y;
};
long long overlappingArea(Point l1, Point r1, Point l2, Point r2) {
long long area1 = abs(l1.x - r1.x) * abs(l1.y - r1.y);
long long area2 = abs(l2.x - r2.x) * abs(l2.y - r2.y);
long long areaI =
(min(r1.x, r2.x) - max(l1.x, l2.x)) * (min(r1.y, r2.y) - max(l1.y, l2.y));
return areaI;
}
bool doOverlap(Point l1, Point r1, Point l2, Point r2) {
if (l1.x > r2.x || l2.x > r1.x) {
return false;
}
if (l1.y > r2.y || l2.y > r1.y) {
return false;
}
return true;
}
Point intersection_botl(Point l1, Point r1, Point l2, Point r2) {
Point topr, botl;
topr.y = min(r1.y, r2.y);
topr.x = min(r1.x, r2.x);
botl.y = max(l1.y, l2.y);
botl.x = max(l1.x, l2.x);
return botl;
}
Point intersection_topr(Point l1, Point r1, Point l2, Point r2) {
Point topr, botl;
topr.y = min(r1.y, r2.y);
topr.x = min(r1.x, r2.x);
botl.y = max(l1.y, l2.y);
botl.x = max(l1.x, l2.x);
return topr;
}
long long comp_two(Point l1, Point l2, Point r1, Point r2) {
if (doOverlap(l1, r1, l2, r2)) {
return overlappingArea(l1, r1, l2, r2);
} else {
return 0;
}
}
long long geometric_progression_sum(long long endd, long long st, long long k) {
return (endd * k - st) / (k - 1);
}
long long geometric_progression_sum_mod(long long endd, long long st,
long long k, long long M) {
return mul(sub(mul(endd, k, M), st, M), modInverse(k - 1, M), M);
}
long long M = 1e9 + 7;
const int sz = 1e5 + 10;
const int OO = 0x3f3f3f3f;
vector<pair<long long, long long> > v;
bool solve(long long median_val, long long salary, long long n) {
long long median = (n / 2) + 1;
for (int i = n - 1; i >= 0; i--) {
if (v[i].second >= median_val && median > 0) {
salary -= max(v[i].first, median_val);
median--;
} else {
salary -= v[i].first;
}
}
return (salary >= 0 && median == 0);
}
long long bs(long long l, long long r, long long salary, long long n) {
long long last = -1;
while (l <= r) {
long long mid = l + (r - l) / 2;
if (solve(mid, salary, n)) {
l = mid + 1;
last = mid;
} else {
r = mid - 1;
}
}
return last;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
;
int t;
cin >> t;
while (t--) {
long long n, s;
cin >> n >> s;
v.clear();
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
v.push_back({x, y});
}
sort(v.begin(), v.end());
cout << bs(0, 1e18, s, n) << endl;
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Random;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
SalaryChanging solver = new SalaryChanging();
solver.solve(1, in, out);
out.close();
}
static class SalaryChanging {
int n;
long s;
EzIntIntPair[] a;
long lsum;
boolean ok(long x) {
int numLess = 0, numGreater = 0, numEqual = 0;
for (int i = 0; i < n; i++) {
if (a[i].first < x) {
numLess++;
} else if (a[i].first > x) {
numGreater++;
} else {
numEqual++;
}
}
if (numLess + numEqual < n / 2) {
return false;
}
EzLongArrayList diffs;
diffs = new EzLongArrayList();
for (int i = 0; i < n; i++) {
if (a[i].first < x && x <= a[i].second) {
diffs.add(x - a[i].first);
}
}
int need = (n + 1) / 2 - (numEqual + numGreater);
if (diffs.size() < need) {
return false;
}
diffs.sort();
long total = 0;
for (int i = 0; i < need; i++) {
total += diffs.get(i);
}
return lsum + total <= s;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int tt = in.nextInt();
while (tt-- > 0) {
n = in.nextInt();
s = in.nextLong();
a = new EzIntIntPair[n];
lsum = 0;
for (int i = 0; i < n; i++) {
a[i] = new EzIntIntPair(in.nextInt(), in.nextInt());
lsum += a[i].first;
}
Arrays.sort(a);
long ans = a[n / 2].first;
for (long jump = 2 * s; jump >= 1; jump /= 2) {
while (ok(ans + jump)) {
ans += jump;
}
}
out.println(ans);
}
}
}
static class EzIntIntPair implements Comparable<EzIntIntPair> {
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
public int first;
public int second;
public EzIntIntPair(int first, int second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EzIntIntPair that = (EzIntIntPair) o;
return first == that.first && second == that.second;
}
public int hashCode() {
int hash = HASHCODE_INITIAL_VALUE;
hash = (hash ^ PrimitiveHashCalculator.getHash(first)) * HASHCODE_MULTIPLIER;
hash = (hash ^ PrimitiveHashCalculator.getHash(second)) * HASHCODE_MULTIPLIER;
return hash;
}
public int compareTo(EzIntIntPair o) {
int res = Integer.compare(first, o.first);
if (res == 0) {
res = Integer.compare(second, o.second);
}
return res;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
}
static interface EzLongIterator {
boolean hasNext();
long next();
}
static final class EzLongSort {
private static final Random rnd = new Random();
private EzLongSort() {
}
private static void randomShuffle(long[] a, int left, int right) {
for (int i = left; i < right; i++) {
int j = i + rnd.nextInt(right - i);
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
public static void safeArraysSort(long[] a, int left, int right) {
if (left > right || left < 0 || right > a.length) {
throw new IllegalArgumentException(
"Incorrect range [" + left + ", " + right + ") was specified for sorting, length = " + a.length);
}
randomShuffle(a, left, right);
Arrays.sort(a, left, right);
}
}
static final class PrimitiveHashCalculator {
private PrimitiveHashCalculator() {
}
public static int getHash(int x) {
return x;
}
public static int getHash(long x) {
return (int) x ^ (int) (x >>> 32);
}
}
static interface EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static class EzLongArrayList implements EzLongList, EzLongStack {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
private long[] array;
private int size;
public EzLongArrayList() {
this(DEFAULT_CAPACITY);
}
public EzLongArrayList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
array = new long[capacity];
size = 0;
}
public EzLongArrayList(EzLongCollection collection) {
size = collection.size();
array = new long[size];
int i = 0;
for (EzLongIterator iterator = collection.iterator(); iterator.hasNext(); ) {
array[i++] = iterator.next();
}
}
public EzLongArrayList(long[] srcArray) {
size = srcArray.length;
array = new long[size];
System.arraycopy(srcArray, 0, array, 0, size);
}
public EzLongArrayList(Collection<Long> javaCollection) {
size = javaCollection.size();
array = new long[size];
int i = 0;
for (long element : javaCollection) {
array[i++] = element;
}
}
public int size() {
return size;
}
public EzLongIterator iterator() {
return new EzLongArrayListIterator();
}
public boolean add(long element) {
if (size == array.length) {
enlarge();
}
array[size++] = element;
return true;
}
public long get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index " + index + " is out of range, size = " + size);
}
return array[index];
}
private void enlarge() {
int newSize = Math.max(size + 1, (int) (size * ENLARGE_SCALE));
long[] newArray = new long[newSize];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EzLongArrayList that = (EzLongArrayList) o;
if (size != that.size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[i] != that.array[i]) {
return false;
}
}
return true;
}
public int hashCode() {
int hash = HASHCODE_INITIAL_VALUE;
for (int i = 0; i < size; i++) {
hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER;
}
return hash;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < size; i++) {
sb.append(array[i]);
if (i < size - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString();
}
public void sort() {
EzLongSort.safeArraysSort(array, 0, size);
}
private class EzLongArrayListIterator implements EzLongIterator {
private int curIndex = 0;
public boolean hasNext() {
return curIndex < size;
}
public long next() {
if (curIndex == size) {
throw new NoSuchElementException("Iterator doesn't have more elements");
}
return array[curIndex++];
}
}
}
static interface EzLongList extends EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static class InputReader {
private final InputStream is;
private final byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
public InputReader(InputStream stream) {
is = stream;
}
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
static interface EzLongStack extends EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
long sum=sc.nextLong();
Pair a[]=new Pair[n];
for( int i=0;i<n;i++)
{
a[i]=new Pair(sc.nextLong(),sc.nextLong());
}
Arrays.sort(a, new myComparator());
long low=0;
long high=1000000007;
long mid=0;
while(low<high)
{
mid=(low+high+1)/2;
//System.out.println(mid);
if(possible(mid,a,sum))
{
low=mid;
}
else
{
high=mid-1;
}
}
System.out.println(low);
}
}
public static boolean possible(long val,Pair a[],long S)
{
int n=a.length;long sum=0;int cnt=(n+1)/2;
for( int i=0;i<n;i++)
{
sum+=a[i].x;
}
int count=0;int f=0;
for( int i=n-1;i>=0;i--)
{
if(a[i].x>val)
{
count++;
}
if(count==cnt)
{
f=1;break;
}
if(val>=a[i].x&&val<=a[i].y)
{
count++;
sum+=Math.max(val-a[i].x,0);
}
if(count==cnt)
{
f=1;break;
}
}
if(f==1&&sum<=S)
return true;
else return false;
}
}
class myComparator implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
if(Long.compare(a.x,b.x)!=0)
return (int)Long.compare(a.x,b.x);
else
return (int)Long.compare(a.y,b.y);
}
}
class Pair
{
long x, y;
Pair(long x, long y)
{
this.x=x;
this.y=y;
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long n, s;
vector<pair<int, int> > v;
bool moze(int x) {
long long temp = 0LL;
int br = 0;
vector<int> nz;
for (int i = 0; i < n; ++i) {
if (v[i].second < x)
temp += v[i].first * 1LL;
else if (v[i].first >= x) {
temp += v[i].first * 1LL;
++br;
} else
nz.push_back(v[i].first);
}
if ((n + 1) / 2 - br > (int)(nz).size()) return 0;
int izraz = max(0LL, (n + 1) / 2 - br);
for (int i = 0; i < (int)(nz).size(); ++i) {
if (i < (int)(nz).size() - izraz)
temp += 1LL * nz[i];
else
temp += x * 1LL;
}
return temp <= s;
}
void solve() {
cin >> n >> s;
v.resize(n);
for (auto &z : v) cin >> z.first >> z.second;
int l = 1e9 + 1, r = -1e9 - 10;
for (int i = 0; i < n; ++i) {
l = min(l, v[i].first);
r = max(r, v[i].second);
}
sort((v).begin(), (v).end());
int ans = l;
while (l <= r) {
int mid = l + (r - l) / 2;
if (moze(mid)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int l[200010], r[200010];
vector<long long> d;
void solve() {
long long n, s;
scanf("%lld%lld", &n, &s);
for (int i = 1; i <= n; i++) scanf("%lld%lld", &l[i], &r[i]);
int L = 1, R = 1e9, m = (1 + n) / 2;
long long sum0 = accumulate(l + 1, l + 1 + n, 0LL);
while (L < R) {
int mid = (L + R + 1) / 2;
d.clear();
for (int i = 1; i <= n; i++)
if (r[i] >= mid) d.push_back(max(0, mid - l[i]));
sort(d.begin(), d.end());
if (d.size() >= m && sum0 + accumulate(d.begin(), d.begin() + m, 0LL) <= s)
L = mid;
else
R = mid - 1;
}
printf("%d\n", L);
}
int main() {
int T;
scanf("%d", &T);
while (T--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #!/usr/bin/python3
import array
import math
import os
import sys
def main():
T = read_int()
for _ in range(T):
N, S = read_ints()
A = [read_ints() for _ in range(N)]
print(solve(N, S, A))
def solve(N, S, A):
minv = [l for l, r in A]
minv.sort()
half = N // 2
def feasible(target):
low = []
high = []
mid = []
for p in A:
l, r = p
if target < l:
high.append(p)
elif r < target:
low.append(p)
else:
mid.append(p)
if len(low) >= half + 1 or len(high) >= half + 1:
return False
tsum = 0
for l, r in low:
tsum += l
for l, r in high:
tsum += l
mid.sort()
midi = half - len(low)
for i in range(midi):
l, r = mid[i]
tsum += l
tsum += target * (len(mid) - midi)
return tsum <= S
lb = minv[half]
ub = 10 ** 9 + 1
while ub - lb > 1:
mid = (ub + lb) // 2
if feasible(mid):
lb = mid
else:
ub = mid
return lb
###############################################################################
# AUXILIARY FUNCTIONS
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def read_int():
return int(inp())
def read_ints():
return [int(e) for e in inp().split()]
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
if __name__ == '__main__':
main()
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
import operator
input = sys.stdin.readline
def f(med):
total = 0
cnt = 0
cnt2 = 0
other = []
for x in salaries:
if x[0] > med:
total += x[0] # too big pay min salary
cnt += 1
elif x[1] < med:
total += x[0] # useless so pay min salaray
cnt2 += 1
else:
other.append(x)
if cnt2 > n/2:
return False
other.sort(reverse=True)
for x in other:
if cnt< n/2:
total += med
cnt +=1
else:
total += x[0]
# print(f"total:{total}")
if total > s:
return False
return True
q = int(input())
for _ in range(q):
salaries = []
minl = 999999999999999
maxl = -1
n, s = map(int, input().split())
for __ in range(n):
l, r = map(int, input().split())
if l<minl:
minl = l
if r > maxl:
maxl = r
salaries.append((l, r))
# for i in range(10):
# print(f"i:{i} f:f{f(i)}")
# binary search
a= minl
b = maxl
while b>=a:
m=(a+b)//2
if f(m):
a=m+1
else:
b=m-1
# print("ANS")
print(b)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 99;
const int INF = int(1e9) + 100;
int t;
int n;
long long s;
pair<int, int> p[N];
bool ok(int mid) {
long long sum = 0;
int cnt = 0;
vector<int> v;
for (int i = 0; i < n; ++i) {
if (p[i].second < mid)
sum += p[i].first;
else if (p[i].first >= mid) {
sum += p[i].first;
++cnt;
} else
v.push_back(p[i].first);
}
assert(is_sorted(v.begin(), v.end()));
int need = max(0, (n + 1) / 2 - cnt);
if (need > v.size()) return false;
for (int i = 0; i < v.size(); ++i) {
if (i < v.size() - need)
sum += v[i];
else
sum += mid;
}
return sum <= s;
}
int main() {
scanf("%d", &t);
for (int tc = 0; tc < t; ++tc) {
scanf("%d %lld", &n, &s);
for (int i = 0; i < n; ++i) scanf("%d %d", &p[i].first, &p[i].second);
sort(p, p + n);
int lf = 1, rg = INF;
while (rg - lf > 1) {
int mid = (lf + rg) / 2;
if (ok(mid))
lf = mid;
else
rg = mid;
}
printf("%d\n", lf);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
# for #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
for t in range(int(input())):
n,m = [int(j) for j in input().split()]
ls = []
r_max = 0
# l_min = 1e9+11
for i in range(n):
l,r = [int(j) for j in input().split()]
m -= l
r_max = max(r_max, r)
# l_max = min(l_min, l)
ls.append((l,r))
ls.sort()
meind = (n-1)//2
lf = ls[(n-1)//2][0]
rt = r_max
ans = ls[(n-1)//2][0]
# print(ls, m)
def fun(med):
# global m
mon = m
cnt = 0
for i in range(meind, n):
if ls[i][0]<med:
if ls[i][1]>=med:
mon -= (med - ls[i][0])
else:
cnt += 1
if cnt>0:
for i in range(meind-1, -1, -1):
if cnt<=0:
break
if ls[i][1]>=med:
mon -= (med - ls[i][0])
cnt-=1
# else:
# return False
# mon -= (med - ls[i][0])
if mon>=0 and cnt<=0:
return True
return False
while(lf<=rt):
mid = lf+(rt-lf)//2
# print(mid, ans, "ds")
if fun(mid)==True:
ans = max(ans, mid)
lf = mid+1
else:
rt = mid-1
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> v;
int t, n;
long long s;
bool ok(int x) {
vector<pair<int, int>> b, c;
int cnt = 0;
long long aux = 0;
for (const auto& [l, r] : v)
if (r < x)
cnt++, aux += l;
else if (x < l)
aux += l;
else
c.emplace_back(l, r);
sort(c.begin(), c.end());
reverse(c.begin(), c.end());
if (cnt > n / 2) return false;
while (cnt < n / 2 && !c.empty()) {
cnt++;
aux += c.back().first;
c.pop_back();
}
aux += 1LL * x * c.size();
return aux <= s;
}
int bs() {
int beg = 0, end = 1e9, mid;
while (beg < end) {
mid = (beg + end + 1) >> 1;
if (ok(mid))
beg = mid;
else
end = mid - 1;
}
return beg;
}
int main() {
for (scanf("%d", &t); t--;) {
scanf("%d %lld", &n, &s);
v.clear();
for (int i = 1, l, r; i <= n; ++i)
scanf("%d %d", &l, &r), v.emplace_back(l, r);
printf("%d\n", bs());
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 100;
const int N = 2e5 + 100;
pair<int, int> vec[N];
int n;
long long s;
bool check(int mid) {
vector<int> temp;
long long sum = 0;
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (vec[i].second < mid) {
sum += vec[i].first;
} else if (vec[i].first >= mid) {
sum += vec[i].first;
cnt++;
} else {
temp.emplace_back(vec[i].first);
}
}
int req = max(0, (n + 1) / 2 - cnt);
if (req > temp.size()) return false;
for (int i = 0; i < temp.size(); ++i) {
if (i < temp.size() - req)
sum += temp[i];
else
sum += mid;
}
return sum <= s;
}
int main() {
int t;
cin >> t;
while (t--) {
cin >> n >> s;
for (int i = 0; i < n; ++i) cin >> vec[i].first >> vec[i].second;
sort(vec, vec + n);
int lf = 1, rg = INF;
while (rg - lf > 1) {
int mid = (lf + rg) / 2;
if (check(mid))
lf = mid;
else
rg = mid;
}
cout << lf << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, maxn = 2e5 + 10;
int n, m;
long long s;
struct node {
int l, r;
bool operator<(const node &x) const { return l < x.l; }
} a[maxn];
bool ok(int x) {
long long sum = 0;
for (int i = 0; i < n; ++i) sum += a[i].l;
int c = 0;
for (int i = n - 1; i >= 0 && c < m; --i) {
if (a[i].r >= x) {
sum += max(x - a[i].l, 0);
c++;
}
}
return c == m && sum <= s;
}
int erfen() {
int l = 0, r = 1e9 + 7;
int mi = 0;
while (l <= r) {
int mid = (l + r) / 2;
if (ok(mid)) {
mi = max(mi, mid);
l = mid + 1;
} else
r = mid - 1;
}
return mi;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d%I64d", &n, &s);
m = (n + 1) / 2;
for (int i = 0; i < n; ++i) scanf("%d%d", &a[i].l, &a[i].r);
sort(a, a + n);
printf("%d\n", erfen());
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.io.*;
import java.util.*;
public class D {
Random random = new Random(751454315315L + System.currentTimeMillis());
class Worker implements Comparable<Worker> {
int l;
int r;
public Worker(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public int compareTo(D.Worker o) {
return l - o.l;
}
}
public void solve() throws IOException {
int t = nextInt();
while (t-- > 0) {
int n = nextInt();
long s = nextLong();
Worker[] workers = new Worker[n];
int[] l = new int[n];
int[] r = new int[n];
for (int i = 0; i < n; i++) {
workers[i] = new Worker(nextInt(), nextInt());
s -= workers[i].l;
}
Arrays.sort(workers);
long median = workers[n / 2].l;
long left = median;
long right = (long) 2e14 + 1;
while (right - left > 1) {
long m = left + (right - left) / 2;
int more = 0;
long ss = s;
for (int i = n - 1; i >= 0; i--) {
if (workers[i].r < m || ss < m - workers[i].l) continue;
if (workers[i].l >= m) {
more++;
continue;
}
ss -= m - workers[i].l;
more++;
}
if (more >= (n + 1) / 2) {
left = m;
} else {
right = m;
}
}
out.println(left);
}
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public int[] nextArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new D().run();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
range = xrange
input = raw_input
inp = sys.stdin.read().split(); ii = 0
ans = []
t = int(inp[ii]); ii += 1
for _ in range(t):
n = int(inp[ii]); ii += 1
s = int(inp[ii]); ii += 1
L = [int(x) for x in inp[ii :ii + 2 * n: 2]]
R = [int(x) for x in inp[ii + 1:ii + 2 * n: 2]]
ii += 2 * n
order = sorted(range(n), key = L.__getitem__)
L = [L[i] for i in order]
R = [R[i] for i in order]
s -= sum(L)
s = int(s)
a = sorted(L)[n//2]
b = max(R)
while a < b:
c = a + b + 1 >> 1
picks = [L[i] for i in range(n) if R[i]>= c]
if len(picks) < n//2 + 1:
b = c - 1
continue
extra = sum(max(0, c - p) for p in picks[-(n//2 + 1):])
if extra <= s:
a = c
else:
b = c - 1
ans.append(a)
print '\n'.join(str(c) for c in ans)
| PYTHON |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long INF = 1000 * 1000 * 1000;
const long long int mod = 1000000007;
long long int l[300000], r[300000];
int main() {
std::ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
int n, c;
cin >> n;
long long int s, sum = 0;
cin >> s;
for (int i = 0; i < n; i++) {
cin >> l[i] >> r[i];
s -= l[i];
}
long long int a = 0, b = INF, ans, mid;
bool flag = false;
c = n / 2 + 1;
while (a <= b) {
priority_queue<long long int> p;
flag = false;
mid = (a + b) / 2;
sum = 0;
for (int i = 0; i < n; i++) {
if (r[i] >= mid) {
p.push(l[i]);
}
}
if (p.size() >= c) {
for (int i = 0; i < c; i++) {
sum += max(0ll, mid - p.top());
p.pop();
}
if (sum <= s) {
flag = true;
}
}
if (flag) {
ans = mid;
a = mid + 1;
} else {
b = mid - 1;
}
}
cout << ans << '\n';
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class temp {
boolean possible(long midean , int l[] , int r[] , int n , long s)
{
int c = 0;
for(int i=0;i<n;i++)
{
if(r[i] < midean)
{
c++;
s-=l[i];
}
if(l[i] >= midean)
s-=l[i];
}
ArrayList<pair> a = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(l[i]< midean && r[i]>= midean)
a.add(new pair(l[i],r[i]));
}
Collections.sort(a , new pair());
for(int i=0;i<a.size();i++)
{
if(c < n/2)
{
c++;
s-=a.get(i).l;
}
else
s-=midean;
}
if(c > n/2)
return false;
if(s >= 0)
return true;
else
return false;
}
void solve() throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
long s = sc.nextLong();
int l[] = new int[n];
int r[] = new int[n];
for(int i=0;i<n;i++)
{
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
long ll = 0 , rr = Integer.MAX_VALUE , ans = 0;
while(ll<=rr)
{
long mid = (ll+rr)/2;
if(possible(mid , l , r , n , s))
{
ans = mid;
ll = mid+1;
}
else
rr = mid-1;
}
System.out.println(ans);
}
}
class pair implements Comparator<pair>
{
int l , r;
public pair(int l,int r)
{
this.l = l;
this.r = r;
}
public pair() {
}
public int compare(pair p , pair q)
{
return Integer.compare(p.l , q.l)!=0 ? Integer.compare(p.l , q.l) : Integer.compare(p.r , q.r);
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new temp().solve();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
long long int k;
cin >> n >> k;
vector<pair<int, int> > a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].first >> a[i].second;
}
sort(a.begin(), a.end());
int ans = -1;
long long int l = 0, r = 2e9;
for (int i = 0; i < 60; i++) {
long long int m = l + (r - l) / 2;
int less = 0, right = 0, center = 0;
long long int money = 0;
vector<int> c;
for (auto &e : a) {
if (e.second < m) {
money += e.first;
} else if (e.first >= m) {
money += e.first;
right++;
} else if (e.first < m && m <= e.second) {
c.push_back(e.first);
}
}
int need = max(0, (n + 1) / 2 - right);
if (need > c.size()) {
r = m - 1;
} else {
for (int i = 0; i < c.size(); i++) {
if (i < c.size() - need)
money += c[i];
else
money += m;
}
if (money <= k) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int N;
int l[maxn], r[maxn];
long long s;
int check(int x) {
int must_g = 0, must_s = 0;
long long sum = 0;
vector<int> num;
for (int i = 1; i <= N; i++) {
if (r[i] < x)
must_s++, sum += l[i];
else if (l[i] > x)
must_g++, sum += l[i];
else if (l[i] <= x && r[i] >= x)
num.push_back(l[i]);
}
if (must_g > (N - 1) / 2) return 1;
if (must_s > (N - 1) / 2) return 0;
sort(num.begin(), num.end());
int remain = (N - 1) / 2 - must_s;
for (int i = 0; i <= remain - 1; i++) sum += num[i];
remain = (N - 1) / 2 - must_g + 1;
sum += (long long)remain * (long long)x;
return sum <= s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) {
cin >> N >> s;
for (int i = 1; i <= N; i++) cin >> l[i] >> r[i];
int lll = 1, rrr = 1e9, ans = 0;
while (lll <= rrr) {
int mid = (lll + rrr) >> 1;
if (check(mid)) {
lll = mid + 1;
ans = max(ans, mid);
} else
rrr = mid - 1;
}
cout << ans << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | // @uthor -: puneet
// TimeStamp -: 11:27 PM - 31/10/19
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Bserach implements Runnable {
public void solve() {
int t=in.ni();
while (t-->0){
ArrayList<Pair> list=new ArrayList<>();
int n=in.ni();
long s=in.nl();
for(int i=0;i<n;++i){
list.add(new Pair(in.nl(),in.nl()));
}
Collections.sort(list);
// out.println(list);
long low=1L,high=(long)2E14+1L;
while (low< high){
long mid=(low+high)>>1L;
if(isOk(s,mid,list)){
low=mid+1;
}else {
high=mid;
}
}
out.println(low-1);
}
}
boolean isOk(long s,long m,ArrayList<Pair> list){
int n=list.size();
long sum=0L;
int cnt=0;
ArrayList<Long> remain = new ArrayList<>();
for(int i=0;i<n;++i){
if(list.get(i).r<m)
sum+=list.get(i).l;
else if(list.get(i).l>m) {
sum += list.get(i).l;
cnt++;
}else {
remain.add(list.get(i).l);
}
}
int need=Math.max(0,(n+1)/2-cnt);
if(need>remain.size() || need<0)
return false;
for(int i=remain.size()-1;i>=0;--i){
if(need>0)
sum+=m;
else
sum+=remain.get(i);
need--;
}
return s>=sum;
}
class Pair implements Comparable<Pair> {
long l,r;
public Pair(long l, long r) {
this.l = l;
this.r = r;
}
@Override
public int compareTo(Pair pair) {
return Long.compare(l,pair.l);
}
@Override
public String toString() {
return l+" "+r;
}
}
/* -------------------- Templates and Input Classes -------------------------------*/
@Override
public void run() {
long time = System.currentTimeMillis();
try {
init();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solve();
out.flush();
System.err.println(System.currentTimeMillis() - time);
}
private FastInput in;
private PrintWriter out;
public static void main(String[] args) throws Exception {
// new Thread(null, new Q4(), "Main", 1 << 26).start();
new Bserach().run();
}
private void init() throws FileNotFoundException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
try {
if (System.getProperty("user.name").equals("puneet")) {
outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt");
inputStream = new FileInputStream("/home/puneet/Desktop/input.txt");
}
} catch (Exception ignored) {
}
out = new PrintWriter(outputStream);
in = new FastInput(inputStream);
}
private void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public long ModPow(long x, long y, long MOD) {
long res = 1L;
x = x % MOD;
while (y >= 1) {
if ((y & 1) > 0) res = (res * x) % MOD;
x = (x * x) % MOD;
y >>= 1;
}
return res;
}
public int gcd(int a, int b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
static class FastInput {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInput(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String ns() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(ns());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nc() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nd() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, ni());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, ni());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String next() {
return ns();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] intarr(int n) {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
public double[] doublearr(int n) {
double arr[] = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nd();
}
return arr;
}
public double[][] doublearr(int n, int m) {
double[][] arr = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nd();
}
}
return arr;
}
public int[][] intarr(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = ni();
}
}
return arr;
}
public long[][] longarr(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nl();
}
}
return arr;
}
public long[] longarr(int n) {
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Q3 {
static int bs(long arr[][], long sum, long mid) {
int cntBig = 0, cntSmall = 0, n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i][1] < mid) {
cntSmall++;
sum -= arr[i][0];
} else if (arr[i][0] > mid) {
cntBig++;
sum -= arr[i][0];
}
}
if (cntSmall > n / 2 || sum<0) return -1;
if (cntBig > n / 2) return 1;
for (int i = 0; i < n; i++) {
if (arr[i][0] <= mid && arr[i][1] >= mid) {
if(cntSmall<n/2){
sum-=arr[i][0];
cntSmall++;
}else{
sum-=mid;
cntBig++;
}
}
}
if(sum<0) return -1;
return 0;
}
public static void main(String[] args) {
InputReader in = new InputReader(true);
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
long s = in.nextLong();
long arr[][] = new long[n][2];
for (int i = 0; i < n; i++) {
arr[i][0] = in.nextLong();
arr[i][1] = in.nextLong();
}
// bs->0 = Fine
// bs ->-1= small
// bs -> =big
Arrays.sort(arr, (o1, o2) -> Long.compare(o1[0], o2[0]));
long l = 0, r = (long)Math.min(s,1e9),ans=0;
while (l <= r) {
long mid = (l + r)/2,val=bs(arr,s,mid);
if (val==0){
l=mid+1;
ans=mid;
}else if(val==1){
l=mid+1;
}else if(val==-1){
r=mid-1;
}
}
out.println(ans);
}
out.close();
}
static class InputReader {
int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
InputStream is;
public InputReader(boolean onlineJudge) {
is = System.in;
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
void deepFillInt(Object array, int val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof int[]) {
int[] intArray = (int[]) array;
Arrays.fill(intArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFillInt(obj, val);
}
}
}
void deepFillLong(Object array, long val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof long[]) {
long[] intArray = (long[]) array;
Arrays.fill(intArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFillLong(obj, val);
}
}
}
}
}
// static int[] createArray(int arr[],int s,int e){
// if(s>e)
// return new int[0];
// int cnt[]=new int[e-s+1];
// for(int i=0;i<cnt.length;i++)
// cnt[i]=arr[s+i];
// return cnt;
// }
//
// static long countInversion(int arr[]){
//
// if(arr.length<=1)
// return 0;
// int mid =(arr.length)/2;
// int arr1[]= createArray(arr,0,mid-1),arr2[]= createArray(arr,mid,arr.length-1);
// long total= countInversion(arr1);
// total+=countInversion(arr2);
//
// int i=0, j=0,index=0;
// while(i<arr1.length && j<arr2.length){
// if(arr1[i]>=arr2[j]){
// arr[index++]=arr2[j++];
// }else{
// arr[index++]=arr1[i++];
// total+=j;
// }
// }
//
// while(i<arr1.length){
// total+=arr2.length;
// arr[index++]=arr1[i++];
// }
// while(j<arr2.length){
// arr[index++]=arr2[j++];
// }
//
// return total;
// }
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | # -*- coding: utf-8 -*-
# @Time : 2021/2/4 7:21 δΈε
# @Author : qu
# @Email : [email protected]
# @File : D. Salary Changing.py
from sys import stdin
t = int(stdin.readline())
for _ in range(t):
n, s = map(int, stdin.readline().split())
lr = [list(map(int, stdin.readline().split())) for i in range(n)]
lr.sort(reverse=True)
l = 0
r = s + 1
while l + 1 < r:
mid = (l + r) // 2
right_cnt = 0
salary = 0
for p in lr:
if p[0] > mid:
right_cnt += 1
salary += p[0]
elif p[0] <= mid <= p[1]:
if right_cnt < (n + 1) // 2:
right_cnt += 1
salary += mid
else:
salary += p[0]
elif mid > p[1]:
salary += p[0]
if salary <= s and right_cnt >= (n + 1) // 2:
l = mid
else:
r = mid
print(l)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
int n, vis[N + 2];
long long s;
vector<pair<int, int> > v;
bool ok(int md) {
for (int i = 0; i < n; i++) vis[i] = 0;
int cnt = (n + 1) / 2;
long long ss = s;
for (int i = n - 1; i >= 0; i--) {
if (v[i].second >= md && cnt) vis[i] = 1, cnt--, ss -= max(md, v[i].first);
}
if (cnt || ss < 0) return false;
for (int i = 0; i < n; i++) {
if (!vis[i]) ss -= v[i].first;
if (ss < 0) return false;
}
return true;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n >> s;
v.resize(n);
for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second;
sort(v.begin(), v.end());
int lo = v[n / 2].first, hi = 1e9, md;
while (hi - lo > 2) {
md = (lo + hi) / 2;
if (ok(md))
lo = md;
else
hi = md;
}
for (md = hi; md >= lo; md--)
if (ok(md)) break;
cout << md << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimization("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma GCC target("avx2,avx,fma")
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int i, j, t;
cin >> t;
for (i = 0; i < t; i++) {
int n;
long long int s;
cin >> n >> s;
vector<pair<long long int, long long int> > v;
long long int l, r;
for (j = 0; j < n; j++) {
cin >> l >> r;
v.push_back(make_pair(l, r));
}
sort(v.rbegin(), v.rend());
l = 1;
r = s;
while (l <= r) {
long long int mid = (l + r) / 2;
long long int sum = 0;
int k = 0;
for (j = 0; j < n; j++) {
if (v[j].second >= mid && k < n / 2 + 1) {
sum += max(v[j].first, mid);
k++;
} else
sum += v[j].first;
}
if (k < (n / 2 + 1) || sum > s)
r = mid - 1;
else
l = mid + 1;
}
cout << r << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
public class D {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
D runner = new D();
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
runner.run(sc, out);
}
out.close();
}
public void run(FastScanner sc, FastPrinter out) throws Exception {
int N = sc.nextInt();
long S = sc.nextLong();
long[][] arr = new long[N][2];
for (int i = 0; i < N; i++) {
arr[i][0] = sc.nextLong();
arr[i][1] = sc.nextLong();
}
for (int i = 0; i < N; i++) {
long[] temp = arr[i];
int rand = (int) (Math.random());
arr[i] = arr[rand];
arr[rand] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
return (int) (b[0] - a[0]);
}
});
long min = 0;
long max = S;
while (min <= max) {
long mid = (min + max) / 2;
if (works(arr, S, mid)) {
min = mid + 1;
} else {
max = mid - 1;
}
}
out.println(max);
}
private boolean works(long[][] arr, long budget, long med) {
int N = arr.length;
int count = N / 2 + 1;
for (int i = 0; i < N; i++) {
if (arr[i][1] >= med && count > 0) {
count--;
long cost = arr[i][0];
if (cost < med) cost = med;
budget -= cost;
} else {
budget -= arr[i][0];
}
}
return budget >= 0 && count == 0;
}
public void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int r = (int) (Math.random() * arr.length);
if (i != r) {
arr[i] ^= arr[r];
arr[r] ^= arr[i];
arr[i] ^= arr[r];
}
}
}
static class FastScanner {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream stream) {
din = new DataInputStream(stream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String fileName) throws IOException {
Path p = Paths.get(fileName);
buffer = Files.readAllBytes(p);
bytesRead = buffer.length;
}
int[] nextIntArray(int N) throws IOException {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = nextInt();
}
return arr;
}
String nextLine() throws IOException {
int c = read();
while (c != -1 && isEndline(c))
c = read();
if (c == -1) {
return null;
}
StringBuilder res = new StringBuilder();
do {
if (c >= 0) {
res.appendCodePoint(c);
}
c = read();
} while (!isEndline(c));
return res.toString();
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
String next() throws Exception {
int c = readOutSpaces();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
if (din == null) {
bufferPointer = 0;
bytesRead = -1;
} else {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
private int readOutSpaces() throws IOException {
while (true) {
if (bufferPointer == bytesRead) fillBuffer();
int c = buffer[bufferPointer++];
if (!isSpaceChar(c)) {
return c;
}
}
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][] adj = new int[N][];
int[] numNodes = new int[N];
int[][] input = new int[M][2];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
input[i][0] = a;
input[i][1] = b;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
adj[a][numNodes[a]++] = b;
if (bidirectional) adj[b][numNodes[b]++] = a;
}
return adj;
}
public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][][] adj = new int[N][][];
int[] numNodes = new int[N];
int[][] input = new int[M][3];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
int d = nextInt();
input[i][0] = a;
input[i][1] = b;
input[i][2] = d;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]][2];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
int d = input[i][2];
adj[a][numNodes[a]][0] = b;
adj[a][numNodes[a]][1] = d;
numNodes[a]++;
if (bidirectional) {
adj[b][numNodes[b]][0] = a;
adj[b][numNodes[b]][1] = d;
numNodes[b]++;
}
}
return adj;
}
}
static class FastPrinter {
static final char ENDL = '\n';
StringBuilder buf;
PrintWriter pw;
public FastPrinter(OutputStream stream) {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public FastPrinter(String fileName) throws Exception {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
public FastPrinter(StringBuilder buf) {
this.buf = buf;
}
public void print(int a) {
buf.append(a);
}
public void print(long a) {
buf.append(a);
}
public void print(char a) {
buf.append(a);
}
public void print(char[] a) {
buf.append(a);
}
public void print(double a) {
buf.append(a);
}
public void print(String a) {
buf.append(a);
}
public void print(Object a) {
buf.append(a.toString());
}
public void println() {
buf.append(ENDL);
}
public void println(int a) {
buf.append(a);
buf.append(ENDL);
}
public void println(long a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char[] a) {
buf.append(a);
buf.append(ENDL);
}
public void println(double a) {
buf.append(a);
buf.append(ENDL);
}
public void println(String a) {
buf.append(a);
buf.append(ENDL);
}
public void println(Object a) {
buf.append(a.toString());
buf.append(ENDL);
}
public void printf(String format, Object... args) {
buf.append(String.format(format, args));
}
public void close() {
pw.print(buf);
pw.close();
}
public void flush() {
pw.print(buf);
pw.flush();
buf.setLength(0);
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int ie=0;ie<t;ie++) {
int n=s.nextInt();
long to=s.nextLong();
pair[] arr=new pair[n];
for(int i=0;i<n;i++) {
long a=s.nextLong();
long b=s.nextLong();
pair ob=new pair(a,b);
arr[i]=ob;
}
Arrays.sort(arr,new comp());
bs(arr,to);
}
}
public static void bs(pair[] arr,long to) {
long st=0;
int n=arr.length;
long end=to;
long ans=0;
while(st<=end) {
long mid=(st+end)/2;
long sum=0;
int count=0;
for(int i=0;i<n;i++) {
if(mid<arr[i].l) {
sum=sum+arr[i].l;
count++;
}else if(mid>arr[i].r) {
sum=sum+arr[i].l;
}else {
int rem=Math.max(0, ((n+1)/2)-count);
if(rem>0) {
count++;
sum=sum+mid;
}else {
sum=sum+arr[i].l;
}
}
}
if(sum>to) {
end=mid-1;
}else {
if(count<(n+1)/2) {
end=mid-1;
}else if(count==(n+1)/2) {
ans=mid;
st=mid+1;
}else {
st=mid+1;
}
}
}
System.out.println(ans);
}
}
class pair{
long l;
long r;
public pair(long l,long r)
{
this.l=l;
this.r=r;
}
}
class comp implements Comparator<pair>{
public int compare(pair a,pair b) {
if(a.l<b.l) {
return 1;
}else if(a.l==b.l){
if(a.r<=b.r) {
return 1;
}else {
return -1;
}
}else {
return -1;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 69;
const int64_t INF = 100000000000000018LL;
long long p[N], n, szz[N], m, k;
long long check(vector<pair<long long, long long> >& v, long long m,
long long s) {
long long i, l_b = (long long)v.size() / 2, r_b = 1 + (long long)v.size() / 2;
vector<long long> visited((long long)v.size(), 0);
long long f = 0, sum = 0, cnt = 0, y;
for (i = 0; i < (long long)v.size(); i++) {
if (v[i].first >= m) {
visited[i] = 1;
sum += v[i].first;
cnt++;
if (v[i].first == m) f = 1;
}
}
if (sum > s) return 0;
if (cnt >= r_b && f == 0) return 1;
vector<pair<long long, long long> > v1;
for (i = 0; i < (long long)v.size(); i++) {
if (!visited[i]) v1.push_back({v[i].first, v[i].second});
}
sort((v1).begin(), (v1).end());
if ((long long)v1.size() == 0) {
if (sum <= s && f == 1) return 1;
return 0;
}
vector<long long> vis((long long)v1.size(), 0);
if (cnt < r_b) {
y = r_b - cnt;
for (i = (long long)v1.size() - 1; i >= 0 && y; i--) {
if (v1[i].second >= m) {
sum += m;
f = 1;
y--;
vis[i] = 1;
}
}
if (y) return 0;
}
long long yoyo = INT_MIN;
for (i = 0; i < (long long)v1.size(); i++) {
if (!vis[i]) {
if (v1[i].first == m) f = 1;
yoyo = max(yoyo, v1[i].first);
sum += v1[i].first;
}
}
if (f == 0 && yoyo != INT_MIN) {
sum = sum - yoyo + m;
f = 1;
}
if (sum <= s && f == 1) return 1;
return 0;
}
void solve() {
long long n, s, i, l_min = INT_MAX, r_mx = INT_MIN;
cin >> n >> s;
vector<pair<long long, long long> > v;
for (i = 0; i < n; i++) {
long long l, r;
cin >> l >> r;
v.push_back({l, r});
l_min = min(l_min, l);
r_mx = max(r_mx, r);
}
sort((v).begin(), (v).end());
long long l = l_min, r = r_mx, mid, ans;
while (l <= r) {
mid = l + (r - l) / 2;
if (check(v, mid, s)) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t = 1;
cin >> t;
while (t--) {
solve();
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input = sys.stdin.readline
t=int(input())
while t>0:
t-=1
n,ss=map(int,input().split())
lr=[]
sl=0
for i in range(n):
l,r=map(int,input().split())
sl+=l
lr.append([l,r])
l=0
r=10**9+1
while r-l>1:
mid=(r+l)//2
s=[]
for i in range(n):
if mid<=lr[i][1]:
s.append(max(-lr[i][0],-mid))
if len(s)<n//2+1:
r=mid
continue
s.sort()
sumi=sl+(n//2+1)*mid+sum(s[:n//2+1])
if sumi>ss:
r=mid
else:
l=mid
#print(r,l)
#print(r,l,sumi,ss)
print(l) | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = scan.nextInt();
while (t --> 0) solver.solve(1, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, Scanner scan, PrintWriter out) {
int n = scan.nextInt();
long s = scan.nextLong();
Range[] a = new Range[n];
for(int i = 0; i < n; i++) a[i] = new Range(scan.nextLong(), scan.nextLong());
Arrays.sort(a);
long low = a[n/2].l, high = s, ans = 0;
while(low <= high) {
long mid = (low+high) >> 1;
boolean ok = false;
ArrayList<Long> above = new ArrayList<>();
long cost = 0;
int highCount = 0;
for(int i = 0; i < n; i++) {
if(a[i].l <= mid) {
cost += a[i].l;
if(a[i].r >= mid) above.add(mid-a[i].l);
}
else {
highCount++;
cost += a[i].l;
}
}
int need = n/2 + 1 - highCount;
if(need <= above.size()) {
Collections.sort(above);
for(int i = 0; i < need; i++) cost += above.get(i);
ok = cost <= s;
}
if(ok) {
ans = mid;
low = mid+1;
}
else high = mid-1;
}
out.println(ans);
}
static class Range implements Comparable<Range> {
long l, r;
public Range(long a, long b) {
l = a;
r = b;
}
@Override
public int compareTo(Range o) {
if(l == o.l) return Long.compare(r, o.r);
return Long.compare(l, o.l);
}
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct Data {
long long l, r;
} a[200100];
long long n, s, rmax, lmin;
void Docfile() {
scanf("%lld%lld", &n, &s);
rmax = 0;
lmin = 1e18;
for (int i = 1; i <= n; i++) {
scanf("%lld%lld", &a[i].l, &a[i].r);
rmax = max(rmax, a[i].r);
lmin = min(lmin, a[i].l);
}
}
bool cmp(Data &a, Data &b) {
return ((a.l < b.l) || ((a.l == b.l) && (a.r < b.r)));
}
void Xuli() {
sort(a + 1, a + 1 + n, cmp);
long long sum1, sum2, dem1, dem2, dem3, F[200100];
long long d = lmin, c = rmax, g, kq = 0;
while (d <= c) {
g = (d + c) / 2;
dem1 = dem2 = dem3 = sum1 = sum2 = 0;
F[0] = 0;
for (int i = 1; i <= n; i++) {
if (a[i].r < g) {
dem1++;
sum1 += a[i].l;
} else {
if (a[i].l > g) {
dem2++;
sum2 += a[i].l;
} else {
dem3++;
F[dem3] = F[dem3 - 1] + a[i].l;
}
}
}
if (dem1 > n / 2) {
c = g - 1;
continue;
}
if (dem2 > n / 2) {
d = g + 1;
continue;
}
if (dem1 < n / 2) sum1 += F[n / 2 - dem1];
if (dem2 < n / 2) sum2 += g * (n / 2 - dem2);
if (sum1 + sum2 + g <= s) {
kq = max(kq, g);
d = g + 1;
} else
c = g - 1;
}
printf("%lld\n", kq);
}
int main() {
long t;
scanf("%d", &t);
for (int i = 1; i <= t; i++) {
Docfile();
Xuli();
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class codeforces {
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// The next two void functions are shuffle functions on an array.
// This way, quick sort encounters the worst case scenario with low probability.
// A reason for doing this is if we don't a primitive data array to an object array.
// For safety reasons, it would be preferable to use object arrays unless doing so expends a lot of time.
public static void shuffleLongArray(long[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i=0; i < n; i++) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static void shuffleIntArray(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i=0; i < n; i++) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static void main (String[] args) throws IOException {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Write your solution here.
int t = sc.nextInt();
for (int asap=0; asap < t; asap++) {
int n = sc.nextInt(); long s = sc.nextLong(); // n % 2 == 1, s is the total money we have
long[][] sale = new long[n][2];
for (int i=0; i < n; i++) {
sale[i][0] = sc.nextLong(); sale[i][1] = sc.nextLong();
if (sale[i][0] > sale[i][1]) {
long tmp = sale[i][0]; sale[i][0] = sale[i][1]; sale[i][1] = tmp;
}
}
Random rnd = new Random();
for (int i=0; i < n; i++) {
long tmp = sale[i][0]; long tmp2 = sale[i][1];
int randomPos = i + rnd.nextInt(n-i);
sale[i][0] = sale[randomPos][0];
sale[i][1] = sale[randomPos][1];
sale[randomPos][0] = tmp;
sale[randomPos][1] = tmp2;
}
Arrays.sort(sale, new Comparator<long[]>() {
public int compare (long[] a, long[] b) {
if (Long.compare(a[0], b[0]) != 0) return Long.compare(a[0], b[0]);
return Long.compare(a[1], b[1]);
}
});
// optimally, I would like to minimize the bottom (n-1)/2 and balance out the top (n+1)/2
// would also preferably like a linear sweep solution, but O(n log n) is also fine
// First, we want to actively raise the median. This is done by increasing the middle term only.
// Let's use binary search.
long left = sale[(n-1)/2][0];
rnd = new Random();
for (int i=0; i < n; i++) {
long tmp = sale[i][0]; long tmp2 = sale[i][1];
int randomPos = i + rnd.nextInt(n-i);
sale[i][0] = sale[randomPos][0];
sale[i][1] = sale[randomPos][1];
sale[randomPos][0] = tmp;
sale[randomPos][1] = tmp2;
}
Arrays.sort(sale, new Comparator<long[]>() {
public int compare (long[] a, long[] b) {
if (Long.compare(a[1], b[1]) != 0) return Long.compare(a[1], b[1]);
return Long.compare(a[0], b[0]);
}
});
long right = sale[(n-1)/2][1];
rnd = new Random();
for (int i=0; i < n; i++) {
long tmp = sale[i][0]; long tmp2 = sale[i][1];
int randomPos = i + rnd.nextInt(n-i);
sale[i][0] = sale[randomPos][0];
sale[i][1] = sale[randomPos][1];
sale[randomPos][0] = tmp;
sale[randomPos][1] = tmp2;
}
Arrays.sort(sale, new Comparator<long[]>() {
public int compare (long[] a, long[] b) {
if (Long.compare(a[0], b[0]) != 0) return Long.compare(a[0], b[0]);
return Long.compare(a[1], b[1]);
}
});
// everything in the range [left, right] is attainable via some algorithm involving toggling the median
while (left != right) {
long mid = (left+right+1)/2; // will lean towards the left if uneven; this is monetary value
int counter = 0; // once counter reaches (n+1)/2 we stop taking
long money = 0L;
for (int i=n-1; i >= 0; i--) {
if (mid >= sale[i][0] && mid <= sale[i][1] && counter < (n+1)/2) {
money += mid;
counter++;
}
else {
if (sale[i][0] >= mid) counter++;
money += sale[i][0];
}
}
// compare to see if we can afford it
if (money <= s) { // so we can afford it and can use a higher median
left = mid;
}
else right = mid-1;
}
out.println(left);
}
out.close();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
long long n, s;
std::vector<std::pair<long long, long long>> employees(200000,
std::make_pair(-1, -1));
bool baz(long long mid) {
long long g_cnt = 0;
std::vector<long long> limbo;
long long sal = 0;
for (long long i = 0; i < n; ++i) {
if (employees[i].second < mid)
sal += employees[i].first;
else if (employees[i].first >= mid) {
++g_cnt;
sal += employees[i].first;
} else
limbo.push_back(i);
}
long long req = ((n + 1) / 2) - g_cnt;
if (req > (long long)limbo.size()) return false;
req = std::max((long long)0, req);
long long rem = (limbo.size() - req);
for (long long i = 0; i < rem; ++i) sal += employees[limbo[i]].first;
for (long long i = 0; i < req; ++i) sal += mid;
if (sal <= s) return true;
return false;
}
void foo() {
scanf("%lld %lld", &n, &s);
for (long long i = 0; i < n; ++i)
scanf("%lld %lld", &employees[i].first, &employees[i].second);
std::sort(employees.begin(), employees.begin() + n);
long long left = 1, right = 200000000001111;
long long ans = 1;
while ((right - left) > 1) {
long long mid = (right + left) / 2;
if (baz(mid)) {
ans = mid;
left = mid;
} else {
right = mid - 1;
}
}
if (left > ans && baz(left)) ans = left;
if (right > ans && baz(right)) ans = right;
printf("%lld\n", ans);
}
int main(void) {
long long t;
scanf("%lld", &t);
while (t--) foo();
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class SalaryChanging {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(f.readLine());
PrintWriter out = new PrintWriter(System.out);
for (int t1 = 0; t1 < t; t1++) {
StringTokenizer tokenizer = new StringTokenizer(f.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
long s = Long.parseLong(tokenizer.nextToken());
Integer[][] lAndR = new Integer[n][2];
for (int i = 0; i < n; i++) {
tokenizer = new StringTokenizer(f.readLine());
lAndR[i][0] = Integer.parseInt(tokenizer.nextToken());
lAndR[i][1] = Integer.parseInt(tokenizer.nextToken());
}
Arrays.sort(lAndR, new ArrayComparator<Integer>(0).reversed());
long min = 1;
long max = s;
long bestPay = -1;
while (min <= max) {
long mid = (max + min) / 2;
if (canPayAtLeast(lAndR, mid, s)) {
bestPay = mid;
min = mid + 1;
} else {
max = mid - 1;
}
}
out.println(bestPay);
}
out.close();
}
private static boolean canPayAtLeast(Integer[][] lAndR, long pay, long money) {
int used = 0;
for (int i = 0; i < lAndR.length; i++) {
if (used <= lAndR.length / 2 && pay <= lAndR[i][1] && pay >= lAndR[i][0]) {
money -= pay;
used++;
} else {
money -= lAndR[i][0];
if (lAndR[i][0] >= pay) {
used++;
}
}
}
if (used < lAndR.length / 2 + 1) {
return false;
}
return money >= 0;
}
private static class ArrayComparator<T extends Comparable<T>> implements Comparator<T[]> {
int index;
public ArrayComparator(int index) {
this.index = index;
}
@Override
public int compare(T[] t1, T[] t2) {
return t1[index].compareTo(t2[index]);
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class d {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// static Scanner s=new Scanner(System.in);
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
String[] ss = s();
int t=i(ss[0]);
while(t-->0){
String[] s1=s();
int n=i(s1[0]);
long sum=l(s1[1]);long salgiven=0;
long[] l=new long[n];
long[] r=new long[n];
for(int i=0;i<n;i++){
String[] s2=s();
l[i]=i(s2[0]);r[i]=i(s2[1]);
salgiven+=l[i];
}
long max=200000000000001L;
long low=0;long high=max;
long ans=0;
while(low<=high){
long mid=(low+high)/2;
int count=n/2+1;
PriorityQueue<Long> pq=new PriorityQueue<>();
for(int i=0;i<n;i++){
if(l[i]>=mid){ count--;continue;}
if(mid<=r[i]){
pq.add(mid-l[i]);
}
}long salgiven1=salgiven;
int flag=0;
for(int i=0;i<count;i++){
if(pq.isEmpty()){
flag=1;break;
}
long toadd=pq.poll();
salgiven1+=toadd;
}
if(salgiven1<=sum&&flag==0){
ans=mid;low=mid+1;
}else
high=mid-1;
}
sb.append(ans+"\n");
}
System.out.println(sb.toString());
}
static String[] s() throws IOException {
return s.readLine().trim().split("\\s+");
}
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int i(String ss) {
return Integer.parseInt(ss);
}
static long l(String ss) {
return Long.parseLong(ss);
}
}
class Node1 implements Comparator<Node1>{
int node;long cost;
public Node1(){
}
public Node1(int node,long cost){
this.node=node;this.cost=cost;
}
@Override
public int compare(Node1 o1, Node1 o2) {
if(o1.cost>o2.cost) return 1;
if(o1.cost==o2.cost) return 0;
return -1;
// return o1.cost-o2.cost;
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.util.Arrays;
import java.util.Scanner;
public class que4 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int test = scn.nextInt();
for (int t = 1; t <= test; t++) {
int n = scn.nextInt();
long s = scn.nextLong();
long[] low = new long[n];
long[] rit = new long[n];
int min=0;
long max=-1;
for (int i = 0; i < n; i++) {
low[i] = scn.nextLong();
rit[i] = scn.nextLong();
s = s - low[i];
max=Math.max(rit[i], max);
}
long v= bs(min,max,s,low,rit);
System.out.println(v);
}
}
public static long bs(long min,long high,long s,long []lo,long []hig){
if(min==high){
return min;
}
long mid=(min+high+1)/2;
if(work(mid,s,lo,hig)){
return bs(mid, high, s, lo, hig);
}
return bs(min, mid-1, s, lo, hig);
}
public static boolean work(long mid,long s,long []lo,long []high){
long []cost=new long[lo.length];
for(int i=0;i<lo.length;i++){
if(mid>high[i]){
cost[i]=Long.MAX_VALUE;
}else{
cost[i]=Math.max(mid-lo[i], 0);
}
}
Arrays.sort(cost);
for(int i=0;i<(lo.length+1)/2;i++){
s-=cost[i];
if(s<0){
return false;
}
}
return true;
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | //package codeforces.contests.eduround75;
import java.io.*;
import java.util.*;
/**
* @author tainic on Oct 24, 2019
*/
public class D {
private static boolean LOCAL;
static {
try { LOCAL = "aurel".equalsIgnoreCase(System.getenv().get("USER")); } catch (Exception e){}
}
private static final String TEST =
"3\n" +
"3 26\n" +
"10 12\n" +
"1 4\n" +
"10 11\n" +
"1 1337\n" +
"1 1000000000\n" +
"5 26\n" +
"4 4\n" +
"2 4\n" +
"6 8\n" +
"5 6\n" +
"2 7";
void solve(InputReader in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
long s = in.nextLong();
LR[] lr = new LR[n];
for (int i = 0; i < n; i++) {
lr[i] = new LR(in.nextLong(), in.nextLong());
}
long max = binSearch(1, s, n, lr, s);
out.println(max);
}
}
private long binSearch(long min, long max, int n, LR[] lr, long s) {
while (min <= max) {
long X = (max - min) / 2 + min;
int k = isPossible(X, n, lr, s);
if (k >= 0) {
min = X + 1;
} else {
max = X - 1;
}
}
return min - 1;
}
private int isPossible(long X, int n, LR[] lr, long s) {
int gt = 0, lt = 0;
List<LR> in = new ArrayList<>();
long sum = 0;
for (LR lri : lr) {
if (lri.L > X) {
gt++;
sum += lri.L;
if (sum > s) return +1;
} else if (lri.R < X) {
lt++;
sum += lri.L;
if (sum > s) return -1;
} else {
in.add(lri);
}
}
Collections.sort(in, new Comparator<LR>() {
@Override
public int compare(LR o1, LR o2) {
return Long.compare(o1.L, o2.L);
}
});
int m = n / 2;
if (gt > m) {
return +1;
}
if (lt > m) {
return -1;
}
for (int i = 0; i < m - lt; i++) {
sum += in.get(i).L;
}
sum += (m - gt + 1) * X;
if (sum <= s) return 0;
else return -1;
}
class LR {
private long L, R;
public LR(long L, long R) {
this.L = L;
this.R = R;
}
}
//region util
static class Util {
private static final Random R = new Random();
public static void sort(int[] a) {
sort(a, 0, a.length - 1);
}
private static void sort(int[] a, int from, int to) {
if (from >= to) {
return;
}
// partition
int pivotIndex = R.nextInt(to - from + 1) + from;
int pivot = a[pivotIndex];
// maintain this invariant, at each step i:
// a[j] < pivot, for j = fromIndex to lt - 1
// a[j] == pivot, for j = lt to i - 1
// a[j] > pivot, for j = gt + 1 to toIndex
int lt = from;
int gt = to;
int i = lt;
while (i <= gt) {
int cmp = a[i] - pivot;
if (cmp < 0) {
swap(a, i, lt);
i++;
lt++;
} else if (cmp > 0) {
swap(a, i, gt);
gt--;
} else {
i++;
}
}
// sort left and right
sort(a, from, lt - 1);
sort(a, gt + 1, to);
}
public static int findFirst(int[] a, int key) {
return findFirstOrLast(a, key, 0, a.length - 1, -1);
}
public static int findLast(int[] a, int key) {
return findFirstOrLast(a, key, 0, a.length - 1, 1);
}
static int findFirstOrLast(int[] a, int key, int fromIndex, int toIndex, int dir) {
int left = fromIndex;
int right = toIndex;
while (left <= right) {
int mid = (left + right) >>> 1;
int cmp = key - a[mid];
if (cmp > 0) {
left = mid + 1;
} else if (cmp < 0) {
right = mid - 1;
} else if (dir == -1 && mid > fromIndex && a[mid - 1] == key) {
right = mid - 1;
} else if (dir == 1 && mid < toIndex && a[mid + 1] == key) {
left = mid + 1;
} else {
return mid;
}
}
return -left - 1;
}
public static int findFirst(long[] a, long key) {
return findFirstOrLast(a, key, 0, a.length - 1, -1);
}
public static int findLast(long[] a, long key) {
return findFirstOrLast(a, key, 0, a.length - 1, 1);
}
static int findFirstOrLast(long[] a, long key, int fromIndex, int toIndex, int dir) {
int left = fromIndex;
int right = toIndex;
while (left <= right) {
int mid = (left + right) >>> 1;
int cmp = Long.compare(key,a[mid]);
if (cmp > 0) {
left = mid + 1;
} else if (cmp < 0) {
right = mid - 1;
} else if (dir == -1 && mid > fromIndex && a[mid - 1] == key) {
right = mid - 1;
} else if (dir == 1 && mid < toIndex && a[mid + 1] == key) {
left = mid + 1;
} else {
return mid;
}
}
return -left - 1;
}
public static <T extends Comparable<T>> int findFirst(List<T> a, T key) {
return findFirstOrLast(a, key, 0, a.size() - 1, -1);
}
public static <T extends Comparable<T>> int findLast(List<T> a, T key) {
return findFirstOrLast(a, key, 0, a.size() - 1, 1);
}
static <T extends Comparable<T>> int findFirstOrLast(List<T> a, T key, int fromIndex, int toIndex, int dir) {
int left = fromIndex;
int right = toIndex;
while (left <= right) {
int mid = (left + right) >>> 1;
int cmp = key.compareTo(a.get(mid));
if (cmp > 0) {
left = mid + 1;
} else if (cmp < 0) {
right = mid - 1;
} else if (dir == -1 && mid > fromIndex && a.get(mid - 1) == key) {
right = mid - 1;
} else if (dir == 1 && mid < toIndex && a.get(mid + 1) == key) {
left = mid + 1;
} else {
return mid;
}
}
return -left - 1;
}
public static void swap(int[] a, int i, int j) {
if (i != j) {
int ai = a[i];
a[i] = a[j];
a[j] = ai;
}
}
public static int[] readInts(InputReader in, int k) {
int[] a = new int[k];
for (int i = 0; i < k; i++) {
a[i] = in.nextInt();
}
return a;
}
}
//endregion
//region main
public static void main(String[] args) throws Exception {
long t = System.currentTimeMillis();
try (
InputReader in = new StreamInputReader(!LOCAL ? System.in : new ByteArrayInputStream(TEST.getBytes()));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out, 2048), false)
) {
new D().solve(in, out);
}
System.err.println("time: " + (System.currentTimeMillis() - t) + "ms");
}
//endregion
//region fast io
abstract static class InputReader implements AutoCloseable {
public abstract int read();
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf;
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this(stream, 2048);
}
public StreamInputReader(InputStream stream, int bufSize) {
this.stream = stream;
this.buf = new byte[bufSize];
}
@Override
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
@Override
public void close() throws Exception {
stream.close();
}
}
//endregion
//region imports
//endregion
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
static final int mod = (int)1e9+7;
static int N = (int)2e6 + 2;
static long[][] salary;
public static void main(String[] args) throws Exception
{
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int test = in.nextInt();
while(test-- > 0)
{
int n = in.nextInt();
long s = in.nextLong();
salary = new long[n][2];
for(int i = 0; i < n; i++)
{
salary[i][0] = in.nextInt();
salary[i][1] = in.nextInt();
}
long l = 1, r = s, ans = -1;
while(l <= r)
{
long m = (l + r) / 2;
if(check(m, n, s))
{
ans = m;
l = m + 1;
}
else
{
r = m - 1;
}
// out.println(l + " " + r + " " + m);
}
out.println(ans);
}
out.flush();
}
static boolean check(long m, int n, long s)
{
PriorityQueue<Long> pq = new PriorityQueue();
int left = 0, right = 0;
for(int i = 0; i < n; i++)
{
if(salary[i][0] < m && salary[i][1] < m)
{
left++;
s -= salary[i][0];
}
else if(salary[i][0] > m && salary[i][1] > m)
{
right++;
s -= salary[i][0];
}
else
{
pq.add(salary[i][0]);
}
}
if(left > n / 2)
{
return false;
}
while(pq.size() > 0)
{
if(left < n / 2)
{
s -= pq.poll();
left++;
}
else
{
s -= m;
pq.poll();
break;
}
}
s -= m * pq.size();
return s >= 0;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException
{
if(st == null || !st.hasMoreElements())
{
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = scan.nextInt();
while (t --> 0) solver.solve(1, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, FastReader scan, PrintWriter out) {
int n = scan.nextInt();
long s = scan.nextLong();
Range[] a = new Range[n];
for(int i = 0; i < n; i++) a[i] = new Range(scan.nextLong(), scan.nextLong());
Arrays.sort(a);
long low = a[n/2].l, high = s, ans = 0;
while(low <= high) {
long mid = (low+high)/2;
boolean ok = false;
ArrayList<Long> above = new ArrayList<>();
long cost = 0;
int highCount = 0;
for(int i = 0; i < n; i++) {
if(a[i].l <= mid) {
cost += a[i].l;
if(a[i].r >= mid) above.add(mid-a[i].l);
}
else {
highCount++;
cost += a[i].l;
}
}
int need = n/2 + 1 - highCount;
if(need <= above.size()) {
Collections.sort(above);
for(int i = 0; i < need; i++) cost += above.get(i);
ok = cost <= s;
}
if(ok) {
ans = mid;
low = mid+1;
}
else high = mid-1;
}
out.println(ans);
}
static class Range implements Comparable<Range> {
long l, r;
public Range(long a, long b) {
l = a;
r = b;
}
@Override
public int compareTo(Range o) {
if(l == o.l) return Long.compare(r, o.r);
return Long.compare(l, o.l);
}
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long MOD = (long long)(1e9 + 7);
const long long N = 200007;
vector<pair<long long, long long>> v;
long long s;
int n;
int sure(long long median) {
long long cnt1 = 0;
long long cnt2 = 0;
long long cnt3 = 0;
long long sum = 0;
vector<long long> tmp;
for (auto ele : v) {
long long l = ele.first;
long long r = ele.second;
if (r < median) {
cnt1 += 1;
sum += l;
} else if (l > median) {
cnt3 += 1;
sum += l;
} else {
cnt2 += 1;
tmp.push_back(l);
}
}
long long mn = (n - 1) / 2;
if (cnt1 > mn) {
return 0;
} else if (cnt3 > mn) {
return 1;
}
int idx = 0;
while (cnt1 < mn) {
cnt1 += 1;
sum += tmp[idx];
idx += 1;
}
for (int i = idx; i < tmp.size(); i++) {
sum += median;
}
if (sum > s) {
return 0;
} else {
return 1;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
int tt;
cin >> tt;
for (int t = 1; t <= tt; t++) {
v.clear();
cin >> n >> s;
for (int i = 0; i < n; i++) {
long long x, y;
cin >> x >> y;
v.push_back({x, y});
}
sort(v.begin(), v.end());
long long l = 1;
long long r = MOD;
long long ans = 0;
while (l <= r) {
long long mid = (l + r) / 2;
if (sure(mid) == 1) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
cout << ans << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.math.BigInteger;
import java.util.*;
public class SalaryChanging_task2 {
static int INF = (int) (1E9 + 100);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int test = scanner.nextInt();
for (int i = 0; i < test; i++) {
int n = scanner.nextInt();
long s = scanner.nextLong();
Pair[] salaries = new Pair[n];
for (int j = 0; j < salaries.length; j++) {
salaries[j] = new Pair(scanner.nextInt(), scanner.nextInt());
}
Arrays.sort(salaries);
int f = 1;
int l = INF;
while (l - f > 1) {
int mid = ((l + f) / 2);
if (midOk(mid, s, salaries))
f = mid;
else
l = mid;
}
System.out.println(f);
}
}
public static boolean midOk(int mid, long s, Pair[] salaries) {
long sum = 0L;
int count = 0;
List<Integer> thirdGroup = new ArrayList<Integer>();
for (int i = 0; i < salaries.length; i++) {
if (salaries[i].e < mid)
sum += salaries[i].b;
else if (salaries[i].b >= mid) {
sum += salaries[i].b;
count++;
} else
thirdGroup.add(salaries[i].b);
}
Collections.sort(thirdGroup);
int rem = Math.max(0, ((salaries.length + 1) / 2) - count);
if (rem > thirdGroup.size()) return false;
for (int i = 0; i < thirdGroup.size(); i++) {
if (i < thirdGroup.size() - rem)
sum += thirdGroup.get(i);
else
sum += mid;
}
return sum <= s;
}
}
class Pair implements Comparable<Pair> {
int b;
int e;
public Pair(int b, int e) {
this.b = b;
this.e = e;
}
@Override
public int compareTo(Pair p) {
return Integer.compare(this.b, p.b);
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int t, n;
long long s, sum;
pair<int, int> opt[maxn];
bool check(int mid) {
int k = 0;
long long total = sum;
for (int i = n; i >= 1; --i) {
if (opt[i].second >= mid) {
k++;
if (mid >= opt[i].first) total += mid - opt[i].first;
if (k == (n + 1) / 2) break;
}
}
return k == (n + 1) / 2 && total <= s;
}
int main() {
scanf("%d", &t);
while (t--) {
sum = 0;
scanf("%d%lld", &n, &s);
int L, R;
for (int i = 1; i <= n; ++i) {
int l, r;
scanf("%d%d", &l, &r);
opt[i] = {l, r};
L = min(L, l);
R = max(R, r);
sum += l;
}
sort(opt + 1, opt + 1 + n);
while (L < R) {
int mid = (L + R + 1) >> 1;
if (check(mid))
L = mid;
else
R = mid - 1;
}
printf("%d\n", L);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> a;
long long s, n;
bool check(long long mid) {
long long cnt = 0;
vector<long long> b;
long long sum = 0;
for (long long i = 0; i < n; i++) {
if (a[i].second < mid)
sum += a[i].first;
else if (a[i].first >= mid) {
cnt++;
sum += a[i].first;
} else {
b.push_back(a[i].first);
}
}
long long cur = max(0LL, (n + 1) / 2 - cnt);
if (cur > b.size()) {
return false;
}
for (long long i = 0; i < b.size(); i++) {
if (b.size() - i <= cur) {
sum += mid;
} else
sum += b[i];
}
return sum <= s;
}
void solve() {
cin >> n >> s;
a.resize(n);
for (long long i = 0; i < n; i++) {
cin >> a[i].first >> a[i].second;
}
sort(a.begin(), a.end());
long long l = 0, r = 2e9;
while (r - l > 1) {
long long mid = (l + r) >> 1;
if (check(mid))
l = mid;
else
r = mid;
}
cout << l << "\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(30);
long long t = 1;
cin >> t;
while (t--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct node {
long long l, r;
} a[200010];
long long n, s;
inline long long v_in() {
char ch = getchar();
long long sum = 0, f = 1;
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) sum = (sum << 3) + (sum << 1) + (ch ^ 48), ch = getchar();
return sum * f;
}
inline bool cmp(const node &a, const node &b) { return a.l < b.l; }
bool judge(long long x) {
long long cnt = 0, k = s;
for (register long long i = n; i >= 1; i--) {
if (a[i].l >= x) {
cnt++;
if (cnt >= n / 2 + 1) return true;
continue;
}
if (a[i].r >= x) {
if (k >= x - a[i].l) {
k -= x - a[i].l;
cnt++;
if (cnt >= n / 2 + 1) return true;
}
}
}
return false;
}
int main() {
long long q = v_in();
while (q--) {
n = v_in(), s = v_in();
long long lmin = 2000000000, rmax = 0;
for (register long long i = 1; i <= n; i++) {
a[i].l = v_in();
s -= a[i].l;
a[i].r = v_in();
lmin = ((lmin) < (a[i].l) ? (lmin) : (a[i].l));
rmax = ((rmax) > (a[i].r) ? (rmax) : (a[i].r));
}
sort(a + 1, a + n + 1, cmp);
long long ans = 0, l = lmin, r = rmax;
while (l <= r) {
long long mid = (l + r) >> 1;
if (judge(mid)) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1251D
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long S = Long.parseLong(st.nextToken());
int[] left = new int[N];
int[] right = new int[N];
Person[] arr = new Person[N];
for(int i=0; i < N; i++)
{
st = new StringTokenizer(infile.readLine());
left[i] = Integer.parseInt(st.nextToken());
right[i] = Integer.parseInt(st.nextToken());
arr[i] = new Person(left[i], right[i]);
}
Arrays.sort(arr);
long low = 0L;
long high = S;
while(low != high)
{
long mid = (low+high+1)/2;
int[] tag = new int[N];
int a = 0;
int b = 0;
for(int i=0; i < N; i++)
{
if(arr[i].max < mid)
{
tag[i] = 1;
a++;
}
else if(arr[i].min > mid)
{
tag[i] = 2;
b++;
}
}
if(a > N/2)
high = mid-1;
else if(b > N/2)
low = mid;
else
{
//left
long cost = 0L;
int boof = N/2;
for(int i=0; i < N; i++)
{
if(tag[i] >= 1)
{
if(tag[i] == 1)
boof--;
cost += arr[i].min;
}
}
for(int i=0; i < N; i++)
if(tag[i] == 0)
{
if(boof > 0)
{
cost += arr[i].min;
boof--;
}
else
cost += mid;
}
if(cost > S)
high = mid-1;
else
low = mid;
}
}
//check within delta
sb.append(low+"\n");
}
System.out.print(sb);
}
}
class Person implements Comparable<Person>
{
public int min;
public int max;
public Person(int a, int b)
{
min = a;
max = b;
}
public int compareTo(Person oth)
{
if(min == oth.min)
return max-oth.max;
return min-oth.min;
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while (T--) {
int N;
long long S;
cin >> N >> S;
long long R[N];
pair<long long, long long> LR[N];
for (int i = 0; i < N; ++i) {
long long l, r;
cin >> l >> r;
R[i] = r;
LR[i] = {l, r};
}
sort(R, R + N);
sort(LR, LR + N);
long long result = 0;
for (long long b = R[N / 2]; b >= 1; b /= 2) {
while (result + b <= R[N / 2]) {
long long spent = 0;
int over = 0;
for (int i = N - 1; i >= 0; --i) {
long long l, r;
tie(l, r) = LR[i];
if (over < (N + 1) / 2 && result + b <= r) {
++over;
spent += max(l, result + b);
} else {
spent += l;
}
}
if (spent > S) break;
result += b;
}
}
cout << result << '\n';
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long n, s, l[200005];
pair<long long, long long> arr[200005];
bool valid(long long x) {
long long cnt = 0;
long long sum = 0, z;
vector<long long> v;
for (int i = 1; i <= n; i++) {
if (arr[i].second < x) {
sum += arr[i].first;
} else if (arr[i].first >= x) {
cnt++;
sum += arr[i].first;
} else {
v.push_back(arr[i].first);
}
}
int butuh = (n + 1) / 2;
butuh -= cnt;
butuh = max(0, butuh);
if (butuh > v.size()) return false;
int sz = v.size();
for (int i = 0; i < sz - butuh; i++) {
sum += v[i];
}
sum += (x * butuh);
return sum <= s;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long t;
cin >> t;
while (t--) {
cin >> n >> s;
for (long long i = 1; i <= n; i++) {
cin >> arr[i].first >> arr[i].second;
}
sort(arr + 1, arr + n + 1);
long long ki = 1, ka = 1e9;
long long pos = ki;
while (ki <= ka) {
long long mid = (ki + ka) / 2;
if (valid(mid)) {
pos = mid;
ki = mid + 1;
} else
ka = mid - 1;
}
cout << pos << endl;
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
int II() {
int n;
scanf("%d", &n);
return n;
}
long long int LL() {
long long int n;
scanf("%lld", &n);
return n;
}
void IIn(int n) { printf("%d\n", n); }
char* SS(char* str) {
scanf("%s", str);
return str + strlen(str);
};
void SSn(char* str) { printf("%s\n", str); }
constexpr int MAXN = 200000;
typedef std::pair<int, int> ii;
ii V[MAXN];
int main() {
for (int T = II(); T--;) {
int N = II();
long long int S = LL();
for (int i = 0; i < N; i++) V[i] = ii{II(), II()};
std::sort(V, V + N, std::greater<ii>());
int M = std::max_element(V, V + N, [](const ii& a, const ii& b) {
return a.second < b.second;
})->second;
int bit = 1;
while (bit <= M) bit <<= 1;
bit >>= 1;
int ans = 0;
S -= std::accumulate(V, V + N, 0LL, [](long long int s, const ii& x) {
return s + x.first;
});
while (bit) {
int m = ans | bit;
{
int to_sat = (N + 1) >> 1;
long long int budget = S;
for (int i = 0; i < N; i++)
if (m <= V[i].second) {
if (budget < m - V[i].first) break;
if (V[i].first < m) budget -= m - V[i].first;
--to_sat;
if (to_sat == 0) break;
}
if (to_sat == 0) ans |= bit;
}
bit >>= 1;
}
IIn(ans);
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by himanshubhardwaj on 24/10/19.
*/
public class SalaryChanging {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (t-- > 0) {
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long s = Long.parseLong(str[1]);
ArrayList<Employee> employees = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
str = br.readLine().split(" ");
employees.add(new Employee(Long.parseLong(str[0]), Long.parseLong(str[1])));
}
pw.append(maximumMedianSalary(s, employees) + "\n");
}
pw.flush();
pw.close();
}
private static long maximumMedianSalary(long s, ArrayList<Employee> employees) {
Comparator<Employee> employeeComparator = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return Long.compare(o1.l, o2.l);
}
};
Collections.sort(employees, employeeComparator);
long lowerBound = employees.get(employees.size() / 2).l;
employeeComparator = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return Long.compare(o1.r, o2.r);
}
};
Collections.sort(employees, employeeComparator);
long upperBound = employees.get(employees.size() / 2).r;
while ((upperBound - lowerBound) >= 100) {
long mid = (upperBound + lowerBound) / 2;
boolean possibility = isPossible(s, mid, employees);
if (possibility) {
lowerBound = mid;
} else {
upperBound = mid;
}
}
for (long i = upperBound; i >= lowerBound; i--) {
// for (long i = 68; i >= lowerBound; i--) {
boolean possibility = isPossible(s, i, employees);
if (possibility) {
return i;
}
}
return 0l;
}
private static boolean isPossible(long s, long median, ArrayList<Employee> employees) {
int countLower = 0;
int countUpper = 0;
int countBetween = 0;
long cost = 0l;
ArrayList<Employee> betweenEmployees = new ArrayList<>();
for (Employee e : employees) {
if (e.r < median) {
cost += e.l;
countLower++;
} else if (e.l > median) {
cost += e.l;
countUpper++;
} else {
betweenEmployees.add(e); //e.l<median<=e.r
}
}
if (countUpper >= (employees.size() - (employees.size() / 2))) {
return false;
}
if (countLower > employees.size() / 2) {
return false;
}
Comparator<Employee> employeeComparator = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return Long.compare(o1.l, o2.l);
}
};
Collections.sort(betweenEmployees, employeeComparator);
for (int i = 0; i < betweenEmployees.size(); i++) {
if ((countLower + i) < (employees.size() / 2)) {
cost += betweenEmployees.get(i).l;
} else {
cost += median;
}
}
// if ((countLower + betweenEmployees.size()) < (employees.size() / 2)) {
// cost += (((employees.size() / 2) + 1 - countLower - betweenEmployees.size()) * median);
// }
if (cost <= s) {
return true;
} else {
return false;
}
}
}
class Employee {
long l;
long r;
@java.beans.ConstructorProperties({"l", "r"})
public Employee(long l, long r) {
this.l = l;
this.r = r;
}
}
/*
1
19 1175
44 87
68 100
93 98
76 79
10 58
74 99
87 97
23 75
62 73
100 100
71 76
73 87
76 82
44 84
54 90
2 82
67 99
85 97
66 88
*
* */ | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class D_Edu_Round_75 {
public static long MOD = 1000000007;
static int[][][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int T = in.nextInt();
for (int z = 0; z < T; z++) {
int n = in.nextInt();
long s = in.nextLong();
long[][] data = new long[n][2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
data[i][j] = in.nextInt();
}
}
long st = 0;
long ed = Integer.MAX_VALUE;
long need = (n >> 1) + 1;
long re = ed;
while (st <= ed) {
long mid = (st + ed) / 2;
PriorityQueue<Long> q = new PriorityQueue<>();
long total = 0;
for (int i = 0; i < n; i++) {
if (data[i][1] < mid) {
total += data[i][0];
} else {
q.add(data[i][0]);
total += Long.max(mid, data[i][0]);
}
}
while (q.size() > need && q.peek() < mid && total > s) {
total -= mid;
total += q.poll();
}
if (total <= s && q.size() >= need) {
re = mid;
st = mid + 1;
} else {
ed = mid - 1;
}
}
out.println(re);
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x;
long y;
public Point(int start, long end) {
this.x = start;
this.y = end;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input = lambda: sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
N, S = map(int, input().split())
X = []
for __ in range(N):
l, r = map(int, input().split())
X.append((l, r))
ok = 1
ng = 10**9+1
while ng - ok > 1:
m = (ok+ng) // 2
A = []
B = []
for i in range(N):
if X[i][1] >= m:
A.append(X[i][0])
else:
B.append(X[i][0])
A = sorted(A)[::-1]
if len(A) > N//2 and sum([max(a, m) for a in A[:N//2+1]]) + sum(A[N//2+1:]) + sum(B) <= S:
ok = m
else:
ng = m
print(ok)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
template <typename T>
T GCD(T a, T b) {
return a ? GCD(b % a, a) : b;
}
template <typename T>
T LCM(T a, T b) {
return (a * b) / GCD(a, b);
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
for (auto ob : v) os << ob << " ";
return os;
}
template <typename T, typename S>
std::ostream &operator<<(std::ostream &os, const std::map<T, S> &v) {
for (auto ob : v) os << ob.first << " : " << ob.second << std::endl;
return os;
}
using ld = double;
using ll = long long int;
using ul = unsigned long long int;
using namespace std;
class DSalaryChanging {
bool Possible(vector<pair<int, int>> money, ll s, int mid, int n) {
ll sum = 0;
int cnt = 0;
vector<int> v;
for (int i = 0; i < n; ++i) {
if (money[i].second < mid) {
sum += money[i].first;
} else if (money[i].first >= mid) {
cnt++;
sum += money[i].first;
} else {
v.push_back(money[i].first);
}
}
sort(v.begin(), v.end());
int need = max(0, ((n + 1) / 2) - cnt);
if (need > v.size())
return false;
else {
for (int i = v.size() - 1; i >= 0; --i) {
if (need) {
need--;
sum += mid;
} else
sum += v[i];
}
return sum <= s;
}
}
public:
void solve(std::istream &in, std::ostream &out) {
ll n, s;
in >> n >> s;
vector<pair<int, int>> money;
for (int i = 0; i < n; ++i) {
int l, r;
in >> l >> r;
money.push_back(make_pair(l, r));
}
sort(money.begin(), money.end());
int low = 1, high = 1e9 + 10, ans = 0;
while (low + 1 < high) {
int mid = (low + high) / 2;
bool isPossible = Possible(money, s, mid, n);
if (isPossible) {
ans = mid;
low = mid;
} else {
high = mid;
}
}
out << ans << endl;
}
};
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(nullptr);
DSalaryChanging solver;
std::istream &in(std::cin);
std::ostream &out(std::cout);
int n;
in >> n;
for (int i = 0; i < n; ++i) {
solver.solve(in, out);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long int max(long long int a, long long int b) {
if (a > b)
return a;
else
return b;
}
long long int min(long long int a, long long int b) {
if (a < b)
return a;
else
return b;
}
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
int XX[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int YY[] = {-1, 0, 1, -1, 1, -1, 0, 1};
bool compare(pair<long long int, long long int>& a,
pair<long long int, long long int>& b) {
if (a.first != b.first) return a.first < b.first;
return a.second < b.second;
}
vector<pair<long long int, long long int> > vec;
long long int ans, n, s;
void func(long long int low, long long int high) {
long long int z = vec.size();
z = z / 2;
long long int i, j;
while (low <= high) {
long long int mid = (low + high) >> 1;
set<long long int> s1, s2;
for (i = 0; i < n; i++) {
if (vec[i].second >= mid) {
s2.insert(i);
}
}
long long int count = z, sum = 0, flag = 0;
for (i = 0; i < n; i++) {
if (count <= 0) break;
if (vec[i].first <= mid) {
if (s2.find(i) != s2.end()) {
if (s2.size() <= z + 1) continue;
s2.erase(i);
}
sum += vec[i].first;
count--;
}
}
if (s2.size() >= z + 1) {
vector<long long int> vec3;
for (auto itr : s2) {
long long int mini = max(mid, vec[itr].first);
vec3.push_back(mini);
}
sort(vec3.begin(), vec3.end());
for (i = 0; i < z + 1; i++) sum += vec3[i];
}
if (count <= 0 && s2.size() >= (z + 1) && sum <= s) {
ans = max(ans, mid);
low = mid + 1;
} else {
high = mid - 1;
}
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
long long int i, j, k, x, y, t, e, d, m, z;
long long int val = 0;
cin >> t;
while (t--) {
val++;
cin >> n >> s;
vec.clear();
for (i = 0; i < n; i++) {
cin >> x >> y;
vec.push_back(make_pair(x, y));
}
sort(vec.begin(), vec.end(), compare);
ans = -9000000000000000000;
long long int maxi = -9000000000000000000;
for (i = 0; i <= n / 2; i++) {
maxi = max(maxi, vec[i].second);
}
func(vec[n / 2].first, maxi);
cout << ans << "\n";
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for ik in range(int(input())):
n,k=map(int,input().split())
a=[]
for i in range(n):
l,r=map(int,input().split())
a.append((l,r))
def check(mid):
less=0
more=0
x=0
e=[]
er=0
er1=0
for i in range(n):
if a[i][1]<mid:
less+=1
er+=a[i][0]
elif a[i][0]>mid:
more+=1
er1+=a[i][0]
else:
x+=1
e.append(a[i][0])
x-=1
e.sort()
if more>n//2:
return 1
elif less>n//2:
return -1
tot=er+er1+sum(e[:(n//2-less)])+(x-n//2+less+1)*mid
if tot<=k:
return 0
return -1
st=0
end=k
ans=0
while(st<=end):
mid=(st+end)//2
#print(mid,check(mid))
ch=check(mid)
if ch==0:
ans=mid
st=mid+1
elif ch==1:
st=mid+1
else:
end=mid-1
print(ans)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
void itval(istream_iterator<string> it) {}
template <typename T, typename... Args>
void itval(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
itval(++it, args...);
}
const long long int MOD = 1e9 + 7;
template <typename T>
inline void print(T x) {
cout << x << "\n";
}
template <typename T>
inline void printvec(T x) {
for (auto a : x) cout << a << ' ';
cout << '\n';
}
struct custom {
bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) const {
return p1.first + p2.second < p1.second + p2.first;
}
};
long long int get_pow(long long int a, long long int b, long long int M) {
long long int res = 1;
while (b) {
if (b & 1) res = (res * a) % M;
a = (a * a) % M;
b >>= 1;
}
return res;
}
const long long int N = 1e5 + 5, inf = 2e18;
void solve() {
long long int n, s;
cin >> n >> s;
std::vector<pair<long long int, long long int> > v(n);
for (long long int i = (long long int)0; i < (long long int)(n); i++) {
cin >> v[i].first >> v[i].second;
}
sort(v.begin(), v.end());
long long int lo = 0, hi = 1e9 + 5;
while (lo + 1 < hi) {
long long int mid = (lo + hi) / 2;
long long int sum = 0, m = n / 2, ok = 1, cnt = 0, c = 0;
vector<bool> used(n, false);
long long int l = 0, h = 0;
for (long long int i = (long long int)0; i < (long long int)(n); i++) {
if (v[i].second < mid) {
sum += v[i].first;
used[i] = 1;
l++;
}
if (v[i].first > mid) {
sum += v[i].first;
used[i] = 1;
h++;
}
}
if (l > n / 2 || h > n / 2) ok = 0;
if (l > n / 2) {
hi = mid;
continue;
}
if (h > n / 2) {
lo = mid;
continue;
}
if (ok) {
for (long long int i = (long long int)0; i < (long long int)(n); i++) {
if (used[i]) continue;
if (l < n / 2) {
sum += v[i].first;
l++;
continue;
}
if (h < n / 2) {
sum += mid;
h++;
continue;
}
}
sum += mid;
if (sum > s) ok = 0;
}
if (ok)
lo = mid;
else
hi = mid;
}
cout << lo << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test = 1;
cin >> test;
clock_t z = clock();
for (long long int tes = (long long int)0; tes < (long long int)(test);
tes++) {
solve();
}
fprintf(stderr, "Total Time:%.4f\n", (double)(clock() - z) / CLOCKS_PER_SEC),
fflush(stderr);
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2e5 + 5;
pair<long long, long long> a[MAXN];
long long s;
long long n;
bool check(long long x) {
long long sum = 0, cnt = 0;
vector<long long> nums;
for (long long i = 0; i < n; i++) {
if (a[i].first >= x) {
sum += a[i].first;
cnt++;
} else {
if (a[i].second < x) {
sum += a[i].first;
} else {
nums.push_back(a[i].first);
}
}
}
long long left = max((long long)0, (n + 1) / 2 - cnt);
if (left > nums.size()) return 0;
for (long long i = 0; i < nums.size() - left; i++) {
sum += nums[i];
}
for (long long i = nums.size() - left; i < nums.size(); i++) {
sum += x;
}
return (sum <= s);
}
int main() {
long long q;
cin >> q;
while (q--) {
cin >> n >> s;
for (long long i = 0; i < n; i++) {
cin >> a[i].first >> a[i].second;
}
sort(a, a + n);
long long l = 1, r = 1e9 + 100;
while (l + 1 < r) {
long long m = (l + r) >> 1;
if (check(m)) {
l = m;
} else {
r = m;
}
}
cout << l << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
def bisearch_max(mn, mx, func):
ok = mn
ng = mx
while ok+1 < ng:
mid = (ok+ng) // 2
if func(mid):
ok = mid
else:
ng = mid
return ok
def check(m):
A1, A2, A3 = [], [], []
cnt = k = 0
for l, r in LR:
if r < m:
# A1.append((l, r))
k += l
elif m <= l:
# A2.append((l ,r))
cnt += 1
k += l
else:
A3.append((l, r))
k += l
if k > K:
return False
if cnt+len(A3) < midcnt:
return False
if cnt >= midcnt and k <= K:
return True
A3.sort(reverse=True)
for l, r in A3:
cnt += 1
k += m - l
if k > K:
return False
if cnt >= midcnt and k <= K:
return True
return False
for _ in range(INT()):
N, K = MAP()
midcnt = N//2 + 1
LR = []
for i in range(N):
l, r = MAP()
LR.append((l, r))
res = bisearch_max(0, 10**9+1, check)
print(res)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.*;
import java.io.*;
public class SalChange {
static BufferedReader br;
static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int t = nextInt();
for(int x = 0; x < t; x++) {
int n = nextInt();
long s = nextLong();
Person[] arr = new Person[n];
for(int i = 0; i < n; i++)
arr[i] = new Person(nextLong(), nextLong());
Arrays.sort(arr, null);
long lo = 0, hi = s + 1;
while(lo < hi) {
long m = (lo + hi) >> 1;
// System.out.println(m + " " + lo + " " + hi + " " + ok(m, s, arr));
if(ok(m, s, arr))
lo = m + 1;
else hi = m;
}
System.out.println(lo - 1);
}
}
public static boolean ok(long k, long s, Person[] arr) {
int needed = arr.length / 2 + 1;
for(int i = arr.length / 2 + 1; i < arr.length; i++) {
if(k <= arr[i].max) {
s -= Math.max(k, arr[i].min);
needed--;
} else s -= arr[i].min;
}
for(int i = arr.length / 2; i >= 0; i--) {
if(needed > 0 && arr[i].max >= k) {
s-= k;
needed--;
} else s -= arr[i].min;
}
if(s >= 0 && needed == 0)
return true;
return false;
}
public static String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class Person implements Comparable<Person> {
long min, max;
public Person(long x, long y) {
super();
this.min = x;
this.max = y;
}
@Override
public int compareTo(Person o) {
if(min != o.min)
return Long.compare(min, o.min);
return Long.compare(max, o.max);
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mufaddal Naya
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DSalaryChanging solver = new DSalaryChanging();
solver.solve(1, in, out);
out.close();
}
static class DSalaryChanging {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int tc = c.readInt();
while (tc-- > 0) {
int n = c.readInt();
long tot = c.readLong();
Point p[] = new Point[n];
int dummy[] = new int[n];
for (int i = 0; i < n; i++) {
int l = c.readInt(), r = c.readInt();
dummy[i] = r;
tot -= l;
p[i] = new Point(l, r);
}
Sort.mergeSort(dummy, 0, n);
Arrays.sort(p);
int upperLimit = dummy[n / 2], lowerLimit = 0;
int best = 0;
while (lowerLimit <= upperLimit) {
int mid = (lowerLimit + upperLimit) / 2;
//w.printLine(mid, lowerLimit, upperLimit);
if (query(mid, p, tot)) {
best = mid;
lowerLimit = mid + 1;
} else {
upperLimit = mid - 1;
}
}
w.printLine(best);
}
}
private boolean query(int mid, Point[] p, long tot) {
int res[] = new int[p.length];
for (int i = p.length - 1; i >= 0; i--) {
if (p[i].l >= mid) {
res[i] = p[i].l;
continue;
}
if (p[i].r < mid) {
res[i] = p[i].l;
continue;
}
if (mid - p[i].l <= tot) {
tot -= (mid - p[i].l);
res[i] = mid;
} else {
res[i] = p[i].l;
}
}
Arrays.sort(res);
if (res[res.length / 2] >= mid) {
return true;
}
return false;
}
}
static class Point implements Comparable<Point> {
int l;
int r;
public Point(int l, int r) {
this.l = l;
this.r = r;
}
public int compareTo(Point o) {
if (this.l == o.l) {
return this.r - o.r;
}
return this.l - o.l;
}
}
static class Sort {
public static void mergeSort(int[] a, int low, int high) {
if (high - low < 2) {
return;
}
int mid = (low + high) >>> 1;
mergeSort(a, low, mid);
mergeSort(a, mid, high);
int[] b = Arrays.copyOfRange(a, low, mid);
for (int i = low, j = mid, k = 0; k < b.length; i++) {
if (j == high || b[k] <= a[j]) {
a[i] = b[k++];
} else {
a[i] = a[j++];
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n;
long long s;
vector<pair<long long, long long>> v;
bool feasible(long long mid) {
long long sum = 0;
int cnt = 0, need;
vector<long long> ans;
for (int i = 0; i < v.size(); i++) {
if (v[i].second < mid)
sum += v[i].first;
else if (v[i].first > mid) {
cnt++;
sum += v[i].first;
} else
ans.push_back(v[i].first);
}
need = max(0, ((n + 1) / 2 - cnt));
if (need > ans.size()) return false;
for (int i = ans.size() - 1; i >= 0; i--) {
if (need != 0) {
need--;
sum += mid;
} else
sum += ans[i];
}
return sum <= s;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
cin >> n >> s;
long long x, y;
v.clear();
for (int i = 0; i < n; i++) {
cin >> x >> y;
v.push_back({x, y});
}
sort(v.begin(), v.end());
long long l = 0, h = s, mid, best = -1;
while (l <= h) {
mid = l + (h - l) / 2;
if (feasible(mid)) {
l = mid + 1;
best = mid;
} else {
h = mid - 1;
}
}
cout << best << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
//import javafx.util.*;
import java.math.*;
//import java.lang.*;
public class Main
{
// static int n;static ArrayList<Integer> adj[];
// static int m;
// static boolean v[];
// static int a[];
// static int leaf[];
// static int dist[];
// static final long oo=(long)1e18;
static int mod=1000000007;
public static void main(String[] args) throws IOException {
// Scanner sc=new Scanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
br = new BufferedReader(new InputStreamReader(System.in));
int t=nextInt();
while(t--!=0){
int n=nextInt();
long s=nextLong();
Pair arr[]=new Pair[n];
for(int i=0;i<n;i++){
int l=nextInt();
int r=nextInt();
arr[i]=new Pair(l,r);
}
Arrays.sort(arr);
int l=1;int r=mod;
int ans=-1;
while(l<=r){
int mid=(l+r)/2;
long sum=0;
int cnt=0;
ArrayList<Integer> ar=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(mid<=arr[i].x){
sum+=arr[i].x;
cnt++;
}
else if(arr[i].y<mid){
sum+=arr[i].x;
}
else{
ar.add(arr[i].x);
}
}
int req=Math.max(0,(n/2+1)-cnt);
if(ar.size()<req){
r=mid-1;
continue;
}
for(int i=0;i<ar.size();i++){
if(i<ar.size()-req){
sum+=ar.get(i);
}
else{
sum+=mid;
}
}
if(sum<=s){
l=mid+1;
ans=mid;
}
else{
r=mid-1;
}
}
pw.println(ans);
}
pw.close();
}
public static BufferedReader br;
public static StringTokenizer st;
public static String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public static Integer nextInt() {
return Integer.parseInt(next());
}
public static Long nextLong() {
return Long.parseLong(next());
}
public static Double nextDouble() {
return Double.parseDouble(next());
}
// static class Pair{
// int x;int y;
// Pair(int x,int y,int z){
// this.x=x;
// this.y=y;
// // this.z=z;
// // this.z=z;
// // this.i=i;
// }
// }
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a,Pair b){
// //return (a.y)-(b.y);
// if(a.y==b.y){
// return -1*(a.z-b.z);
// }
// return (a.y-b.y);
// }
// }
public static int[] na(int n)throws IOException{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = nextInt();
return a;
}
static class query implements Comparable<query>{
int l,r,idx,block;
static int len;
query(int l,int r,int i){
this.l=l;
this.r=r;
this.idx=i;
this.block=l/len;
}
public int compareTo(query a){
return block==a.block?r-a.r:block-a.block;
}
}
static class Pair implements Comparable<Pair>{
int x;int y;
Pair(int x,int y){
this.x=x;
this.y=y;
//this.z=z;
}
public int compareTo(Pair a){
return (x-a.x);
//return (x-a.x)>0?1:-1;
}
}
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a1,Pair a2){
// if(o1.a==o2.a)
// return (o1.b>o2.b)?1:-1;
// else if(o1.a>o2.a)
// return 1;
// else
// return -1;
// }
// }
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 ||
n % 3 == 0)
return false;
for (int i = 5;
i * i <= n; i = i + 6)
if (n % i == 0 ||
n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// To compute x^y under modulo m
static long power(long x, long y, long m){
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,int M){
return fast_pow(n,M-2,M);
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int t, n;
long long s;
struct node {
long long l, r;
} nod[200005];
vector<long long> ve;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%lld", &n, &s);
for (int i = 1; i <= n; ++i) scanf("%lld%lld", &nod[i].l, &nod[i].r);
long long l = 1, r = s, mid, ans;
while (l <= r) {
mid = (l + r) >> 1;
int cntl = 0, cntr = 0;
long long cos = 0;
ve.clear();
for (int i = 1; i <= n; ++i) {
if (nod[i].r < mid)
cos += nod[i].l, ++cntr;
else if (nod[i].l > mid)
cos += nod[i].l, ++cntl;
else
ve.push_back(nod[i].l);
}
if (cntl >= (n + 1) / 2)
ans = mid, l = mid + 1;
else if (cntr > n / 2)
r = mid - 1;
else {
sort(ve.begin(), ve.end());
int k = n / 2 - cntr;
for (int i = 0; i < k; ++i) cos += ve[i];
cos += (ve.size() - k) * mid;
if (cos <= s) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
}
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | def check(mid):
x=[]
y=[]
z=[]
for i in it:
if i[1]<mid:
x.append(i)
elif i[0]>=mid:
y.append(i)
else:
z.append(i)
co=sum([i[0] for i in x])
co+=sum([i[0] for i in y])
ll=len(y)
m=0
#if len(z)==0:
# return False
ne=max(0,(n+1)//2-ll)
if ne>len(z):
return False
j=0
for i in z:
if j<len(z)-ne:
co+=i[0]
else:
co+=mid
j+=1
return co<=s
import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,s=map(int,input().split())
it=[]
for i in range(n):
it.append(list(map(int,input().split())))
it.sort()
l=1
r=max(it,key=lambda x:x[1])[1]+1
while abs(l-r)>=2:
mid=(l+r)//2
st=check(mid)
if st:
l=mid
else:
r=mid
ma=l
for i in range(l,r+1):
st=check(i)
if st:
ma=max(ma,i)
print(ma)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int l[200005], r[200005];
pair<int, int> p[200005];
int main() {
int q;
scanf("%d", &q);
while (q--) {
int n;
long long s;
scanf("%d%lld", &n, &s);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &l[i], &r[i]);
p[i] = pair<int, int>(l[i], r[i]);
}
sort(p + 1, p + 1 + n);
int mid = (n + 1) / 2;
int lo = p[mid].first, hi = 1e9, ans = 0;
while (lo <= hi) {
int mid = (lo + hi) / 2;
int cnt1 = 0, cnt2 = 0;
for (int i = 1; i <= n; i++) {
if (p[i].first <= mid) cnt1++;
}
long long LO = 0;
bool ok = 1;
priority_queue<int> pq;
for (int i = 1; i <= n / 2; i++) {
if (p[i].first > mid) {
LO += p[i].first;
} else {
LO += p[i].first;
if (p[i].second >= mid) {
pq.push(i);
}
}
}
for (int i = n / 2 + 1; i <= n; i++) {
if (p[i].first <= mid && mid <= p[i].second) {
LO += mid;
} else if (p[i].second < mid) {
if (pq.empty()) {
ok = 0;
break;
}
int j = pq.top();
pq.pop();
LO -= p[j].first;
LO += p[i].first;
LO += mid;
} else {
LO += p[i].first;
}
}
if (!ok) {
hi = mid - 1;
continue;
}
if (LO <= s)
ans = mid, lo = mid + 1;
else
hi = mid - 1;
}
printf("%d\n", ans);
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.*;
public class Solution
{
static boolean check(int x , pair[] arr,long s)
{
int cnt = 0;
long req = 0;
for(int i = arr.length-1 ; i >= 0 ; i--)
{
if(x <= arr[i].r && cnt != arr.length/2+1)
{
req += Math.max(arr[i].l,x);
cnt++;
}
else
req += arr[i].l;
}
if(cnt != arr.length/2+1)
return false;
if(req > s)
return false;
return true;
}
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
long s = sc.nextLong();
pair arr[] = new pair[n];
for(int i = 0 ; i < n ; i++)
{
arr[i] = new pair(sc.nextInt() , sc.nextInt());
}
Arrays.sort(arr , new Compare());
int l = 1 , r = 1000000000;
while(l <= r)
{
int mid = (l+r)/2;
if(check(mid,arr,s))
l = mid+1;
else
r = mid-1;
}
System.out.println(r);
}
}
}
class pair
{
int l , r;
public pair(int l , int r)
{
this.l = l;
this.r = r;
}
}
class Compare implements Comparator<pair>
{
public int compare(pair a , pair b)
{
return a.l - b.l;
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t= Integer.parseInt(br.readLine());
for(int i=0;i<t;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long sal = Long.parseLong(st.nextToken());
int[][] range = new int[n][2];
for(int j=0;j<n;j++){
st = new StringTokenizer(br.readLine());
range[j][0] = Integer.parseInt(st.nextToken());
range[j][1] = Integer.parseInt(st.nextToken());
}
Arrays.sort(range,(a,b)->a[0]-b[0]);
findMedian(range,out,sal);
}
out.close();
}
public static void findMedian(int[][] range, PrintWriter out,long sal){
int mid = range.length/2;
int high = -1;
for(int i=0;i<=mid;i++){
sal-=range[i][0];
high = Math.max(range[i][1],high);
}
for(int i=mid+1;i<range.length;i++) sal-=range[i][0];
long val = binarySearch(range,sal,high,mid);
out.println(val);
}
public static long binarySearch(int[][] range,long sal,int high,int i){
int low= range[i][0];
while(low < high){
int mid = (low+high)/2;
if(check(sal,mid,range) > 0) low = mid+1;
else high = mid;
}
low = (check(sal,low,range) >= 0) ? (low) : low-1;
return low;
}
public static long check(long sal,int mid,int[][] range){
int left = 0;
int right = 0;
int max= range.length/2+1;
for(int i=range.length-1;i>=0 && right <= max;i--){
if(range[i][1] < mid) left++;
else if(range[i][0]> mid) right++;
else{
if(right == max)continue;
right++;
sal-=(mid-range[i][0]);
}
}
if(sal < 0 || left>=max || right > max) return -1;
return sal;
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | // created by Whiplash99
import java.io.*;
import java.util.*;
public class D
{
static class Employee
{
long l,r;
Employee(long l, long r)
{
this.l=l;
this.r=r;
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
int T=Integer.parseInt(br.readLine().trim());
StringBuilder sb=new StringBuilder();
PriorityQueue<Long> pq=new PriorityQueue<>();
while(T-->0)
{
String s[]=br.readLine().trim().split(" ");
N=Integer.parseInt(s[0]);
long cash=Long.parseLong(s[1]);
Employee employee[]=new Employee[N];
for(i=0;i<N;i++)
{
s=br.readLine().trim().split(" ");
long l=Long.parseLong(s[0]);
long r=Long.parseLong(s[1]);
employee[i]=new Employee(l,r);
}
Arrays.sort(employee,(Employee x, Employee y)->Long.compare(x.l,y.l));
long l=0,r=0,mid,ans=0;
int target=N/2+1;
l=employee[N/2].l;
Arrays.sort(employee,(Employee x,Employee y)->Long.compare(y.r,x.r));
r=employee[N/2].r;
long left=cash;
for(i=0;i<N;i++)
left-=employee[i].l;
while(l<=r)
{
mid=(l+r)/2;
pq.clear();
for(i=0;i<N;i++)
{
if(employee[i].l>=mid)
pq.add(0L);
else if(employee[i].r>=mid)
pq.add(mid-employee[i].l);
}
int count=0;
long sum=0;
while (count<target&&!pq.isEmpty())
{
count++;
sum+=pq.poll();
}
if(sum<=left&&count==target)
{
ans=mid;
l=(mid+1);
}
else
r=mid-1;
}
sb.append(ans).append("\n");
}
System.out.println(sb);
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> v;
long long n, s;
bool ok(int mid) {
long long sum = 0;
long long cnt = 0;
vector<long long> vec;
for (int i = 0; i < n; i++) {
if (v[i].second < mid)
sum += v[i].first;
else if (v[i].first >= mid) {
sum += v[i].first;
cnt++;
} else {
vec.push_back(v[i].first);
}
}
long long need = max((long long)0, ((n + 1) >> 1) - cnt);
if (vec.size() < need)
return false;
else {
int l = vec.size();
for (int i = 0; i < l - need; i++) {
sum += vec[i];
}
sum += (need * mid);
}
if (sum <= s) return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--) {
cin >> n >> s;
long long l, r;
long long maxi = 0, mini = INT_MAX;
for (int i = 0; i < n; i++) {
cin >> l >> r;
maxi = max(maxi, r);
mini = min(mini, l);
v.push_back(make_pair(l, r));
}
sort(v.begin(), v.end());
long long b = mini, e = maxi, mid;
long long ans = 0;
while (b <= e) {
mid = (b + e) >> 1;
if (ok(mid)) {
b = mid + 1;
ans = mid;
} else
e = mid - 1;
}
cout << ans << endl;
v.clear();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n, s = RL()
arr = [RLL() for _ in range(n)]
mid = n//2+1
def c(num):
now = 0
total = 0
tmp = []
for l, r in arr:
if r<num:
total+=l
elif l>num:
total+=l
now+=1
else:
tmp.append([l, r])
dif = mid-now
tmp.sort(key=lambda a: a[0], reverse=1)
for i in range(len(tmp)):
if i+1<=dif:
total+=num
now+=1
else:
total+=tmp[i][0]
return now>=mid and total<=s
l, r = 0, s
while l<r:
m = (l+r+1)//2
if c(m):
l = m
else:
r = m-1
print(l)
if __name__ == "__main__":
main()
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | // Working program using Reader Class
import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class NumberInput
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node implements Comparable<Node>{
long left;
long right;
Node(long l, long r){
left=l;
right=r;
}
public int compareTo(Node n) {
if(this.left<n.left) {
return -1;
}
else if(this.left>n.left) {
return 1;
}
else {
if(this.right<n.right) {
return -1;
}
else if(this.right>n.right) {
return 1;
}
return 0;
}
}
}
public static void main(String[] args) throws IOException
{
//Reader scan=new Reader();
Reader scan=new Reader();
PrintWriter out=new PrintWriter(System.out);
int test=scan.nextInt();
while(test-->0) {
int n=scan.nextInt();
long s=scan.nextLong();
ArrayList<Node> node=new ArrayList<Node>();
ArrayList<Long> leftValues = new ArrayList<Long>();
ArrayList<Long> rightValues = new ArrayList<Long>();
for(int i=0;i<n;i++) {
long left=scan.nextLong();
long right=scan.nextLong();
leftValues.add(left);
rightValues.add(right);
node.add(new Node(left,right));
}
Collections.sort(node);
Collections.sort(leftValues);
Collections.sort(rightValues);
long min=leftValues.get(n/2);
long max=rightValues.get(n/2);
long possible=min;
while(min<=max) {
long mid=(min+max)/2;
int count=0;
long sum=0;
for(int i=node.size()-1;i>=0;i--) {
if(node.get(i).left>=mid) {
sum+=node.get(i).left;
count++;
}
else {
if(count>n/2) {
sum+=node.get(i).left;
}
else {
if(node.get(i).right>=mid) {
sum+=mid;
count++;
}
else {
sum+=node.get(i).left;
}
}
}
}
if(count>n/2 && sum<=s) {
possible=mid;
min=mid+1;
}
else {
max=mid-1;
}
}
out.println(possible);
}
out.close();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1251d {
public static void main(String[] args) throws IOException {
int t = ri();
while (t --> 0) {
int n = rni();
long s = nl();
int l[] = new int[n], r[] = new int[n], ev[][] = new int[2 * n][];
Set<Integer> compressor = new TreeSet<>();
Map<Integer, Integer> compress = new HashMap<>(), decompress = new HashMap<>();
for (int i = 0; i < n; ++i) {
l[i] = rni();
r[i] = ni();
compressor.add(l[i] - 1);
compressor.add(r[i]);
}
int compress_id = 0;
for (int i : compressor) {
compress.put(i, compress_id);
decompress.put(compress_id++, i);
}
for (int i = 0; i < n; ++i) {
ev[2 * i] = new int[] {compress.get(l[i] - 1), i};
ev[2 * i + 1] = new int[] {compress.get(r[i]), i};
}
sort(ev, (a, b) -> a[0] - b[0]);
int[] lmed = copy(l), rmed = copy(r);
rsort(lmed);
rsort(rmed);
long sum_l = 0;
for (int i = 0; i < n; ++i) {
sum_l += l[i];
}
int ans = lmed[n / 2];
// prln(lmed[n / 2], rmed[n / 2]);
for (int ll = lmed[n / 2], rr = rmed[n / 2]; ll <= rr; ) {
int m = ll + (rr - ll) / 2, seen_seg = 0;
TreeSet<Integer> cur_seg = new TreeSet<>((a, b) -> l[a] == l[b] ? a - b : l[b] - l[a]);
for (int i = 2 * n - 1; i >= 0; --i) {
int[] e = ev[i];
if (decompress.get(e[0]) < m) {
break;
}
if (cur_seg.contains(e[1])) {
cur_seg.remove(e[1]);
++seen_seg;
} else {
cur_seg.add(e[1]);
}
}
long spend = sum_l;
// prln(cur_seg.size(), seen_seg, n - n / 2 - seen_seg);
if (cur_seg.size() < n - n / 2 - seen_seg) {
rr = m - 1;
continue;
}
Iterator<Integer> iter = cur_seg.iterator();
for (int i = 0, end = n - n / 2 - seen_seg; i < end; ++i) {
spend += m - l[iter.next()];
}
if (spend <= s) {
ans = m;
ll = m + 1;
} else {
rr = m - 1;
}
}
prln(ans);
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int)d;}
static int cei(double d) {return (int)ceil(d);}
static long fll(double d) {return (long)d;}
static long cel(double d) {return (long)ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
static void h() {__out.println("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
for (ll i = 0; i < v.size(); ++i) os << v[i] << " ";
return os;
}
template <typename T>
ostream& operator<<(ostream& os, const set<T>& v) {
for (auto it : v) os << it << " ";
return os;
}
template <typename T, typename S>
ostream& operator<<(ostream& os, const pair<T, S>& v) {
os << v.first << " " << v.second;
return os;
}
const ll mod = 1e9 + 7;
const ll inf = 2e18;
const ll ninf = -2e18;
ll takemod(ll a) { return ((a % mod) + mod) % mod; }
ll pow(ll a, ll b, ll m) {
ll ans = 1;
a %= m;
while (b) {
if (b & 1) ans = (ans * a) % m;
b /= 2;
a = (a * a) % m;
}
return ans;
}
ll modinv(ll a) { return takemod(pow(takemod(a), mod - 2, mod)); }
ll n, s;
bool check(ll mid, vector<pair<ll, ll> >& arr) {
vector<pair<ll, ll> > tmp;
ll lt = 0;
ll minc = 0;
for (ll i = 0; i < n; i++) {
if (arr[i].second >= mid)
tmp.push_back(arr[i]);
else {
lt++;
minc += arr[i].first;
}
}
ll req = n / 2;
req++;
sort(tmp.begin(), tmp.end());
ll bound = (ll)tmp.size() - req;
for (ll i = 0; i < bound; i++) {
if (tmp[i].first <= mid) {
lt++;
minc += tmp[i].first;
}
}
for (ll i = bound; i < tmp.size() && i >= 0; i++) {
minc += max(tmp[i].first, mid);
}
if (lt != req - 1 || minc > s) return false;
return true;
}
void solve() {
cin >> n >> s;
vector<pair<ll, ll> > arr(n);
vector<ll> tmp;
for (ll i = 0; i < n; i++) {
ll x, y;
cin >> x >> y;
arr[i] = {x, y};
tmp.push_back(x);
}
sort(tmp.begin(), tmp.end());
ll lo = tmp[n / 2];
ll hi = 1e9;
while (lo <= hi) {
ll mid = (lo + hi) / 2;
if (check(mid, arr)) {
lo = mid + 1;
} else
hi = mid - 1;
}
cout << lo - 1 << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
time_t t1, t2;
t1 = clock();
ll t;
cin >> t;
while (t--) solve();
t2 = clock();
cerr << '\n' << t2 - t1 << '\n';
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.PriorityQueue;
import java.util.AbstractQueue;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.AbstractCollection;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author daltao
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "daltao", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
TaskD solver = new TaskD();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
static class TaskD {
int n;
long s;
int[][] lrs;
PriorityQueue<int[]> qs1 = new PriorityQueue<>(200000, (a, b) -> -(a[0] - b[0]));
PriorityQueue<int[]> qs2 = new PriorityQueue<>(200000, (a, b) -> a[0] - b[0]);
public void solve(int testNumber, FastInput in, FastOutput out) {
n = in.readInt();
s = in.readLong();
lrs = new int[n][2];
for (int i = 0; i < n; i++) {
lrs[i][0] = in.readInt();
lrs[i][1] = in.readInt();
}
int l = 1;
int r = (int) 1e9;
while (l < r) {
int m = (l + r + 1) >> 1;
if (check(m)) {
l = m;
} else {
r = m - 1;
}
}
out.println(l);
}
public boolean check(int m) {
qs1.clear();
qs2.clear();
for (int i = 0; i < n; i++) {
if (lrs[i][1] >= m) {
qs1.add(lrs[i]);
} else {
qs2.add(lrs[i]);
}
}
int half = DigitUtils.ceilDiv(n, 2);
if (qs1.size() < half) {
return false;
}
long total = 0;
for (int i = 0; i < half; i++) {
total += Math.max(m, qs1.remove()[0]);
}
while (!qs1.isEmpty()) {
total += qs1.remove()[0];
}
while (!qs2.isEmpty()) {
total += qs2.remove()[0];
}
return total <= s;
}
}
static class FastInput {
private final InputStream is;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public String next() {
return readString();
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(1 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
static class DigitUtils {
private DigitUtils() {
}
public static int floorDiv(int a, int b) {
return a < 0 ? -ceilDiv(-a, b) : a / b;
}
public static int ceilDiv(int a, int b) {
return a < 0 ? -floorDiv(-a, b) : (a + b - 1) / b;
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
const long long mod = 1e9 + 7;
void chmod(long long &M) {
if (M >= mod)
M %= mod;
else if (M < 0) {
M += (abs(M) / mod + 1) * mod;
M %= mod;
}
}
long long modpow(long long x, long long n) {
if (n == 0) return 1;
long long res = modpow(x, n / 2);
if (n % 2 == 0)
return res * res % mod;
else
return res * res % mod * x % mod;
}
int getl(int i, int N) { return i == 0 ? N - 1 : i - 1; };
int getr(int i, int N) { return i == N - 1 ? 0 : i + 1; };
double argument(const pair<double, double> &a, const pair<double, double> &b) {
double ax = a.first, ay = a.second, bx = b.first, by = b.second;
return atan2(by - ay, bx - ax);
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int half = n / 2;
long long s;
cin >> s;
vector<long long> l(n), r(n);
for (int i = 0; i < n; i++) cin >> l[i] >> r[i];
long long ok = 0, ng = 1e9 + 1;
long long left_cnt, right_cnt, sum, mid;
while (ng - ok > 1) {
sum = 0, left_cnt = 0, right_cnt = 0;
mid = (ok + ng) / 2;
priority_queue<long long> pq;
for (int i = 0; i < n; i++) {
if (mid < l[i]) {
++right_cnt;
sum += l[i];
} else if (mid > r[i]) {
++left_cnt;
sum += l[i];
} else {
pq.push(l[i]);
}
}
if (right_cnt > half) {
ok = mid;
continue;
}
if (left_cnt > half) {
ng = mid;
continue;
}
while (!pq.empty()) {
long long tmp = pq.top();
pq.pop();
if (right_cnt < half + 1) {
++right_cnt;
sum += mid;
} else {
sum += tmp;
}
}
(right_cnt == half + 1 && sum <= s ? ok : ng) = mid;
}
cout << ok << endl;
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const long long INF = mod * mod;
int n;
long long s;
pair<long long, long long> p[200010];
bool check(long long mid) {
sort(p, p + n,
[&mid](const pair<long long, long long> &a,
const pair<long long, long long> &b) {
if (mid <= a.second && mid <= b.second)
return a.first < b.first;
else if (mid <= a.second)
return false;
else if (mid <= b.second)
return true;
else
return a.first < b.first;
});
long long tmp = 0;
for (int((i)) = (0); ((i)) < ((n / 2)); ++((i))) tmp += p[i].first;
for (int(i) = (n / 2); (i) < (n); ++(i)) {
if (p[i].second < mid) return false;
tmp += max(mid, p[i].first);
}
return tmp <= s;
}
int main() {
int q;
scanf("%d", &q);
while (q--) {
scanf("%d%lld", &n, &s);
for (int((i)) = (0); ((i)) < ((n)); ++((i)))
scanf("%lld%lld", &p[i].first, &p[i].second);
long long high = s + 1, low = 0;
while (high - low > 1) {
long long mid = (high + low) / 2;
(check(mid) ? low : high) = mid;
}
printf("%lld\n", low);
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input = sys.stdin.readline
def check(num):
count1=0
count2=0
spent=0
left=[]
for i in l:
if i[0]>num:
count2+=1
spent+=i[0]
elif i[1]<num:
count1+=1
spent+=i[0]
else:
left.append(i)
# if num==36:
# print (num,left,spent,count2,count1)
if count2>n//2+1:
return True
elif count1>n//2:
return False
else:
# print (num,left,spent,count2,count1)
for i in left:
if count2!=n//2+1:
spent+=num
count2+=1
else:
spent+=i[0]
count1+=1
# print (num,left,spent,count2,count1)
if count2==n//2+1 and count1==n//2 and spent<=s:
return True
return False
for nt in range(int(input())):
n,s=map(int,input().split())
l=[]
for i in range(n):
a,b=map(int,input().split())
l.append((a,b))
l.sort(reverse=True)
if n==1:
print (min(l[0][1],s))
continue
low=0
high=10**10
while low<high:
mid=(low+high)//2
if check(mid):
low=mid+1
else:
high=mid-1
if check(low):
print (low)
else:
print (low-1) | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n;
long long s;
vector<array<int, 2>> v(200001);
bool check(int x) {
int cnt = n / 2 + 1;
long long res = 0;
for (int i = n - 1; i > -1 && res <= s; i--) {
if (cnt && v[i][1] >= x) {
res += max(x, v[i][0]);
cnt--;
} else
res += v[i][0];
}
return (res <= s && cnt == 0);
}
void solve() {
cin >> n >> s;
v.resize(n);
for (int i = 0; i < n; i++) cin >> v[i][0] >> v[i][1];
sort(v.begin(), v.end());
int l = 0, r = 1e9 + 5, mid, ans = 1;
while (l <= r) {
mid = (l + r) / 2;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
struct IOSetup {
IOSetup() {
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << fixed << setprecision(20);
cerr << fixed << setprecision(10);
}
} iosetup;
int main() {
int t;
cin >> t;
while (t--) {
int n;
long long s;
cin >> n >> s;
vector<long long> l(n), r(n);
for (int i = (0); i < (n); ++i) cin >> l[i] >> r[i];
vector<pair<int, int> > lr(n);
for (int i = (0); i < (n); ++i) lr[i] = {l[i], r[i]};
sort((lr).begin(), (lr).end());
long long lb = lr[n / 2].first, ub = s + 1;
while (ub - lb > 1) {
long long mid = (lb + ub) / 2;
vector<int> a, c;
vector<pair<long long, long long> > lr;
for (int i = (0); i < (n); ++i) {
if (r[i] < mid) {
a.emplace_back(i);
} else if (mid < l[i]) {
c.emplace_back(i);
} else {
lr.emplace_back(l[i], r[i]);
}
}
if (a.size() >= (n + 1) / 2) {
ub = mid;
continue;
}
long long need = 0;
for (int e : a) need += l[e];
for (int e : c) need += l[e];
sort((lr).begin(), (lr).end());
reverse((lr).begin(), (lr).end());
int nokori = (n + 1) / 2 - c.size();
need += mid * nokori;
for (int i = (nokori); i < (lr.size()); ++i) need += lr[i].first;
(need <= s ? lb : ub) = mid;
}
cout << lb << '\n';
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
bool possible(long long val, long long s, vector<pair<int, int>> &pl, int n) {
long long tot = 0, cnt = (n + 1) / 2;
vector<int> llp;
for (int i = 0; i < n; i++) {
if (pl[i].first >= val) {
tot += pl[i].first;
cnt--;
} else if (pl[i].second < val) {
tot += pl[i].first;
} else {
llp.push_back(pl[i].first);
}
}
if (cnt <= 0) return true;
if (cnt > llp.size()) return false;
sort(llp.begin(), llp.end());
for (int i = 0; i < llp.size() - cnt; i++) {
tot += llp[i];
}
tot += val * cnt;
return tot <= s;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
long long s;
cin >> n >> s;
long long high, low;
vector<pair<int, int>> pl(n);
for (int i = 0; i < n; i++) {
cin >> pl[i].first >> pl[i].second;
}
if (n == 1) {
cout << min(s, (long long)pl[0].second) << endl;
continue;
}
low = 0;
high = s;
while (low + 1 < high) {
long long mid = (low + high) / 2;
if (possible(mid, s, pl, n)) {
low = mid;
} else {
high = mid;
}
}
cout << low << endl;
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long double pi = 3.14159265358979323;
long long mod = 1000000000 + 7;
long long modu = 998244353;
const long double pii = acos(-1.0);
const long long INF = 1e18;
const long long inf = 1e9;
long long power(long long x, long long y) {
long long res = 1;
x = x;
while (y > 0) {
if (y & 1) res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
long long powe(long long x, long long y) {
x = x % mod, y = y % (mod - 1);
long long ans = 1;
while (y > 0) {
if (y & 1) {
ans = (1ll * x * ans) % mod;
}
y >>= 1;
x = (1ll * x * x) % mod;
}
return ans;
}
long long gcd(long long a, long long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
long long lcm(long long a, long long b) { return (a / gcd(a, b) * b); }
bool isPrime(long long n) {
if (n < 2) return false;
for (long long i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
long long ncr(long long n, long long r) {
long long res = 1;
if (r > n) return 0;
if (r > n - r) r = n - r;
for (long long i = 0; i < r; i++) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
long long add(long long a, long long b) { return ((a % mod + b % mod) % mod); }
long long sub(long long a, long long b) {
return ((a % mod - b % mod + mod) % mod);
}
long long mul(long long a, long long b) {
return (((a % mod) * (b % mod)) % mod);
}
long long divi(long long a, long long b) {
return (mul(a, powe(b, mod - 2)) % mod);
}
void fun() {}
const long long N = 2e9 + 7;
void pre() {}
bool ok(long long mid, long long s, std::vector<pair<long long, long long> > v,
long long n) {
long long cnt = 0;
long long avail = s;
for (long long i = 0; i < n; i++) {
if (v[i].second >= mid) cnt++;
}
if (cnt < (n + 1) / 2) return false;
long long ans = 0;
for (long long i = n - 1; i >= 0; i--) {
if (v[i].second >= mid)
avail -= max(v[i].first, mid), ans++, v[i].first = -1;
if (ans == (n + 1) / 2) break;
}
for (long long i = 0; i < n; i++) {
if (v[i].first == -1) continue;
avail -= v[i].first;
}
return (avail >= 0);
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
fun();
pre();
long long tttt = 1;
cin >> tttt;
while (tttt--) {
long long n, s;
cin >> n >> s;
std::vector<pair<long long, long long> > v;
for (long long i = 0; i < n; i++) {
long long l, r;
cin >> l >> r;
v.push_back(make_pair(l, r));
}
if (n == 1) {
cout << min(s, v[0].second) << "\n";
continue;
}
sort(v.begin(), v.end());
long long ans = 0;
long long hi = inf, lo = 0;
while (hi >= lo) {
long long mid = (hi + lo) >> 1;
if (ok(mid, s, v, n))
ans = mid, lo = mid + 1;
else
hi = mid - 1;
}
cout << ans << "\n";
}
cerr << "time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec \n";
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long int N = 5e5 + 5, mod = 1000000007, bit = 60;
bool comp(pair<long long int, long long int> &a,
pair<long long int, long long int> &b) {
if (a.second != b.second) {
return a.second < b.second;
}
return a.first < b.first;
}
bool comp1(pair<long long int, long long int> &a,
pair<long long int, long long int> &b) {
if (a.first != b.first) {
return a.first < b.first;
}
return a.second < b.second;
}
bool check(long long int mid, long long int k,
vector<pair<long long int, long long int> > &p) {
long long int n = p.size(), cost = 0, i, compulsory = 0, need, rem;
vector<pair<long long int, long long int> > v;
for (i = 0; i < n; i++) {
if (p[i].second < mid) {
cost += p[i].first;
} else if (p[i].first >= mid) {
compulsory++;
cost += p[i].first;
} else {
v.push_back({p[i].first, p[i].second});
}
}
need = max(0ll, ((n + 1) >> 1) - compulsory);
if (v.size() < need) {
return 0;
}
rem = v.size() - need;
sort(v.begin(), v.end(), comp1);
reverse(v.begin(), v.end());
while (rem--) {
cost += v.back().first;
if (v.back().first > mid) {
return 0;
}
v.pop_back();
}
while (need--) {
cost += max(mid, v.back().first);
if (v.back().second < mid) {
return 0;
}
v.pop_back();
}
return cost <= k;
}
signed main() {
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
long long int pro = 1, temp, t, i, j, l, r, n, m, mid, z, k, x, y, rem,
carry = 0, ind, ans = 0, mx = -LONG_LONG_MAX,
mn = LONG_LONG_MAX, cnt = 0, curr = 0, prev, next, sum = 0,
flag = 1, i1 = -1, i2 = -1;
cin >> t;
while (t--) {
cin >> n >> k;
vector<pair<long long int, long long int> > p(n);
for (i = 0; i < n; i++) {
cin >> p[i].first >> p[i].second;
}
sort(p.begin(), p.end());
l = p[n / 2].first;
sort(p.begin(), p.end(), comp);
r = p[n / 2].second;
while (l <= r) {
mid = (l + r) >> 1;
if (check(mid, k, p)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
cout << ans << '\n';
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | a=int(input())
ans=[]
import sys
input=sys.stdin.readline
def checker(ans,mid,n,s):
g1=n//2
c1=0
c2=0
c3=0
cost=0
t1=[]
for i in range(len(ans)):
if(ans[i][0]<=mid<=ans[i][1]):
t1.append([ans[i][0],ans[i][1]])
elif(ans[i][1]<mid):
c3+=1
cost+=ans[i][0]
else:
c1+=1
cost+=ans[i][0]
if(c1>g1 or c3>g1):
if(c3>g1):
return 0;
else:
return 2;
else:
left=g1-c3
leftr=g1-c1
for i in range(left):
cost+=t1[i][0]
cost+=(leftr+1)*mid
if(cost<=s):
return 1;
else:
return 0;
import math
for i in range(a):
n,s=map(int,input().split())
ans=[]
mini=math.inf
maxa=0
for i in range(n):
x,y=map(int,input().split())
ans.append([x,y])
mini=min(x,y,mini)
maxa=max(x,y,maxa)
ans.sort()
maxa+=5
value=0
while(mini<maxa):
mid=(mini+maxa)//2
t=checker(ans,mid,n,s)
if(t==0):
maxa=mid
else:
if(t==1):
value=max(value,mid)
mini=mid+1
print(value)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long md = 1e9 + 7;
const long long MX = 2e5 + 5;
const long long INF = 1e18;
const long double PI = 4 * atan((long double)1);
long long power_md(long long a, long long n) {
long long res = 1;
while (n) {
if (n % 2) res = (res % md * a % md) % md;
a = (a % md * a % md) % md;
n /= 2;
}
res %= md;
return res;
}
long long power(long long a, long long n) {
long long res = 1;
while (n) {
if (n % 2) res *= a;
a = a * a;
n /= 2;
}
return res;
}
long long abst(long long a) { return ((a < 0) ? (-1 * a) : (a)); }
class cmp_set {
public:
bool operator()(long long a, long long b) { return a > b; }
};
vector<string> vec_splitter(string s) {
s += ',';
vector<string> res;
while (!s.empty()) {
res.push_back(s.substr(0, s.find(',')));
s = s.substr(s.find(',') + 1);
}
return res;
}
void debug_out(vector<string> __attribute__((unused)) args,
__attribute__((unused)) long long idx,
__attribute__((unused)) long long LINE_NUM) {
cerr << endl;
}
template <typename Head, typename... Tail>
void debug_out(vector<string> args, long long idx, long long LINE_NUM, Head H,
Tail... T) {
if (idx > 0)
cerr << ", ";
else
cerr << "Line(" << LINE_NUM << ") ";
stringstream ss;
ss << H;
cerr << args[idx] << " = " << ss.str();
debug_out(args, idx + 1, LINE_NUM, T...);
}
long long n, s;
vector<pair<long long, long long> > v;
long long fun(long long x) {
long long req = 0;
long long cnt = 0;
for (long long i = v.size() - 1; i >= 0; i--) {
if (cnt == ((n / 2) + 1)) break;
if (v[i].second < x)
continue;
else {
cnt++;
req += max((long long)0, x - v[i].first);
}
}
if (cnt < ((n / 2) + 1)) return 0;
if (req > s) return 0;
return 1;
}
int32_t main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
long long t;
cin >> t;
while (t--) {
v.clear();
cin >> n >> s;
long long sum = 0;
for (long long i = 0; i < n; i++) {
long long l, r;
cin >> l >> r;
v.push_back({l, r});
sum += l;
}
sort(v.begin(), v.end());
s -= sum;
long long lo = v[n / 2].first, hi = 1e9, mid;
while (lo < hi) {
mid = lo + (hi - lo + 1) / 2;
if (fun(mid))
lo = mid;
else
hi = mid - 1;
}
cout << lo << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
static int mod = 1_000_000_007;
static int[] di = {1, 0, 0, -1};
static int[] dj = {0, -1, 1, 0};
static int M = 100005;
public static void main(String[] args) throws IOException {
int t = in.nextInt();
while(t --> 0) {
int n = in.nextInt();
long don = in.nextLong();
Pair[] p = new Pair[n];
for(int i = 0; i < n; ++i) {
int l = in.nextInt();
int r = in.nextInt();
p[i] = new Pair(l, r);
}
Arrays.parallelSort(p);
int lo = 1, hi = (int)1e9;
int ans = -1;
while(lo <= hi) {
int mid = (lo + hi) / 2;
long need = minDon(p, n, mid);
if(don >= need) {
ans = mid;
lo = mid + 1;
}
else {
hi = mid - 1;
}
}
System.out.println(ans);
}
out.close();
}
static long minDon(Pair[] a, int n, int median) {
int leftCnt = 0, rightCnt = 0;
long don = 0;
int m = 0;
for(Pair p : a) {
int l = p.first, r = p.second;
if(r < median) {
leftCnt++;
don += l;
}
else if(l >= median) {
rightCnt++;
don += l;
if(l == median)
m++;
}
}
if(leftCnt > n / 2)
return Long.MAX_VALUE;
if(rightCnt > n / 2)
return Long.MIN_VALUE;
for(Pair p : a) {
int l = p.first, r = p.second;
if(l < median && r >= median) {
if(leftCnt < n / 2) {
leftCnt++;
don += l;
}
else {
rightCnt++;
don += median;
m++;
}
}
}
if(m == 0)
return Long.MIN_VALUE;
return don;
}
static boolean inside(int i, int j, int n, int m) {
return i >= 0 && i < n && j >= 0 && j < m;
}
static long pow(long a, long n, long mod) {
if(n == 0)
return 1;
if(n % 2 == 1)
return a * pow(a, n-1, mod) % mod;
long x = pow(a, n / 2, mod);
return x * x % mod;
}
static class SegmentTree {
int n;
char[] a;
int[] seg;
int DEFAULT_VALUE = 0;
public SegmentTree(char[] a, int n) {
super();
this.a = a;
this.n = n;
seg = new int[n * 4 + 1];
build(1, 0, n-1);
}
private int build(int node, int i, int j) {
if(i == j) {
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
int first = build(node * 2, i, (i+j) / 2);
int second = build(node * 2 + 1, (i+j) / 2 + 1, j);
return seg[node] = combine(first, second);
}
int update(int k, char value) {
return update(1, 0, n-1, k, value);
}
private int update(int node, int i, int j, int k, char value) {
if(k < i || k > j)
return seg[node];
if(i == j && j == k) {
a[k] = value;
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
int m = (i + j) / 2;
int first = update(node * 2, i, m, k, value);
int second = update(node * 2 + 1, m + 1, j, k, value);
return seg[node] = combine(first, second);
}
int query(int l, int r) {
return query(1, 0, n-1, l, r);
}
private int query(int node, int i, int j, int l, int r) {
if(l <= i && j <= r)
return seg[node];
if(j < l || i > r)
return DEFAULT_VALUE;
int m = (i + j) / 2;
int first = query(node * 2, i, m, l, r);
int second = query(node * 2 + 1, m+1, j, l, r);
return combine(first, second);
}
private int combine(int a, int b) {
return a | b;
}
}
static class DisjointSet {
int n;
int[] g;
int[] h;
public DisjointSet(int n) {
super();
this.n = n;
g = new int[n];
h = new int[n];
for(int i = 0; i < n; ++i) {
g[i] = i;
h[i] = 1;
}
}
int find(int x) {
if(g[x] == x)
return x;
return g[x] = find(g[x]);
}
void union(int x, int y) {
x = find(x); y = find(y);
if(x == y)
return;
if(h[x] >= h[y]) {
g[y] = x;
if(h[x] == h[y])
h[x]++;
}
else {
g[x] = y;
}
}
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
// @Override
// public int compareTo(Pair o) {
// return this.first != o.first ? o.first - this.first : o.second - this.second;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long s;
int n;
vector<pair<int, int>> lims;
int solve(int median) {
int smallcnt = 0;
int largecnt = 0;
long long rem = s;
for (int i = 0; i < n; i++)
if (lims[i].second < median) {
smallcnt++;
rem -= lims[i].first;
} else if (lims[i].first > median) {
largecnt++;
rem -= lims[i].first;
}
if (largecnt > n / 2) return -1;
if (smallcnt > n / 2) return 1;
int smallleft = n / 2 - smallcnt;
for (int i = 0; i < n && smallleft > 0; i++)
if (lims[i].first <= median && lims[i].second >= median) {
rem -= lims[i].first;
smallleft--;
}
int stillneed = n - n / 2 - largecnt;
if (1LL * stillneed * median > rem) return 1;
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n >> s;
lims.resize(n);
for (int i = 0; i < n; i++) cin >> lims[i].first >> lims[i].second;
sort(lims.begin(), lims.end());
int low = 1, high = 1000000000;
while (low < high) {
int mid = (low + high) >> 1;
if (mid == low) mid++;
int res = solve(mid);
if (res == 1)
high = mid - 1;
else if (res == -1)
low = mid + 1;
else
low = mid;
}
cout << low << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | def check(x, s, a, n):
num = (n+1) // 2
cur = 0
sum_ = 0
for i in range(n-1, -1, -1):
l, r = a[i]
if cur == num:
break
if l >= x:
cur += 1
elif l <= x and x <= r:
cur += 1
sum_ += x - l
if cur == num and sum_ <= s:
return True
return False
q = int(input())
ans = []
for _ in range(q):
n, s = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
a = sorted(a, key = lambda x: x[0])
s = s - sum([l for l, r in a])
l, u = a[n // 2][0], 1000000000
while u - l > 1:
md = (u+l) // 2
if check(md, s, a, n) == True:
l = md
else:
u = md
ans.append(str(l))
print('\n'.join([x for x in ans]))
#3
#3 26
#10 12
#1 4
#10 11
#1 1337
#1 1000000000
#5 26
#4 4
#2 4
#6 8
#5 6
#2 7 | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
const int INF = 1e9 + 7;
const int MAXN = 3e5 + 20;
const double eps = 1e-9;
const long long inf = 1e18;
const long double pi = acos(-1.0);
using namespace std;
int n;
long long s;
long long a[MAXN], b[MAXN];
long long cnt1, cnt2, pr, l, r, ans, m;
long long sum;
void solve() {
cin >> n >> s;
for (int i = 1; i <= n; i++) cin >> a[i] >> b[i];
l = 0;
r = 1000000001;
pr = n / 2;
while (r - l > 1) {
m = (l + r) / 2;
cnt1 = 0;
cnt2 = 0;
sum = 0;
vector<int> c;
for (int i = 1; i <= n; i++) {
if (b[i] < m) {
cnt1++;
sum += a[i];
} else if (a[i] > m) {
cnt2++;
sum += a[i];
} else
c.push_back(a[i]);
}
if (cnt1 > pr) {
r = m;
continue;
}
if (cnt2 > pr) {
l = m;
continue;
}
sum += (pr - cnt2) * m;
sum += m;
if (sum > s) {
r = m;
continue;
}
sort(c.begin(), c.end());
for (int i = 0; i < pr - cnt1; i++) sum += c[i];
if (sum > s) {
r = m;
continue;
}
l = m;
}
cout << l << endl;
}
int main() {
ios::sync_with_stdio(NULL), cin.tie(0), cout.tie(0);
cout.setf(ios::fixed), cout.precision(20);
int t;
cin >> t;
while (t > 0) {
t--;
solve();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3 * 1e5 + 10;
struct node {
long long l, r;
} a[maxn];
int n;
long long m;
bool cmp(node a, node b) {
if (a.l != b.l) return a.l > b.l;
return a.r > b.r;
}
bool f(long long x) {
int num = 0;
long long sum = 0;
for (int i = 0; i < n; i++) {
if (a[i].r >= x && num < (n + 1) / 2) {
if (a[i].l > x)
sum += a[i].l;
else
sum += x;
num++;
} else {
sum += a[i].l;
}
}
if (num < ((n + 1) / 2)) return false;
if (sum > m) return false;
return true;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
scanf("%lld", &m);
long long maxm = 0;
for (int i = 0; i < n; i++) {
scanf("%lld%lld", &a[i].l, &a[i].r);
if (a[i].r > maxm) maxm = a[i].r;
}
sort(a, a + n, cmp);
long long x = a[n / 2].l, y = maxm + 10;
long long mid;
long long maxx = a[n / 2].l;
if (f(x)) {
if (x > maxx) maxx = x;
}
if (f(y)) {
if (y > maxx) maxx = y;
}
while (y - x > 1) {
mid = x + (y - x) / 2;
if (f(mid)) {
if (mid > maxx) maxx = mid;
x = mid;
} else
y = mid;
}
printf("%lld\n", maxx);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
long long tot;
int n;
pair<int, int> a[maxn];
bool judge(int mid) {
long long sum = 0;
int cnt = 0;
vector<int> v;
for (int i = 0; i < n; i++) {
if (a[i].second < mid)
sum += a[i].first;
else if (a[i].first >= mid) {
sum += a[i].first;
cnt++;
} else
v.push_back(a[i].first);
}
sort(v.begin(), v.end());
cnt = max(0, (n + 1) / 2 - cnt);
if (cnt > v.size()) return 0;
for (int i = 0; i < v.size(); i++) {
if (i < v.size() - cnt)
sum += v[i];
else
sum += mid;
}
return sum <= tot;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d%lld", &n, &tot);
for (int i = 0; i < n; i++) {
scanf("%d%d", &a[i].first, &a[i].second);
}
sort(a, a + n);
int l = 1, r = 1e9 + 10;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (judge(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
printf("%d\n", l);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
def bisearch_max(mn, mx, func):
ok = mn
ng = mx
while ok+1 < ng:
mid = (ok+ng) // 2
if func(mid):
ok = mid
else:
ng = mid
return ok
def check(m):
midcnt = N//2 + 1
A1, A2, A3 = [], [], []
cnt = k = 0
for l, r in LR:
if r < m:
A1.append((l, r))
k += l
elif m <= l:
A2.append((l ,r))
cnt += 1
k += l
else:
A3.append((l, r))
k += l
if k > K:
return False
if cnt+len(A3) < midcnt:
return False
if cnt >= midcnt and k <= K:
return True
A3.sort(reverse=True)
for l, r in A3:
cnt += 1
k += m - l
if k > K:
return False
if cnt >= midcnt and k <= K:
return True
return False
for _ in range(INT()):
N, K = MAP()
LR = []
for i in range(N):
l, r = MAP()
LR.append((l, r))
res = bisearch_max(0, 10**9+1, check)
print(res)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC)throws Exception{
int n = ni();
long s = nl();
Person[] a = new Person[n];
for(int i = 0; i< n; i++){
a[i] = new Person(nl(), nl());
s -= a[i].l;
}
long lo = 0, hi = (long)1e12;
ar = new Long[n];
while(lo+1 < hi){
long mid = lo+(hi-lo)/2;
if(check(a, s, mid))lo = mid;
else hi = mid;
}
if(check(a, s, hi))lo = hi;
pn(lo);
}
Long[] ar;
boolean check(Person[] a, long s, long med){
int c = 0, sz = 0;
for(Person p:a){
if(p.r < med)continue;
if(p.l >= med)c++;
else{
ar[sz++] = med-p.l;
}
}
Arrays.sort(ar, 0, sz);
for(int i = 0; i< sz; i++){
if(s-ar[i] >= 0){
s -= ar[i];
c++;
}
}
return c >= (a.length+1)/2;
}
class Person{
long l, r, cur;
public Person(long l, long r){
this.l = l;
this.r = r;
cur = this.l;
}
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
long IINF = (long)1e18, mod = (long)1e9+7;
final int INF = (int)1e9, MX = (int)2e6+5;
DecimalFormat df = new DecimalFormat("0.0000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-7;
static boolean multipleTC = true, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
if(fileIO){
in = new FastReader("C:/users/user/desktop/inp.in");
out = new PrintWriter("C:/users/user/desktop/out.out");
}else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = (multipleTC)?ni():1;
pre();
for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct node {
long long int l, r;
} inp[200010];
long long n, s;
bool cmp(node a, node b) { return a.l > b.l; }
bool check(long long int m) {
long long int sum = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
sum += inp[i].l;
}
for (int i = 0; i < n; i++) {
if (inp[i].r >= m) {
sum += max(m - inp[i].l, 1ll * 0);
cnt++;
}
if (cnt == (n + 1) / 2) {
break;
}
}
if (cnt == (n + 1) / 2 && sum <= s) {
return true;
} else {
return false;
}
}
int main() {
int t;
cin >> t;
while (t--) {
cin >> n >> s;
for (int i = 0; i < n; i++) {
cin >> inp[i].l >> inp[i].r;
}
long long int l = 0, r = s, ans;
sort(inp, inp + n, cmp);
while (l <= r) {
long long int mid = (l + r) / 2;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
cout << ans << endl;
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int q, n;
long long s;
class emp {
public:
long long l, r;
emp() {}
emp(long long l, long long r) : l(l), r(r) {}
bool operator<(const emp& other) const {
if (l != other.l) return l < other.l;
return r < other.r;
}
};
emp E[200010];
bool f(long long med) {
int l = 0, g = 0, e = 0;
long long sum = 0;
for (int i = 0; i < n; i++) {
if (E[i].r < med) {
l++;
sum += E[i].l;
}
if (E[i].l > med) {
g++;
sum += E[i].l;
}
}
if (l > n / 2 || g > n / 2 + 1) return false;
for (int i = 0; i < n; i++) {
if (E[i].l <= med && med <= E[i].r) {
if (l < n / 2)
sum += E[i].l, l++;
else
sum += med, g++;
}
}
if (l != n / 2 || g != n / 2 + 1) return false;
return sum <= s;
}
int main() {
scanf("%d", &q);
while (q--) {
scanf("%d %lld", &n, &s);
for (int i = 0; i < n; i++) scanf("%lld %lld", &E[i].l, &E[i].r);
sort(E, E + n);
long long lo = E[n / 2].l, hi = s, mid;
while (lo <= hi) {
mid = (lo + hi) / 2;
if (f(mid))
lo = mid + 1;
else
hi = mid - 1;
}
printf("%lld\n", hi);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
import operator
input = sys.stdin.buffer.readline
def f(med):
total = 0
cnt = 0
for x in salaries:
# print(x)
if x[1] < med:
total += x[0] # useless so pay min salaray
else:
if cnt < n/2:
total += max(x[0],med)
cnt+=1
else:
total+= x[0]
# print(total)
# print(med,total)
if total > s or cnt< n/2:
return False
return True
q = int(input())
for _ in range(q):
salaries = []
minl = 999999999999999
maxl = -1
n, s = map(int, input().split())
for __ in range(n):
l, r = map(int, input().split())
if l<minl:
minl = l
if r > maxl:
maxl = r
salaries.append((l, r))
salaries.sort(reverse=True)
# print(salaries)
# for i in range(10):
# print(f"i:{i} f:f{f(i)}")
# binary search
a= minl
b = maxl
while b>=a:
m=(a+b)//2
##
##
if f(m):
a=m+1
else:
b=m-1
# print("ANS")
print(b)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. 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:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
long sum=sc.nextLong();
Pair a[]=new Pair[n];
for( int i=0;i<n;i++)
{
a[i]=new Pair(sc.nextLong(),sc.nextLong());
}
Arrays.sort(a, new myComparator());
/**for( int i=0;i<n;i++)
{
System.out.println(a[i].x+" "+a[i].y);
}*/
long low=0;
long high=1000000007;
long mid=0;
while(low<high)
{
mid=(low+high+1)/2;
//System.out.println(mid);
if(possible(mid,a,sum))
{
low=mid;
}
else
{
high=mid-1;
}
}
System.out.println(low);
}
}
public static boolean possible(long val,Pair a[],long S)
{
int n=a.length;long sum=0;int cnt=(n+1)/2;
for( int i=0;i<n;i++)
{
sum+=a[i].x;
}
int count=0;int f=0;
for( int i=n-1;i>=0;i--)
{
if(a[i].x>val)
{
count++;
}
if(count==cnt)
{
f=1;break;
}
if(val>=a[i].x&&val<=a[i].y)
{
count++;
sum+=Math.max(val-a[i].x,0);
}
if(count==cnt)
{
f=1;break;
}
}
if(f==1&&sum<=S)
return true;
else return false;
}
}
class myComparator implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
if(Long.compare(a.x,b.x)!=0)
return (int)Long.compare(a.x,b.x);
else
return (int)Long.compare(a.y,b.y);
}
}
class Pair
{
long x, y;
Pair(long x, long y)
{
this.x=x;
this.y=y;
}
}
| JAVA |
Subsets and Splits