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
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; set<long long> S; void go(const long long &x, const int &M, const long long &U) { if (x > U) return; if (x > M) S.insert(x); go(10 * x + 4, M, U), go(10 * x + 7, M, U); } bool ok(long long x) { for (; x; x /= 10) { int a = x % 10; if (a != 4 && a != 7) return false; } return true; } int main() { long long N, K; cin >> N >> K; long long F = -1; int M = 1; for (long long f = 1; f * M < K; f *= M, M++) ; if (M > (int)N) { cout << -1 << endl; return 0; } M = min((int)N, 20); go(0, 0, N - M); vector<long long> a(M); for (int _n(M), i(0); i < _n; i++) a[i] = N - M + i + 1; if (K < F || F == -1) { for (long long k = K - 1; k > 0;) { long long f = 1; int i = 1; while (f * (i + 1) <= k) f *= ++i; int j = k / f; swap(a[M - i - 1], a[M - i + j - 1]); sort(&a[0] + M - i, &a[0] + M); k -= f * j; } } else if (K == F) { reverse((a).begin(), (a).end()); } int ans = 0; for (int _n(M), i(0); i < _n; i++) if (ok(N - M + i + 1) && ok(a[i])) ans++; ans += S.size(); cout << ans << endl; return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
debug = False import sys, math def out(): FIN.close() FOUT.close() sys.exit() def num(ind): i = 0 k = ind while k > 0: i += 1 if not f[i]: k -= 1 return i def nextlucky(x): s = str(x) lens = len(s) for i in range(lens - 1, -1, -1): if s[i] == '4': res = s[:i] + '7' + '4' * (lens - i - 1) return int(res) return int('4' * (lens + 1)) if debug: FIN = open('input.txt', 'r') FOUT = open('output.txt', 'w') else: FIN = sys.stdin FOUT = sys.stdout n, k = map(int, FIN.readline().split()) fact = [0] * 14 fact[0] = 1 for i in range(1, 14): fact[i] = fact[i - 1] * i if n < 14 and fact[n] < k: FOUT.write('-1') out() a = [0] * 14 p = [0] * 14 f = [False] * 14 for i in range(1, 14): a[i] = n - 13 + i ind = 0 for i in range(1, 14): j = 1 while ind < k: j += 1 ind += fact[13 - i] ind -= fact[13 - i] j -= 1 p[i] = num(j) f[p[i]] = True lucky = [0] * 2000 lucky[0] = 4 count = 0 while lucky[count] <= n: count += 1 lucky[count] = nextlucky(lucky[count - 1]) ans = 0 ind = count for i in range(count): if lucky[i] < n - 12: ans += 1 else: # ind = i break for i in range(1, 14): if (i + n - 13) > 0 and (a[p[i]] > 0): if ((i + n - 13) in lucky) and ((a[p[i]]) in lucky): ans += 1 FOUT.write(str(ans)) out()
PYTHON
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int inf = 1000000005; long long int llinf = 2000000000000000005LL; long long int mod = 1000000007; long long int mod9 = 1000000009; double pi = 3.1415926535897; double eps = 1e-15; int dx[] = {1, -1, 0, 0, 1, -1, 1, -1}, dy[] = {0, 0, 1, -1, 1, 1, -1, -1}; vector<bool> isprime; vector<int> primes; void seive(int n, bool wantlist = true) { isprime.resize(n + 1, true); isprime[0] = isprime[1] = false; int sq = sqrt(n + 1); for (int i = 2; i < sq + 1; i++) { if (isprime[i]) { for (int j = i * i; j <= n; j += i) isprime[j] = false; } } for (int i = 2; wantlist && i <= n; i++) { if (isprime[i]) primes.push_back(i); } } template <class T> inline T gcd(T a, T b) { while (b > 0) { a %= b; swap(a, b); } return a; } template <class T> inline T lcm(T a, T b) { return a * b / gcd(a, b); } template <class T> inline vector<T> operator+(vector<T>& a, vector<T>& b) { assert(a.size() == b.size()); int n = a.size(); vector<T> c(n); for (int i = 0; i < n; i++) c[i] = a[i] + b[i]; return c; } int fastMax(int x, int y) { return (((y - x) >> (32 - 1)) & (x ^ y)) ^ y; } inline long long int bexp(long long int x, long long int n, long long int m = mod) { long long int res = 1; x %= m; while (n) { if (n & 1) res = res * x % m; x = x * x % m; n >>= 1; } return res; } inline bool ispalin(string& str) { int n = str.length(); for (int i = 0; i < n / 2; i++) if (str[i] != str[n - i - 1]) return false; return true; } bool lucky(int n) { bool ans = true; while (n > 0) { ans = ans && (n % 10 == 4 || n % 10 == 7); n /= 10; } return ans; } int main() { int n, k; cin >> n >> k; k--; if (n <= 14) { long long int n1 = 1; for (int i = 1; i < n + 1; i++) n1 *= i; if (n1 < k + 1) { cout << -1 << endl; return 0; } } vector<int> rep; for (int i = 1; i < 50 && k > 0; i++) { rep.push_back(k % i); k /= i; } reverse(rep.begin(), rep.end()); vector<int> a(rep.size()); for (int i = 0; i < rep.size(); i++) a[i] = i + 1 + (n - rep.size()); int cnt = 0; for (int i = 0; i < rep.size(); i++) { int pos = n - rep.size() + i + 1; if (lucky(pos) && lucky(a[rep[i]])) cnt++; a.erase(a.begin() + rep[i]); } vector<long long int> luc; for (int x = 2; x < 2048; x++) { long long int num = 0, msk = x, mul = 1; while (msk > 1) { if (msk & 1) num += 7L * mul; else num += 4L * mul; msk >>= 1; mul *= 10L; } luc.push_back(num); } int i = 0; while (luc[i++] <= n - rep.size()) cnt++; cout << cnt << endl; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Queue; import java.util.Collection; import java.io.InputStream; import java.util.Vector; /** * Built using CHelper plug-in * Actual solution is at the top * @author bkand1908 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, Scanner in, PrintWriter out) { int count = in.nextInt(); int index = in.nextInt() - 1; int tail = -1; for (int i = 0; i <= count; ++i) if (factorial(i) > index) { tail = i; break; } if (tail == -1) { out.println(-1); return; } long[] lucky = generateLucky(); int ans = Arrays.binarySearch(lucky, count - tail); if (ans < 0) ans = -ans - 1; else ++ans; boolean[] taken = new boolean[tail]; int start = count - tail + 1; for (int i = 0; i < tail; ++i) { long fact = factorial(tail - i - 1); for (int j = 0; j < tail; ++j) if (!taken[j]) { if (fact > index) { taken[j] = true; if (Arrays.binarySearch(lucky, start + i) >= 0 && Arrays.binarySearch(lucky, start + j) >= 0) ++ans; break; } else index -= fact; } } out.println(ans); } private long factorial(int n) { long res = 1; for (long i = 2; i <= n; ++i) res *= i; return res; } private long[] generateLucky() { Vector<Long> lucky = new Vector<Long>(); Queue<Long> q = new LinkedList<Long>(); q.add(4l); q.add(7l); while (!q.isEmpty()) { long value = q.remove(); if (value >= 1000000000) continue; lucky.add(value); q.add(value * 10 + 4); q.add(value * 10 + 7); } long[] ans = new long[lucky.size()]; for (int i = 0; i < ans.length; ++i) ans[i] = lucky.elementAt(i); return ans; } }
JAVA
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int N, K; vector<int> lucky; void gen(long long N, long long v) { if (v > N) { return; } if (v != 0) { lucky.push_back((int)v); } gen(N, 10 * v + 4); gen(N, 10 * v + 7); } vector<int> fact; vector<int> a; set<int> s; void gen2(int K, int index) { if (index < 0) return; int v = K / fact[index]; set<int>::iterator it = s.begin(); advance(it, v); a.push_back(*it); s.erase(it); gen2(K - v * fact[index], index - 1); } int main() { scanf("%d%d", &N, &K); K--; fact.push_back(1); for (int i = 1;; i++) { long long v = (long long)fact.back() * i; if (v > (long long)K) { break; } fact.push_back((int)v); } for (int i = 0; i < (int)((fact).size()); i++) { s.insert(i); } gen2(K, (int)((fact).size()) - 1); if (N < (int)((a).size())) { puts("-1"); return 0; } for (int i = 0; i < (int)((a).size()); i++) { a[i] += (1 + N - (int)((a).size())); } gen(N, 0); sort(lucky.begin(), lucky.end()); int cnt = 0; for (int i = 0; i < (int)((lucky).size()); i++) { int index = lucky[i]; if (index > N - (int)((a).size())) { index = a[index - (N - (int)((a).size())) - 1]; } if (binary_search(lucky.begin(), lucky.end(), index)) { cnt++; } } printf("%d\n", cnt); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> int mul[14]; int Lucky[1025], tot; void pre() { mul[0] = 1; for (int i = 1; i < 14; i++) mul[i] = mul[i - 1] * i; for (int bit = 1; bit < 10; bit++) { for (int i = 0; i < 1 << bit; i++) { int num = 0; for (int j = bit - 1; j >= 0; j--) { if (i >> j & 1) num = num * 10 + 7; else num = num * 10 + 4; } Lucky[tot++] = num; } } } int Cantor(int *num, int ans, int n) { int flag[14] = {0}; ans--; if (n > 13) n = 13; for (int i = 1; i <= n; i++) { int k = ans / mul[n - i], j; ans %= mul[n - i]; for (j = 1; j <= n; j++) { if (!flag[j]) k--; if (k < 0) break; } if (k >= 0) return -1; num[i] = j; flag[j] = 1; } return 0; } bool jg(int x) { while (x) { if (x % 10 != 4 && x % 10 != 7) return false; x /= 10; } return true; } int main() { pre(); int N, K; scanf("%d%d", &N, &K); int num[14]; int ans = Cantor(num, K, N); if (ans == -1) return puts("-1"), 0; if (N <= 13) { for (int i = 1; i <= N; i++) if (jg(num[i]) && jg(i)) ans++; } else { int Base = N - 13; for (int i = N - 12, j = 1; i <= N; i++, j++) { if (jg(i) && jg(num[j] + Base)) ans++; } int k = std::lower_bound(Lucky, Lucky + tot, N - 13) - Lucky; ans += k; if (jg(N - 13)) ans++; } printf("%d\n", ans); return 0; }
CPP
122_E. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
2
11
#include <bits/stdc++.h> using namespace std; int n, k, c; long long factN = 1; int a[20], tk[20]; int lck[100000], reach = 0; void DFS(long long x) { if (x > 1000000000) { return; } lck[reach++] = x; DFS(x * 10 + 4); DFS(x * 10 + 7); } bool lucky(long long x) { do { int cur = x % 10; if (cur != 4 && cur != 7) { return 0; } x /= 10; } while (x != 0); return 1; } int main() { cin >> n >> k; int cur = 2; while (cur <= n && factN <= k) { factN *= cur; cur++; } if (factN < k) { cout << "-1\n"; return 0; } c = min(13, n); cur = 2; factN = 1; for (cur = 2; cur <= c; cur++) { factN *= cur; } for (int i = 0; i < c; i++) { factN /= (c - i); int wht = (k - 1) / factN + 1; int j = 1; for (int hmany = 0; j <= c && hmany < wht; j++) { if (tk[j] == 0) { hmany++; } } j--; a[i] = j; tk[j] = 1; k -= (wht - 1) * factN; } long long ans = 0; for (int i = 0; i < c; i++) { int ss = a[i] + max(n - 13, 0); if (lucky(ss)) { if (lucky(i + 1 + max(n - 13, 0))) { ans++; } } } if (n > 12) { DFS(4); DFS(7); sort(lck, lck + reach); ans += (upper_bound(lck, lck + reach, n - 13) - lck); } 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.io.*; import java.util.*; import java.math.*; public class p1251D { public class Emp implements Comparable<Emp>{ public long l; public long r; public long s; public Emp (long l, long r, long s) { this.l = l; this.r = r; this.s = s; } public int compareTo(Emp e) { if(this.l < e.l) { return 1; } else if(this.l == e.l) { return 0; } else { return -1; } } public String toString() { return (l + "\t" + r); } } public void realMain() throws Exception { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000); String in = fin.readLine(); String[] ar = in.split(" "); int T = Integer.parseInt(ar[0]); ArrayList<Emp> emps = new ArrayList<Emp>(); for(int t = 0; t < T; t++) { emps.clear(); long ret2 = 0; boolean dig2 = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig2 = true; ret2 = ret2 * 10 + ch - '0'; } else if (dig2) break; } int n = (int)ret2; ret2 = 0; dig2 = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig2 = true; ret2 = ret2 * 10 + ch - '0'; } else if (dig2) break; } long s = ret2; long curs = 0; for(int i = 0; i < n; i++) { int ret = 0; boolean dig = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig = true; ret = ret * 10 + ch - '0'; } else if (dig) break; } int l = ret; ret = 0; dig = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig = true; ret = ret * 10 + ch - '0'; } else if (dig) break; } int r = ret; Emp emp = new Emp(l, r, l); emps.add(emp); curs += l; } Collections.sort(emps); //System.out.println(emps.toString()); long sprime = s - curs; //System.out.println(s + " " + curs + " " + sprime); long low = 0; long high = 1000000001; long best = 0; while(low <= high) { long mid = (low + high) / 2; //System.out.println("trying: " + mid); int count = 0; int i = 0; long moreneeded = 0; while(count < (n / 2) + 1 && i < n) { if(emps.get(i).r >= mid) { count++; moreneeded += Math.max(0, mid - emps.get(i).l); } i++; } //System.out.println(count + " " + moreneeded); boolean works = true; if(count < (n / 2) + 1) { works = false; } if(moreneeded > sprime) { works = false; } if(works) { best = Math.max(best, mid); //System.out.println("new best: " + best); low = mid + 1; } else { high = mid - 1; } } System.out.println(best); } } public static void main(String[] args) throws Exception { p1251D a = new p1251D(); a.realMain(); } }
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 cas, n; pair<long long, long long> a[maxn]; long long k; bool chk(long long mid) { long long tmp = 0; int pos = n / 2 + 1; for (int i = 1; i <= n; i++) { if (a[i].second >= mid && pos) { tmp += max(mid, a[i].first); pos--; } else tmp += a[i].first; } return tmp <= k && !pos; } int main() { cin >> cas; while (cas--) { cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> a[i].first >> a[i].second; } sort(a + 1, a + 1 + n, greater<pair<long long, long long> >{}); long long l = 0, r = 1e9 + 1; while (l < r) { long long mid = l + r + 1 >> 1; if (chk(mid)) l = mid; else r = mid - 1; } cout << l << 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.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class Solution implements Runnable{ static class pair implements Comparable { int f; int s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o)//ascending order { pair pr=(pair)o; if(s>pr.s) return 1; if(s==pr.s) { if(f>pr.f) return 1; else return -1; } else return -1; } public boolean equals(Object o) { pair ob=(pair)o; if(o!=null) { if((ob.f==this.f)&&(ob.s==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f; int s; double t; triplet(int f,int s,double t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; double tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o)//ascending order { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } int n; long sum; ArrayList<pair>al; int solve(long mid) { long cost=0; PriorityQueue<Integer>pq=new PriorityQueue<>(); int n1=0,n2=0; for(pair p : al) { if(p.s<mid) { cost+=p.f; n1++; } else if(p.f>mid) { cost+=p.f; n2++; } else pq.add(p.f); } if(n1>n/2) return -1; while(n1++ < n/2) { cost+=pq.remove(); } cost+=mid; cost+=(n/2-n2)*mid; if(cost<=sum) return 1; else return -1; } public static void main(String args[])throws Exception { new Thread(null,new Solution(),"Solution",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t=in.ni(); while(t--!=0) { al=new ArrayList<>(); n=in.ni(); sum=in.nl(); PriorityQueue<Integer>pq=new PriorityQueue<>(); for(int i=1;i<=n;i++) { int x=in.ni(); int y=in.ni(); pq.add(x); al.add(new pair(x,y)); } int pp=1; while(pp++<=n/2) pq.remove(); long l=pq.remove(),r=1000000000,ans=-1; while(l<=r) { long mid=(l+r)/2; //System.out.println(mid); int n1=0,n2=0,min=2000000000,max=0; for(pair p : al) { if(p.s < mid) { max=Math.max(max,p.s); n1++; } if(p.f > mid) { min=Math.min(min,p.f); n2++; } } if(n1+n2==n) { int k=solve(min); if(k==-1) r=mid-1; else { l = max; ans=min; } } else { int k=solve(mid); if(k==-1) r=mid-1; else { l = mid + 1; ans=mid; } } } out.println(ans); } out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } 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 ni() { 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 nl() { 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] = ni(); } 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> const long long inf = (long long)1e18 + 7; const long long Mod = (long long)998244353; using namespace std; long long modexpo(long long a, long long b) { long long ret = 1; while (b) { if (b & 1) { ret = (ret * a) % Mod; } a = (a * a) % Mod; b >>= 1; } return ret; } bool solve(vector<pair<long long, long long> > v, long long med, long long s, long long n) { long long cnt = 0, i; for (i = 0; i < n; i++) { if (v[i].first >= med) { cnt++; if (cnt > n / 2) return true; } else if (v[i].first < med && v[i].second >= med) { s -= (med - v[i].first); if (s < 0) return false; cnt++; if (cnt > n / 2) return true; } } return false; } bool cmp(pair<long long, long long> a, pair<long long, long long> b) { if (a.first == b.first) { return a.second > b.second; } return a.first > b.first; } int main() { long long t; cin >> t; while (t--) { long long s, i, n, ans = inf, mini = inf, maxi = 0; cin >> n >> s; long long arr[n + 2], l[n + 2], r[n + 2]; vector<pair<long long, long long> > v; for (i = 0; i < n; i++) { cin >> l[i] >> r[i]; v.push_back({l[i], r[i]}); s -= l[i]; mini = min(mini, l[i]); maxi = max(maxi, r[i]); } sort(v.begin(), v.end(), cmp); long long lo = mini, hi = maxi; while (lo <= hi) { long long mid = (lo + hi) / 2; if (solve(v, mid, s, n)) { ans = mid; lo = mid + 1; } else { hi = 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
import sys from bisect import bisect_left # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ t = int(input()) for _ in range(t): n, s = map(int, input().split()) mid = n >> 1 rl = [] for i in range(n): li, ri = map(int, input().split()) rl.append((ri, li)) rl.sort() leftSum = [0] currSum = 0 for i in range(n >> 1): currSum += rl[i][1] leftSum.append(currSum) L = 1 R = 10 ** 9 + 1 while L + 1 < R: median = (L + R) >> 1 st = bisect_left(rl, (median, 0)) if st > mid: R = median continue cost = leftSum[st] ls = [] for i in range(st, n): ls.append(rl[i][1]) ls.sort() if ls[-mid-1] > median: L = median continue for i in range(mid + 1): cost += max(median, ls[-i-1]) for i in range(mid + 1, n - st): cost += ls[-i-1] if cost <= s: L = median else: R = median print(L) # inf.close()
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 int inf = 9e18; const long double pi = 2 * acos(0.0); long long int tes, n, s; vector<pair<long long int, long long int>> arr; long long int power(long long int x, long long int y) { long long int res = 1ll; while (y > 0) { if (y & 1) res = res * x; y >>= 1; x = x * x; } return res; } bool calc(long long int med) { long long int sum = 0, tar = (n + 1) / 2; vector<long long int> temp(n, -1), temp2; ; for (int i = 0; i < n; i++) { if (med > arr[i].first && med <= arr[i].second) temp[i] = 1; else if (arr[i].second < med) temp[i] = 2; else temp[i] = 3; }; for (int i = 0; i < n; i++) { if (temp[i] == 2) sum += arr[i].first; else if (temp[i] == 3) sum += arr[i].first, tar--; else temp2.push_back(arr[i].first); } long long int n1 = (int)((temp2).size()); sort(temp2.begin(), temp2.end()); ; for (int i = n1 - 1; i > -1; i--) { if (tar > 0) sum += med, tar--; else sum += temp2[i]; } if (tar > 0 || sum > s) return false; else return true; } void solve() { arr.clear(); cin >> n >> s; arr.resize(n); ; for (int i = 0; i < n; i++) cin >> arr[i].first >> arr[i].second; long long int l = 0, r = s + 1; while (r > l + 1) { long long int mid = (l + r) / 2; if (calc(mid)) l = mid; else r = mid; } cout << l << "\n"; } int32_t main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; cin >> tes; while (tes--) { 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 input1 = sys.stdin.readline def solve(): n, s = [int(i) for i in input1().split()] empl = [] for i in range(n): empl.append([int(j) for j in input1().split()]) empl.sort(reverse = True) lg = 0 rg = 10 ** 9 + 1 while rg - lg > 1: mg = (rg + lg) // 2 need = (n + 1) // 2 money = s for i in range(n): li = empl[i][0] ri = empl[i][1] if ri >= mg and need > 0: money -= max(mg, li) need -= 1 else: money -= li if need == 0 and money >= 0: check = True else: check = False if check: lg = mg else: rg = mg print(lg) t = int(input1()) while t > 0: empl = [] solve() t -= 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; const int N = 2e5 + 5; struct node { int l, r; } a[N]; bool operator<(const node& a, const node& b) { return a.l > b.l; } long long n, s; bool check(long long x) { long long i = 0, k = 0, sum = 0; while (k < n / 2 + 1) { i++; if (i > n) break; if (a[i].r < x) continue; else { k++; sum += max(0ll, x - a[i].l); } } if (k != n / 2 + 1) return 0; else return sum <= s; } int main() { int T; cin >> T; while (T--) { cin >> n >> s; for (int i = 1; i <= n; i++) { cin >> a[i].l >> a[i].r; s -= a[i].l; } sort(a + 1, a + n + 1); long long l = 1, r = 1e9; while (l <= r) { long long mid = (l + r) / 2; if (check(mid)) l = mid + 1; else r = mid - 1; } cout << r << 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
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.sort(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; } } 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; template <class T> int read(T& x) { int c = getchar(), f = (x = 0); while (~c && (c < 48 || c > 57)) { if (c == '-') { f = 1; } c = getchar(); } if (!~c) { return 0; } while (c > 47 && c < 58) { x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); } if (f) { x = -x; } return 1; } template <class T, class U> inline int read(T& a, U& b) { return read(a) && read(b); } template <class T, class U, class V> inline int read(T& a, U& b, V& c) { return read(a) && read(b) && read(c); } inline int read(double& _, double& __) { return scanf("%lf%lf", &_, &__); } inline int read(char* _) { return scanf("%s", _); } inline int read(double& _) { return scanf("%lf", &_); } inline void print(long long _) { printf("%lld ", _); } inline void print(int _) { printf("%d ", _); } inline void println(long long _) { printf("%lld\n", _); } inline void println(int _) { printf("%d\n", _); } template <class T> inline void cmax(T& _, T __) { if (_ < __) _ = __; } template <class T> inline void cmin(T& _, T __) { if (_ > __) _ = __; } const int maxn = 2e5 + 10, INF = 0x3f3f3f3f; const long long LINF = (long long)INF << 32 | INF; long long mid; struct Node { long long L, R; Node(long long a = 0, long long b = 0) : L(a), R(b) {} bool operator<(const Node& T) const { return L > T.L; } } a[maxn]; long long T, n, tot, L = 0, R = INF, x; bool Judge() { int cnt = 0; long long tmp = tot; for (int i = 1; i <= (n); i++) { if (a[i].L >= mid) { ++cnt; continue; } if (a[i].R < mid) continue; if (tmp < mid - a[i].L) break; tmp -= mid - a[i].L; if (++cnt >= x) return true; } return cnt >= x; } int main() { int T; read(T); while (T--) { read(n, tot); L = 0, R = tot, x = (n + 1) / 2; for (int i = 1; i <= (n); i++) { read(a[i].L, a[i].R); tot -= a[i].L; } sort(a + 1, a + n + 1); while (L < R) { mid = L + (R - L + 1) / 2; if (Judge()) L = mid; else R = mid - 1; } printf("%lld\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
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]))
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; long long t, n, s, l, r, mid, sum, ans, answer; pair<long long, long long> p[200005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; for (int rr = 0; rr < t; rr++) { cin >> n >> s; for (int i = 0; i < n; i++) { cin >> p[i].first >> p[i].second; } sort(p, p + n); l = 1; r = s; while (l <= r) { mid = (l + r) >> 1; sum = (n + 1) >> 1; ans = 0; for (int i = n - 1; i >= 0; i--) { if (p[i].first <= mid && p[i].second >= mid && sum > 0) { sum--; ans += mid; } else if (p[i].first > mid) { sum--; ans += p[i].first; } else { ans += p[i].first; } } if (ans > s || sum > 0) { r = mid - 1; } else { l = mid + 1; answer = mid; } } cout << answer << '\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 sys def BinSearch(): pass t = int(sys.stdin.readline()) for _ in range(t): n, s = map(int, sys.stdin.readline().split()) tmp = [tuple(map(int, sys.stdin.readline().split())) for _ in range(n)] mid = s r = s l = 0 tmp.sort() while True: tp = [] tp1 = 0 tmpSum = 0 for x in tmp: if x[0] >= mid: tp1 += 1 tmpSum += x[0] elif x[1] >= mid: tp.append(x) else: tmpSum += x[0] q = len(tp) qq = (n + 1) // 2 - tp1 for i in range(q): if i >= qq: tmpSum += tp[q - 1 - i][0] if qq > q or tmpSum + qq * mid > s: if r - l <= 1: print(r - 1) break r = mid else: if r - l <= 1: print(l) break l = mid mid = l + (r - l) // 2
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 long long int inf = 9e18; const long double pi = 2 * acos(0.0); using namespace std; long long int power(long long int a, long long int n) { if (n == 0) { return 1; } long long int p = power(a, n / 2) % 1000000007; p = (p * p) % 1000000007; if (n % 2 == 1) { p = (p * a) % 1000000007; } return p; } long long int gcd(long long int a, long long int b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6; vector<long long int> sieve(N, 0); void si() { sieve[1] = 1; for (int i = 2; i < N; i++) { if (sieve[i] == 0) { for (int j = i; j < N; j += i) { sieve[j] = i; } } } } long long int isprime(long long int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return 0; } } return 1; } long long int n, s; int solve(vector<pair<long long int, long long int> > &a, long long int val, long long int s) { vector<pair<long long int, long long int> > v; int need = (n - 1) / 2; long long int tot = 0; int left = 0, right = 0; for (int i = 0; i < n; i++) { if (a[i].first < val && a[i].second < val) { left += 1; tot += a[i].first; } else if (a[i].first > val && a[i].second > val) { right += 1; tot += a[i].first; } else { v.push_back(make_pair(a[i].first, a[i].second)); } } sort(v.begin(), v.end()); if (left > need) { return -1; } if (right > need) { return -2; } int need1 = need - left; for (int i = 0; i < need1; i++) { tot += v[i].first; } int need2 = need - right + 1; for (int i = 0; i < need2; i++) { tot += val; } if (tot > s) { return -2; } return 1; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; int t; cin >> t; while (t--) { cin >> n >> s; vector<long long int> L(n); vector<long long int> R(n); vector<pair<long long int, long long int> > a(n); for (int i = 0; i < n; i++) { cin >> L[i] >> R[i]; a[i] = make_pair(L[i], R[i]); } sort(L.begin(), L.end()); sort(R.begin(), R.end()); long long int l = L[n / 2]; long long int r = R[n / 2]; while (l <= r) { long long int mid = (l + r) / 2; if (solve(a, mid, s) == -1) { l = mid + 1; } else if (solve(a, mid, s) == -2) { r = mid - 1; } else { if (solve(a, mid + 1, s) == -1 || solve(a, mid + 1, s) == -2) { cout << mid << "\n"; break; } else { l = mid + 1; } } } } 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; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); inline long long rand(long long x, long long y) { return (rng() % (y + 1 - x)) + x; } string to_string(char c) { string second(1, c); return second; } template <typename T> inline T gcd(T a, T b) { return a == 0 ? b : gcd(b % a, a); } long long int t, n, second; pair<long long int, long long int> A[(200006)]; vector<long long int> v; bool bstar(long long int x) { v.clear(); for (long long int i = (n - 1); i >= (long long int)(0); --i) if (A[i].second >= x && v.size() < (n / 2 + 1)) { v.push_back(A[i].first); } if (v.size() < (n / 2 + 1)) return 0; long long int ans = 0; for (auto i : v) ans += max(0ll, x - i); return ans <= second; } void solve() { cin >> n >> second; for (long long int i = (0); i <= (long long int)(n - 1); ++i) { long long int a, b; cin >> a >> b; second -= a; A[i] = pair<long long int, long long int>(a, b); } sort(A, A + n); long long int st = 0, en = 2e14 + 10, mid = 0; while (en - st > 1) { mid = (st + en) >> 1; if (bstar(mid)) st = mid; else en = mid; } cout << st << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); 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 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.Comparator; 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; int[][] a; long lsum; boolean ok(long x) { int numLess = 0, numGreater = 0, numEqual = 0; for (int i = 0; i < n; i++) { if (a[i][0] < x) { numLess++; } else if (a[i][0] > 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][0] < x && x <= a[i][1]) { diffs.add(x - a[i][0]); } } int need = (n + 1) / 2 - (numEqual + numGreater); if (diffs.size() < need) { return false; } diffs = sorted(diffs); 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 int[n][2]; lsum = 0; for (int i = 0; i < n; i++) { a[i][0] = in.nextInt(); a[i][1] = in.nextInt(); lsum += a[i][0]; } Arrays.sort(a, Comparator.comparingInt(x -> x[0])); long ans = a[n / 2][0]; for (long jump = 2 * s; jump >= 1; jump /= 2) { while (ok(ans + jump)) { ans += jump; } } out.println(ans); } } EzLongArrayList sorted(EzLongArrayList v) { long[] sorted = v.toArray(); EzLongSort.safeArraysSort(sorted); return new EzLongArrayList(sorted); } } 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 n = a.length; randomShuffle(a, 0, n); Arrays.sort(a, 0, n); } } static interface EzLongCollection { int size(); EzLongIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static interface EzLongList extends 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 long[] toArray() { long[] result = new long[size]; System.arraycopy(array, 0, result, 0, size); return result; } 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(); } 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 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(); } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(long x) { return (int) x ^ (int) (x >>> 32); } } }
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.*; @SuppressWarnings("unused") public class Main { private FastScanner in; private PrintWriter out; final int MOD = (int)1e9+7; long ceil(long a, long b){return (a + b - 1) / b;} long gcd(long a, long b){return b == 0 ? a : gcd(b, a % b);} long lcm(long a, long b){return a / gcd(a, b) * b; /*γ‚ͺーバーフローに注意*/} int n; long s; Long[][] lr; void solve() { int t = in.nextInt(); for (int i = 0; i < t; i++) { n = in.nextInt(); s = in.nextLong(); lr = new Long[n][2]; for (int j = 0; j < n; j++) { lr[j][0] = in.nextLong(); lr[j][1] = in.nextLong(); } Arrays.sort(lr, (e1, e2)->Long.compare(e1[0], e2[0])); long ok = lr[n / 2][0], ng = s+1; while(ng - ok > 1){ long mid = (ok + ng) / 2; boolean tf = isOk(mid); if(tf) ok = mid; else ng = mid; } out.println(ok); } } //end solve boolean isOk(long mid){ long sum = 0; int numLeft = 0, numRight = 0; ArrayList<Long> listMid = new ArrayList<>(); for(int i = 0; i < n; i++){ if(lr[i][1] < mid){ numLeft++; sum += lr[i][0]; }else if(lr[i][0] > mid){ numRight++; sum += lr[i][0]; }else{ listMid.add(lr[i][0]); } if(sum > s) return false; } if((n - 1) / 2 < numLeft || (n - 1) / 2 < numRight) return false; for(int i = 0; i < listMid.size(); i++){ if((n - 1) / 2 == numLeft) break; numLeft++; sum += listMid.get(i); if(sum > s) return false; } sum += ((n - 1) / 2 - numRight + 1) * mid; if(sum > s) return false; return true; } public static void main(String[] args) { new Main().m(); } private void m() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.flush(); in.close(); out.close(); } static class FastScanner { private Reader input; public FastScanner() {this(System.in);} public FastScanner(InputStream stream) {this.input = new BufferedReader(new InputStreamReader(stream));} public void close() { try { this.input.close(); } catch (IOException e) { e.printStackTrace(); } } public int nextInt() {return (int) nextLong();} public long nextLong() { try { int sign = 1; int b = input.read(); while ((b < '0' || '9' < b) && b != '-' && b != '+') { b = input.read(); } if (b == '-') { sign = -1; b = input.read(); } else if (b == '+') { b = input.read(); } long ret = b - '0'; while (true) { b = input.read(); if (b < '0' || '9' < b) return ret * sign; ret *= 10; ret += b - '0'; } } catch (IOException e) { e.printStackTrace(); return -1; } } public double nextDouble() { try { double sign = 1; int b = input.read(); while ((b < '0' || '9' < b) && b != '-' && b != '+') { b = input.read(); } if (b == '-') { sign = -1; b = input.read(); } else if (b == '+') { b = input.read(); } double ret = b - '0'; while (true) { b = input.read(); if (b < '0' || '9' < b) break; ret *= 10; ret += b - '0'; } if (b != '.') return sign * ret; double div = 1; b = input.read(); while ('0' <= b && b <= '9') { ret *= 10; ret += b - '0'; div *= 10; b = input.read(); } return sign * ret / div; } catch (IOException e) { e.printStackTrace(); return Double.NaN; } } public char nextChar() { try { int b = input.read(); while (Character.isWhitespace(b)) { b = input.read(); } return (char) b; } catch (IOException e) { e.printStackTrace(); return 0; } } public String nextStr() { try { StringBuilder sb = new StringBuilder(); int b = input.read(); while (Character.isWhitespace(b)) { b = input.read(); } while (b != -1 && !Character.isWhitespace(b)) { sb.append((char) b); b = input.read(); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public int[] nextIntArrayDec(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt() - 1; } return res; } public int[] nextIntArray1Index(int n) { int[] res = new int[n + 1]; for (int i = 0; i < n; i++) { res[i + 1] = nextInt(); } return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } public long[] nextLongArrayDec(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong() - 1; } return res; } public long[] nextLongArray1Index(int n) { long[] res = new long[n + 1]; for (int i = 0; i < n; i++) { res[i + 1] = nextLong(); } return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) { res[i] = nextDouble(); } return res; } } }
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> 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; 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 if (money[i].first < mid && money[i].second >= mid) { if (cnt > n / 2) { sum += money[i].first; } else { cnt++; sum += mid; } } } return cnt > n / 2 && 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()); reverse(money.begin(), money.end()); int low = 0, high = 1e9 + 17, ans = 0; while (low <= high) { int mid = low + (high - low) / 2; bool isPossible = Possible(money, s, mid, n); if (isPossible) { ans = mid; low = mid + 1; } else { high = mid - 1; } } 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
import sys input = sys.stdin.readline t=int(input()) for test in range(t): n,s=map(int,input().split()) LR=[tuple(map(int,input().split())) for i in range(n)] LR.sort(reverse=True) R=[r for l,r in LR] R.sort() #print(LR,R) MIN=LR[n//2][0] MAX=R[n//2] OK=(n+1)//2 while MIN!=MAX: mid=(MIN+MAX+1)//2 #print(MIN,MAX,mid) count=0 money=0 for l,r in LR: if count<OK: if r>=mid: money+=max(l,mid) count+=1 else: money+=l else: money+=l if count>=OK and money<=s: MIN=mid else: MAX=mid-1 print(MIN)
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; using LL = long long; int T, n; LL s, l[200005], r[200005], bufl[200005]; bool check(LL x) { int a = 0, b = 0, c = 0; LL sa = 0; for (int i = 1; i <= n; i++) if (r[i] < x) ++a, sa += l[i]; else if (l[i] <= x) ++b, bufl[b] = l[i]; else ++c, sa += l[i]; if (c >= n + 1 >> 1) return true; if (a >= n + 1 >> 1) return false; nth_element(bufl + 1, bufl + (n + 1 >> 1) - a, bufl + b + 1); LL u = ((n + 1 >> 1) - c) * x + sa; for (int i = 1; i < (n + 1 >> 1) - a; i++) u += bufl[i]; return u <= s; } int main() { scanf("%d", &T); while (T--) { scanf("%d%lld", &n, &s); for (int i = 1; i <= n; i++) scanf("%lld%lld", &l[i], &r[i]); LL L = 1, R = min(s, (long long)1E9), M; while (L < R) { M = L + R + 1 >> 1; if (check(M)) L = M; else R = M - 1; } printf("%lld\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
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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") #------------------------------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=-10**6, 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) class SegmentTree1: def __init__(self, data, default=10**6, func=lambda a, b: min(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) MOD=10**9+7 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 mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(200001)] pp=[0]*200001 def SieveOfEratosthenes(n=200000): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 for i in range (1,200001): pp[i]=pp[i-1] if prime[i]: pp[i]+=1 #---------------------------------running code------------------------------------------ for _ 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
import java.util.*; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; import java.awt.image.BufferedImage; import java.io.*; import java.math.BigInteger; public class template { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); for(int i=0;i<n;i++){ int ppl = sc.nextInt(); long dol = sc.nextLong(); ArrayList<pair> arr = new ArrayList<pair>(); ArrayList<pair> arr2 = new ArrayList<pair>(); for(int j=0;j<ppl;j++){ arr.add(new pair(sc.nextInt(),sc.nextInt())); arr2.add(arr.get(j)); } Collections.sort(arr, new pairx()); Collections.sort(arr2, new pairy()); int[] x = new int[ppl]; for(int j=0;j<x.length;j++){ x[j]=arr.get(j).x; dol-=arr.get(j).x; } int l = 0; int r = (int)1e9; int m = 0; while(r>=l){ m = l + (r - l) / 2; if(fill(m,x,arr)==dol){ r=m; break; } if(fill(m,x,arr)>dol){ r = m-1; } else{ l=m+1; } //System.out.println(r+" "+l); } //pw.println(l+" "+r); //pw.println(fill(r,x,arr2)); pw.println(Math.min(Math.max(x[ppl/2],r),arr2.get(ppl/2).y)); } pw.close(); } static long fill(int dols, int[] x,ArrayList<pair> y){ int mid = x.length/2; long sum = 0; for(int i = x.length-1;mid>=0;i--){ if(i==-1){ return Long.MAX_VALUE; } if(y.get(i).y<dols){ continue; } else{ sum+=Math.max(0, dols-x[i]); mid--; } } return sum; } static class pair { int x,y; public pair(int x,int y){ this.x=x; this.y=y; } } static class pairx implements Comparator<pair>{ public int compare(pair a, pair b){ return Integer.compare(a.x,b.x); } } static class pairy implements Comparator<pair>{ public int compare(pair a, pair b){ return Integer.compare(a.y,b.y); } } } @SuppressWarnings("all") class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
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>> emp; int n; long long s, minS; bool bSearch(long long t) { int neededBigger = n / 2 + 1; long long curS = s - minS; for (int i = emp.size() - 1; i >= 0 && neededBigger > 0; i--) { if (emp[i].first >= t) { neededBigger--; continue; } else if (emp[i].second >= t) { long long need = t - emp[i].first; if (curS < need) { return false; } curS -= need; neededBigger--; } } if (neededBigger > 0) { return false; } return true; } int main() { int t; cin >> t; while (t--) { cin >> n; cin >> s; minS = 0; emp.clear(); emp.resize(n); for (int i = 0; i < n; i++) { long long l, r; cin >> l >> r; emp[i] = {l, r}; minS += l; } sort(emp.begin(), emp.end()); long long a = 0, b = s; while (a < b) { long long mid = (a + b + 1) / 2; bool curB = bSearch(mid); if (curB) { a = mid; } else { b = mid - 1; } } cout << a << 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; const int N = 2e5 + 6; const long long MOD2 = 1e9 + 7; const long long MOD = 998244353; long long s; pair<long long, long long> a[N]; int n; int qan; bool check(long long v) { long long ans = 0; qan = n / 2 + 1; for (int i = (n)-1; i >= 0; i--) { if (a[i].first > v && qan) { ans += a[i].first; qan--; } else if (a[i].first <= v && v <= a[i].second && qan) { ans += v; qan--; } else { ans += a[i].first; } } if (qan == 0 && ans <= s) return true; return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int ttt; cin >> ttt; while (ttt--) { cin >> n >> s; for (int i = 0; i < (n); ++i) { cin >> a[i].first >> a[i].second; } sort(a, a + n); int l = 0, r = 1e9 + 1; while (l < r) { int md = (l + r) / 2; if (check(md)) { l = md + 1; } else { r = md; } } cout << l - 1 << 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
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static ArrayList<Pair> graph[]; static int pptr=0; static String st[]; /****************************************Solutions Begins***************************************/ public static void main(String[] args) throws Exception{ nl(); int t=pi(); while(t-->0){ nl(); int n=pi(); long s=pl(); Pair input[]=new Pair[n]; for(int i=0;i<n;i++){ nl(); input[i]=new Pair(pi(),pi()); } Arrays.sort(input,(a,b)->{ if(a.v!=b.v)return a.v-b.v; else return b.u-a.u; }); long ans=-1; long start=0; long end=s; PriorityQueue<Integer> pq=new PriorityQueue<>(); while(start<=end){ long mid=(start+end)/2; boolean flag=true; if(input[n/2].v<mid)flag=false; long mn=0; if(flag){ int cnt=0; pq.clear(); for(int i=0;i<n;i++){ if(input[i].v<mid){ mn+=input[i].u; cnt++; } else pq.add(input[i].u); } while(cnt<n/2){ mn+=pq.remove(); cnt++; } while(cnt<n){ mn+=Math.max(mid,pq.remove()); cnt++; } } if(flag&&mn<=s){ ans=mid; start=mid+1; } else{ end=mid-1; } } out.println(ans); } /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static void nl() throws Exception{ pptr=0; st=br.readLine().split(" "); } static void nls() throws Exception{ pptr=0; st=br.readLine().split(""); } static int pi(){ return Integer.parseInt(st[pptr++]); } static long pl(){ return Long.parseLong(st[pptr++]); } static double pd(){ return Double.parseDouble(st[pptr++]); } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000000000000"); out.print(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static long countBit(long mask){ long ans=0; while(mask!=0){ if(mask%2==1){ ans++; } mask/=2; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o){ System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c){ long x=1; long y=a%c; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y){ if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0){ r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
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 optimise() { ios_base::sync_with_stdio(false); cin.tie(NULL); } bool compare(pair<long long int, long long int> X, pair<long long int, long long int> Y) { if (X.second < Y.second) return 1; else if (Y.second < X.second) return 0; else { if (X.first <= Y.first) return 1; else return 0; } } void solve() { long long int n, s; cin >> n >> s; vector<pair<long long int, long long int> > v(n); for (long long int i = 0; i < n; i++) { cin >> v[i].first >> v[i].second; } sort(v.rbegin(), v.rend()); long long int beg = 1; long long int end = s; long long int ans = -1; while (beg <= end) { long long int mid = (beg + end) / 2; long long int sum = 0; long long int curr = 0; long long int flag = 0; for (long long int i = 0; i < n; i++) { if ((v[i].first >= mid || (v[i].first <= mid && v[i].second >= mid)) && (curr < (n + 1) / 2)) { sum += max(v[i].first, mid); curr++; } else sum += v[i].first; } if (curr == (n + 1) / 2 && sum <= s) { beg = mid + 1; ans = mid; } else end = mid - 1; } cout << ans; } signed main() { optimise(); long long int t; t = 1; cin >> t; while (t--) { solve(); cout << "\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.util.*; public class temp1 { public static PrintWriter out; static int o = 0, e = 0; static int[] fa; static int[][][][] dp; static ArrayList<Integer>[] a; static int ans = 0; public static void main(String[] args) throws IOException { Reader scn = new Reader(); int t = scn.nextInt(); while (t-- != 0) { long n = scn.nextLong(), s = scn.nextLong(); ArrayList<pair> p = new ArrayList<>(); for (int i = 0; i < n; i++) p.add(new pair(scn.nextLong(), scn.nextLong())); Collections.sort(p); long lo = 0, hi = (long) 1e10, ans = 0; while (lo <= hi) { long mid = (lo + hi) / 2; if (f(mid, p, s)) { ans = mid; lo = mid + 1; } else hi = mid - 1; } System.out.println(ans); } } private static boolean f(long mid, ArrayList<pair> p, long s) { for (pair rp : p) s -= rp.x; int cnt = (p.size() + 1) / 2; for (pair rp : p) { if (cnt > 0 && rp.y >= mid) { s -= Math.max(mid - rp.x, 0); cnt--; } } return s >= 0 && cnt == 0; } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if(a== 0) // return b; // // return gcd(b%a,a); // } // static class comp implements Comparator<pair> { // // @Override // public int compare(pair o1, pair o2) { // // return (int) (o1.y - o1.y); // } // // } static class pair implements Comparable<pair> { long x = 0; long y = 0; pair(long a, long s) { x = Math.min(a, s); y = Math.max(a, s); } @Override public int compareTo(pair o) { if(this.x!=o.x) return (int)(o.x - this.x); else return(int)( o.y -this.y); } } public 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[100000 + 1]; // 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 int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } 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 sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, s = map(int, input().split()) L = [0]*n R = [0]*n RL = [0]*n for i in range(n): l, r = map(int, input().split()) L[i] = l R[i] = r RL[i] = (r, l) L.sort() R.sort() #RL.sort() def is_ok(x): t = 0 cnt1 = 0 cnt2 = 0 g = [] for i in range(n): r, l = RL[i] if r < x: t += l elif x <= l: cnt1 += 1 t += l else: cnt2 += 1 g.append(l) g.sort() need = (n+1)//2-cnt1 for i in range(len(g)-need): t += g[i] t += x*need if t <= s: return True else: return False ok = L[n//2] ng = R[n//2]+1 while ok+1 < ng: c = (ok+ng)//2 if is_ok(c): ok = c else: ng = c 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
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static long cf = 998244353; static final long MAX = (long) 1e8; public static List<Integer>[] edges; public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); long s = sc.nextLong(); Pair[] p = new Pair[n]; for(int i=0;i<n;++i) p[i] = new Pair(sc.nextInt(),sc.nextInt()); Arrays.sort(p,new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.l != o2.l) return o1.l - o2.l; return o1.r - o2.r; } }); int need = (n+1)/2; int low = 1,high = (int) 1e9; while(low<=high) { int median = (low+high)/2; if(check(median,p,need,s)) { low = median+1; }else high = median-1; } out.println(low-1); } out.close(); } private static boolean check(int median, Pair[] p, int need, long s) { for(Pair x : p) s-=x.l; for(int i=p.length-1;i>=0 && need > 0;--i) { if(p[i].r >= median) { --need; s-=Math.max(median-p[i].l, 0); } } return s>=0&&need == 0; } static class Pair{ int l; int r; Pair(int l,int r){ this.l = l; this.r = r; } } }
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 inf = 0x3f3f3f3f; const long long INF = 1e18; vector<pair<long long, long long> > a; int n; long long s; long long check(long long m) { int countt = a.size() / 2 + 1; long long sum = 0; for (int i = 0; i < a.size(); i++) { if (a[i].first <= m && a[i].second >= m && countt) { sum += m; countt--; } else { sum += a[i].first; if (a[i].first > m) countt--; } } if (countt) return s + 10; else return sum; } int main() { int t; cin >> t; while (t--) { scanf("%d%I64d", &n, &s); a.clear(); for (int i = 1; i <= n; i++) { long long x, y; scanf("%I64d%I64d", &x, &y); a.push_back(make_pair(x, y)); } sort(a.begin(), a.end()); reverse(a.begin(), a.end()); long long l = a[a.size() / 2].first + 1, r = s; while (l <= r) { long long midd = (l + r) >> 1; if (check(midd) <= s) l = midd + 1; else r = midd - 1; } printf("%I64d\n", l - 1); } 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; void fast() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } const long long mas = 200000 + 10; long long l[mas], r[mas]; long long num[mas]; bool cmp(int x, int y) { return l[x] < l[y]; } int main() { fast(); long long t; cin >> t; long long n, s, kol, mn, mx, h, tmp; while (t--) { cin >> n >> s; for (int i = 1; i <= n; ++i) cin >> l[i] >> r[i]; for (int i = 1; i <= n; ++i) num[i] = i; sort(num + 1, num + n + 1, cmp); for (int i = 1; i <= n; ++i) s -= l[i]; mn = 1; mx = 10000000000; while (mn + 1 < mx) { kol = 0; h = (mx + mn) / 2; for (int i = 1; i <= n; ++i) { if (r[i] >= h) kol++; } if (kol <= n / 2) { mx = h; continue; } kol = 0; for (int i = n; i >= 1; --i) { if (r[num[i]] >= h) kol++; if (kol == n / 2 + 1) { kol = i; break; } } tmp = s; for (int i = n; i >= kol; --i) { if (r[num[i]] >= h && l[num[i]] < h) { tmp -= h - l[num[i]]; } } if (tmp >= 0) { mn = h; } else { mx = h; } } cout << mn << "\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 LabAlgoOne { //Scanner static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); static String currentInputLine = ""; static String inputFileName = "avia.in"; static String outputFileName = "avia.out"; static int currentInputIndex = 0; static void nextInputLine() { try { currentInputLine = reader.readLine(); currentInputIndex = 0; } catch (IOException ignored) { throw new RuntimeException(); } } static void skipSpaces() { while (currentInputIndex < currentInputLine.length() && currentInputLine.charAt(currentInputIndex) == ' ') { currentInputIndex++; } if (currentInputIndex == currentInputLine.length()) { nextInputLine(); skipSpaces(); } } static String next() { skipSpaces(); int end = currentInputLine.indexOf(" ", currentInputIndex); if (end == -1) { end = currentInputLine.length(); } String res = currentInputLine.substring(currentInputIndex, end); currentInputIndex = end; return res; } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static void toFile() { try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFileName))); writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFileName))); } catch (IOException e) { throw new RuntimeException(); } } //Main private static class Worker { long min, max; Worker(long min, long max) { this.min = min; this.max = max; } } private static boolean check(long sum, long med, ArrayList<Worker> workers) { ArrayList<Worker> less = new ArrayList<>(); ArrayList<Worker> proc = new ArrayList<>(); ArrayList<Worker> great = new ArrayList<>(); for (Worker worker : workers) { if (worker.max < med) { less.add(worker); } else if (worker.min > med) { great.add(worker); } else { proc.add(worker); } } if (less.size() > workers.size() / 2 || great.size() > workers.size() / 2) { return false; } proc.sort(new Comparator<Worker>() { @Override public int compare(Worker worker, Worker t1) { long res = worker.min - t1.min; if (res < 0) { return -1; } else if (res == 0) { return 0; } else { return 1; } } }); long sup = 0; for (Worker worker : less) { sup += worker.min; } for (Worker worker : great) { sup += worker.min; } sup += (workers.size() / 2 + 1 - great.size()) * med; for (int i = 0; i + less.size() < workers.size() / 2; i++) { sup += proc.get(i).min; } return sup <= sum; } public static void main(String[] args) { int n = nextInt(); for (int i = 0; i < n; i++) { int m = nextInt(); long s = nextLong(); ArrayList<Worker> workers = new ArrayList<>(); for (int j = 0; j < m; j++) { workers.add(new Worker(nextLong(), nextLong())); } workers.sort(new Comparator<Worker>() { @Override public int compare(Worker worker, Worker t1) { long res = worker.max - t1.max; if (res < 0) { return -1; } else if (res == 0) { return 0; } else { return 1; } } }); long r = workers.get(workers.size() / 2).max + 1; workers.sort(new Comparator<Worker>() { @Override public int compare(Worker worker, Worker t1) { long res = worker.min - t1.min; if (res < 0) { return -1; } else if (res == 0) { return 0; } else { return 1; } } }); long l = workers.get(workers.size() / 2).min; while (l + 1 != r) { long med = (l + r) / 2; if (check(s, med, workers)) { l = med; } else { r = med; } } System.out.println(l); } writer.println(); writer.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 sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal #from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 for t in range(int(data())): n,s=mdata() lis=sorted([mdata() for i in range(n)]) sum1=0 m=0 for i in range(n): sum1+=lis[i][0] m=max(m,lis[i][1]) s-=sum1 start,end=0,m while start<=end: sum2=s mid=(start+end)//2 cnt=0 for i,j in lis[::-1]: if i>=mid: cnt+=1 elif j>=mid and sum2>=mid-i: cnt+=1 sum2-=mid-i if cnt>=n//2+1: start=mid+1 else: end=mid-1 out(end)
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 D { boolean ok(long MEAN, long S, long[][] interv){ PriorityQueue<Long> pq = new PriorityQueue<>(); long SUM = 0; int N = interv[0].length; int to_add = N/2 + 1; int no_above = 0; for(int i = 0; i<N; i++) { SUM += interv[0][i]; if(interv[1][i] >= MEAN){ pq.add(-interv[0][i]); no_above++; } } if(no_above < to_add) return false; for(int t = 0; t<to_add; t++){ long x = -pq.poll(); SUM += Math.max(0, MEAN - x); } return SUM <= S; } void solve(BufferedReader in) throws Exception { long T = toInt(in.readLine()); for(int t = 0; t<T; t++) { long[] xx = toInts(in.readLine()); int n = (int) xx[0]; long S = xx[1]; long[] los = new long[n]; long[] his = new long[n]; long[][] interv = new long[2][n]; for(int i = 0; i<n; i++) { xx = toInts(in.readLine()); long a = xx[0], b = xx[1]; los[i] = a; his[i] = b; interv[0][i] = a; interv[1][i] = b; } Arrays.sort(los); Arrays.sort(his); int mid = n/2; long lo = los[mid]; long hi = his[mid]; while(lo < hi) { long MEAN = (lo + hi + 1)/2; if(ok(MEAN, S, interv)){ lo = MEAN; } else hi = MEAN - 1; } System.out.println(lo); } } long toInt(String s) {return Long.parseLong(s);} long[] toInts(String s) { String[] a = s.split(" "); long[] o = new long[a.length]; for(int i = 0; i<a.length; i++) o[i] = toInt(a[i]); return o; } void e(Object o) { System.err.println(o); } public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); (new D()).solve(in); } }
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 import math from collections import defaultdict from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : map(int, input().split()) def write(*args, sep="\n"): for i in args: sys.stdout.write("{}".format(i) + sep) INF = float('inf') MOD = int(1e9 + 7) for t in range(int(input())): n, x= read() lr = sorted([list(read()) for i in range(n)], reverse = True) s = 0 e = 1<<32 while s <= e: m = (s + e) // 2 money = 0 a, b, c = 0, [], 0 for l, r in lr: if l > m: c += 1 money += l elif r < m: a += 1 money += l else: b.append((l, r)) if money > x or a >= n//2 + 1: e = m - 1 continue need = n//2 + 1 - c cnt = 0 #print(money, a,b,c,m, sep="\n") for l, r in b: #print(money, cnt, need, l, r) if cnt < need: money += m cnt += 1 else: money += l if money <= x: s = m + 1 else: e = m - 1 write(e)
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 input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N, S = map(int, input().split()) LR = [list(map(int, input().split())) for _ in range(N)] Query.append((N, S, LR)) for N, S, LR in Query: G = [] for L, _ in LR: G.append(L) G.sort() l = G[N//2] r = S+1 while r - l > 1: m = (l+r)//2 A = [] B = [] C = [] for L, R in LR: if L <= m <= R: C.append(L) elif R < m: A.append(L) else: B.append(L) C.sort() if len(A) < N//2+1 <= len(A)+len(C): if sum(A)+sum(B)+sum(C[:N//2-len(A)]) + m*(len(A)+len(C)-N//2) <= S: l = m else: r = m else: r = m 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; int main() { ios::sync_with_stdio(false); cin.tie(0); long long n, i, j, x, t, y, s; cin >> t; while (t--) { cin >> n >> s; vector<pair<long long, long long> > v; long long lo = 1e18, mid, hi = 0; for (i = 0; i < n; i++) { cin >> x >> y; v.push_back({x, y}); lo = min(lo, x); hi = max(hi, y); } sort(v.begin(), v.end(), greater<pair<long long, long long> >()); x = n / 2; long long ans = lo; while (lo <= hi) { mid = (lo + hi) / 2; bool ok = 1; long long temp = 0; vector<long long> d; for (i = 0; i < n; i++) { if (v[i].second < mid) { temp += v[i].first; d.push_back(v[i].first); } } long long cnt = 0; for (i = 0; i < n; i++) { if (mid <= v[i].first) { temp += v[i].first; d.push_back(v[i].first); cnt++; } } for (i = 0; i < n; i++) { if (mid > v[i].first && mid <= v[i].second) { if (cnt > x) { temp += v[i].first; d.push_back(v[i].first); } else { temp += mid; d.push_back(mid); cnt++; } } } if (cnt <= x) ok = 0; if (temp > s) ok = 0; if (ok) { sort(d.begin(), d.end()); ans = max(ans, d[x]); lo = mid + 1; } else hi = 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
#include <bits/stdc++.h> using namespace std; using ll = long long; ll n, s; vector<pair<ll, ll>> v; bool ok(ll x) { ll ns = 0, cnt = 0; vector<ll> vx; for (ll i = 0; i < n; ++i) { if (v[i].second < x) { ns += v[i].first; } else if (v[i].first >= x) { ns += v[i].first; cnt++; } else vx.push_back(v[i].first); } sort(vx.begin(), vx.end()); ll tam = max(0LL, (n + 1LL) / 2LL - cnt); if (tam > vx.size()) return false; for (ll i = 0; i < vx.size(); ++i) { if (i < vx.size() - tam) ns += vx[i]; else ns += x; } return ns <= s; } void solve() { cin >> n >> s; v = vector<pair<ll, ll>>(n); for (ll i = 0; i < n; ++i) { cin >> v[i].first >> v[i].second; } sort(v.begin(), v.end()); ll lo = 1, hi = 1e9 + 10, mid; while (hi - lo > 1LL) { mid = (lo + hi) / 2LL; if (ok(mid)) { lo = mid; } else { hi = mid; } } cout << lo << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t = 1; 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; bool can(long long mid, vector<pair<long long, long long>> &f, long long n, long long s) { long long sum = 0, cnt = 0; vector<long long> v; for (long long i = 0; i < n; i++) { if (f[i].second < mid) sum += f[i].first; else if (f[i].first >= mid) { sum += f[i].first; cnt++; } else { v.push_back(f[i].first); } } long long rem = max(0LL, (n + 1) / 2 - cnt); if (v.size() < rem) return false; sort(v.rbegin(), v.rend()); for (long long i = 0; i < v.size(); ++i) { if (rem > 0) { sum += mid; rem--; } else { sum += v[i]; } } return sum <= s; } signed main() { long long t; cin >> t; while (t--) { long long n, s; cin >> n >> s; vector<pair<long long, long long>> f(n); for (long long i = 0; i < n; i++) { cin >> f[i].first >> f[i].second; } long long left = 0, right = 1e9 + 7; while (right - left > 1) { long long mid = right + left >> 1; if (can(mid, f, n, s)) left = mid; else right = mid; } cout << left << '\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; const int maxn = 5e5 + 5; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; template <typename T> void scan(T& a) { cin >> a; } template <typename T, typename... Args> void scan(T& t, Args&... a) { scan(t); scan(a...); } template <typename T> void debug(T a) { cout << a << ' '; } template <typename T, typename... Args> void debug(T t, Args... a) { debug(t); debug(a...); } template <typename T> void send(T a) { cout << a << '\n'; } template <typename T> void send(vector<T> a) { for (int i = 0; i < a.size(); i++) debug(a[i]); send(' '); } template <typename T, typename... Args> void send(T t, Args... a) { send(t); send(a...); } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int q; scan(q); while (q-- > 0) { long long p; int n; scan(n, p); vector<pair<long long, long long>> a(n); vector<long long> res; for (int i = 0; i < n; i++) { scan(a[i].first, a[i].second); res.push_back(a[i].first); } sort((a).begin(), (a).end()); int middle = n / 2; long long l = a[middle].first, r = 2000000000; while (l < r) { long long mid = (l + r) / 2ll; long long answ = 0; int cnt = middle + 1; for (int i = n - 1; i >= 0; i--) { if (a[i].first > mid && cnt) { answ += a[i].first; cnt--; } else if (a[i].first <= mid && mid <= a[i].second && cnt) { cnt--; answ += mid; } else answ += a[i].first; } if (cnt == 0 && answ <= p) { l = mid + 1; } else r = mid; } cout << l - 1 << '\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, MAX = 2e5 + 2; int n; long long sum, res; vector<pair<long long, long long>> v; int b_s(long long beg, long long end) { if (beg > end) return 0; long long mid = (beg + end) / 2, total = sum; int cnt = 0; vector<pair<long long, long long>> temp = v; for (int i = n - 1; i >= 0; --i) if (temp[i].second >= mid && cnt < (n + 1) / 2) cnt++, temp[i].second = -1, total -= max(temp[i].first, mid); if (cnt == (n + 1) / 2) { long long mx = 0; for (int i = 0; i < n; i++) if (temp[i].second != -1) total -= temp[i].first, mx = max(mx, temp[i].first); if (mx > mid) total = -1; if (total >= 0) return res = max(res, mid), b_s(mid + 1, end); } return b_s(beg, mid - 1); } void fast(); int main() { fast(); int t; cin >> t; while (t--) { cin >> n >> sum; v.resize(n); for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second; sort((v).begin(), (v).end()); res = 0; if (n == 1) cout << min(sum, v[0].second) << "\n"; else { b_s(v[n / 2].first, sum); cout << res << "\n"; } } } void fast() { std::ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); }
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.InputMismatchException; import java.io.IOException; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ 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); DSalaryChanging solver = new DSalaryChanging(); solver.solve(1, in, out); out.close(); } static class DSalaryChanging { public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); long sal = s.nextLong(); long[] l = new long[n]; long[] r = new long[n]; long minTotal = 0; for (int i = 0; i < n; i++) { l[i] = s.nextLong(); minTotal += l[i]; r[i] = s.nextLong(); } Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = i; Arrays.sort(a, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { if (l[o1] < l[o2]) return -1; if (l[o1] > l[o2]) return 1; return 0; } }); long left = l[a[n / 2]], right = (long) 1e15; long ans = left; while (left <= right) { long mid = (left + right) / 2; int[] asg = new int[n]; int rightCount = 0; int lim = n - 1; while (lim >= 0 && l[a[lim]] > mid) { asg[lim] = 1; lim--; rightCount++; } for (int i = 0; i <= lim; i++) { if (r[a[i]] < mid) { asg[i] = -1; } } long used = minTotal; for (int i = n - 1; rightCount < n / 2 + 1 && i >= 0; i--) { if (asg[i] != 0) continue; asg[i] = 1; used += mid - l[a[i]]; rightCount++; } if (rightCount == n / 2 + 1 && used <= sal) { ans = mid; left = mid + 1; } else { right = mid - 1; } } w.println(ans); } } } 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 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 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); } } }
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
from sys import stdin from sys import setrecursionlimit as SRL SRL(10 ** 7) rd = stdin.readline rrd = lambda: map(int, rd().strip().split()) q = int(input()) lr = [] def check(x, s): cnt = 0 tt = [] xcnt = 0 for l, r in lr[::-1]: if l>x: tt.append(l) cnt += 1 elif r >= x and l <= x and cnt < n // 2 + 1: cnt += 1 xcnt += 1 else: tt.append(l) if cnt == n // 2 + 1 and x * xcnt + sum(tt) <= s: return True return False while q: n, s = rrd() lr = [] for i in range(n): l, r = rrd() lr.append([l, r]) lr.sort() l = lr[n//2][0] r = s + 1 while l < r: m = (l + r) // 2 if check(m, s): l = m + 1 else: r = m print(r - 1) q -= 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; using ll = long long; const int N = 2e5 + 2; int t; int n; ll s, a[N]; pair<ll, ll> seg[N]; vector<ll> vs; int main() { ios::sync_with_stdio(false); cin >> t; while (t--) { cin >> n >> s; for (int i = 1; i <= n; ++i) { cin >> seg[i].first >> seg[i].second; a[i] = seg[i].first; s -= a[i]; } ll l = 0, r = 1e9, t; while (l <= r) { ll m = (l + r) / 2; int cnt = 0; for (int i = 1; i <= n; ++i) if (a[i] > m) ++cnt; if (cnt <= n / 2) { t = m; r = m - 1; } else { l = m + 1; } } l = t; r = 1e9; ll ans; while (l <= r) { ll m = (l + r) / 2; vs.clear(); int cs = 0; for (int i = 1; i <= n; ++i) if (a[i] < m) { ++cs; if (seg[i].second >= m) vs.push_back(m - seg[i].first); } sort(vs.begin(), vs.end()); cs -= n / 2; ll sum = 0; bool ok = true; if (cs > 0) { if (cs > vs.size()) ok = false; else { for (int i = 0; i < cs; ++i) sum += vs[i]; } } if (sum > s) ok = false; if (ok) { ans = m; l = m + 1; } else { r = m - 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 sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, s = map(int, input().split()) human = [] x = n//2 + 1 for _ in range(n): human.append(list(map(int, input().split()))) human.sort(reverse = True) remain = s for i in range(n): remain -= human[i][0] right = 10**9+1 left = 0 while right - left > 1: mid = left + (right-left)//2 count = 0 money = remain for i in range(n): if human[i][1] < mid: continue elif human[i][0] >= mid: count += 1 continue else: if money >= mid - human[i][0]: money -= mid - human[i][0] count += 1 else: break if count >= x: left = mid else: right = mid print(left)
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; 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 if (money[i].first < mid && money[i].second >= mid) { if (cnt > n / 2) { sum += money[i].first; } else { cnt++; sum += mid; } } } return cnt > n / 2 && 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()); reverse(money.begin(), money.end()); int low = 1, high = 1e9 + 17, 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
import sys import math from collections import defaultdict from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : map(int, input().split()) def write(*args, sep="\n"): for i in args: sys.stdout.write("{}".format(i) + sep) INF = float('inf') MOD = int(1e9 + 7) for t in range(int(input())): n, x= read() lr = sorted([list(read()) for i in range(n)], reverse = True) s = 0 e = int(1e9 + 10) while s <= e: m = (s + e) // 2 money = 0 a, b, c = 0, [], 0 for l, r in lr: if l > m: c += 1 money += l elif r < m: a += 1 money += l else: b.append((l, r)) if money > x or a >= n//2 + 1: e = m - 1 continue need = n//2 + 1 - c cnt = 0 #print(money, a,b,c,m, sep="\n") for l, r in b: #print(money, cnt, need, l, r) if cnt < need: money += m cnt += 1 else: money += l if money <= x: s = m + 1 else: e = m - 1 print(e)
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 MAXN = 2e5 + 5; int n; long long s; int x[MAXN], y[MAXN]; int tot, cnt, z[MAXN]; inline bool Check(int sl) { tot = cnt = 0; long long sum = 0; for (int i = 1; i <= n; i++) { if (y[i] >= sl) { if (x[i] >= sl) cnt++, sum += x[i]; else z[++tot] = -x[i]; } else sum += x[i]; } if (tot + cnt <= n / 2) return 0; sort(z + 1, z + tot + 1); for (int i = 1; i <= tot; i++) { if (cnt + i - 1 <= n / 2) sum += sl; else sum -= z[i]; } return sum <= s; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%I64d", &n, &s); for (int i = 1; i <= n; i++) scanf("%d%d", x + i, y + i); int l = 1, r = 1e9; while (l < r) { const int mid = l + r + 1 >> 1; if (Check(mid)) l = mid; else r = mid - 1; } printf("%d\n", r); } 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 INF = 1LL << 60; const long long MOD = 1000000007; template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } signed main(void) { long long q; cin >> q; for (long long(fjfea) = 0; (fjfea) < (q); (fjfea)++) { long long n, money; cin >> n >> money; vector<pair<long long, long long>> range(n); for (long long(i) = 0; (i) < (n); (i)++) { long long a, b; cin >> a >> b; range[i] = make_pair(a, b); } sort(range.begin(), range.end()); long long l = -1, r = money * 2; bool paid[n]; while (abs(r - l) > 1) { long long cost = 0, low = 0, high = 0; memset(paid, false, n); long long mid = (r + l) / 2; for (long long(i) = 0; (i) < (n); (i)++) { if (range[i].second < mid) cost += range[i].first, low++, paid[i] = true; if (range[i].first > mid) cost += range[i].first, high++, paid[i] = true; } if (low > n / 2 || cost > money) { r = mid; continue; } if (high > n / 2) { l = mid; continue; } for (long long(i) = 0; (i) < (n); (i)++) { if (!paid[i]) { if (low < n / 2) { low++; cost += range[i].first; paid[i] = true; } else { cost += mid; high++; } } } if (cost > money) { r = mid; continue; } else l = mid; } cout << l << 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; namespace flyinthesky { const int MAXN = 200000 + 5; long long n, s, ll[MAXN], rr[MAXN]; long long tot, orz[MAXN]; struct qj { long long l, r; } itv[MAXN]; bool chk(long long x) { long long gg1 = 0, gg2 = 0, gg3 = 0; for (int i = 1; i <= n; ++i) { if (itv[i].r < x) ++gg1; else if (itv[i].l > x) ++gg2; else orz[++gg3] = x - itv[i].l; } sort(orz + 1, orz + 1 + gg3); if (n / 2 - gg1 + n / 2 - gg2 >= gg3) return 0; for (int i = 2; i <= gg3; ++i) orz[i] += orz[i - 1]; long long hh = orz[n / 2 - gg2 + 1]; if (tot + hh <= s) return 1; else return 0; } void clean() {} int solve() { clean(); int t; cin >> t; while (t--) { scanf("%lld%lld", &n, &s); tot = 0; for (int i = 1; i <= n; ++i) { scanf("%lld%lld", &ll[i], &rr[i]); itv[i] = (qj){ll[i], rr[i]}; tot += ll[i]; } if (n == 1) { printf("%lld\n", min(s, rr[1])); continue; } sort(ll + 1, ll + 1 + n); sort(rr + 1, rr + 1 + n); long long l = ll[(n + 1) / 2], r = rr[(n + 1) / 2] + 1, ans = 0; while (l < r) { int mid = (l + r) >> 1; if (chk(mid)) ans = mid, l = mid + 1; else r = mid; } printf("%lld\n", ans); } return 0; } } // namespace flyinthesky int main() { flyinthesky::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.io.*; import java.util.*; public class D1251 { static boolean check(pair a[],int n,int med,long v) { long req=0;List<Integer> ind=new ArrayList<>();int c=0; for(int i=0;i<n;i++) { if(a[i].right<med) { c++; req+=a[i].left; } else if(a[i].left>med) { req+=a[i].left; } else { ind.add(med-a[i].left); } } //System.out.println(med+" "+c+" "+req+" "+ind); if(c>=(n+1)/2) return false; else if(c+ind.size()<(n+1)/2) return true; else { Collections.sort(ind); Collections.reverse(ind); int i=0,size=ind.size(); while(i<size) { if(c<n/2) { req+=med-ind.get(i); c++; } else req+=med; i++; } if(req<=v) return true; else return false; } } public static void main(String args[])throws IOException { Reader sc=new Reader(); int t=sc.nextInt(); for(int z=1;z<=t;z++) { int n=sc.nextInt(); long coins=sc.nextLong(); pair a[]=new pair[n];int max=0; for(int i=0;i<n;i++) { int l=sc.nextInt(); int r=sc.nextInt(); a[i]=new pair(l,r); max=Math.max(max,r); } int lo=1,hi=max,res=0; while(hi-lo> 1) { int mid=(hi+lo)/2; if(check(a,n,mid,coins)) { lo=mid; res=mid; } else hi=mid; //System.out.println(lo+" "+hi+" "+mid+" "+res); } if(lo>=1) { if(check(a,n,lo,coins)) res=Math.max(res,lo); } if(hi>=1) { if(check(a,n,hi,coins)) res=Math.max(res,hi); } System.out.println(res); } } static class pair { int left,right; public pair(int l,int r) { left=l; right=r; } } } 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[1024]; 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 (); } }
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 N = 2e5 + 2; vector<pair<long long, long long>> v(N); long long n, s; bool check(long long mid) { long long cnt = 0, sum = 0; vector<long long> tmp; for (long long i = 0; i < n; i++) { if (mid > v[i].second) sum += v[i].first; else if (mid <= v[i].first) { sum += v[i].first; cnt++; } else tmp.push_back(v[i].first); } long long need = max(0LL, (n + 1) / 2 - cnt); if (need > tmp.size()) return false; for (long long i = 0; i < tmp.size(); i++) { if (i < tmp.size() - need) sum += tmp[i]; else sum += mid; } return sum <= s; } signed main() { std ::ios_base ::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; long long t; cin >> t; while (t--) { cin >> n >> s; v.resize(n); for (long long i = 0; i < n; i++) cin >> v[i].first >> v[i].second; sort((v).begin(), (v).end()); long long l = 1, r = 1e9 + 5; while (l < r - 1) { long long mid = (l + r) / 2; if (check(mid)) l = mid; else r = mid; } cout << l << "\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.util.*; public class Main { static FastReader in; static PrintWriter out; static void solve() { int n = in.nextInt(); long s = in.nextLong(); long[][] a = new long[n][2]; long l = (long) 1e9, r = 1; for (int i = 0; i < n; i++) { a[i][0] = in.nextLong(); a[i][1] = in.nextLong(); l = Math.min(l, a[i][0]); r = Math.max(r, a[i][1]); s -= a[i][0]; } Arrays.sort(a, new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { if (o1[0] == o2[0]) { return Long.compare(o1[1], o2[1]); } return Long.compare(o1[0], o2[0]); } }); while (l < r) { long m = (l + r + 1) >> 1; // out.println(m); long s1 = s; int cnt = 0; for (int i = n - 1; i >= 0 && cnt < n / 2 + 1; i--) { if (a[i][1] >= m) { if (a[i][0] < m) { s1 -= m - a[i][0]; } cnt++; } } if (s1 < 0 || cnt < n / 2 + 1) { r = m - 1; } else { l = m; } } out.println(l); } public static void main(String[] args) { in = new FastReader(System.in); // in = new FastReader(new FileInputStream("input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream("output.txt")); int q = in.nextInt(); while (q-- > 0) solve(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
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.InputStreamReader; import java.io.IOException; import java.util.*; import java.lang.Math; public class Solution { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static long mod = 998244353; public static void main(String[] args) throws IOException { Solution sol = new Solution(); st = new StringTokenizer(br.readLine()); int q = Integer.parseInt(st.nextToken()); for(int i = 0; i<q; i++){ sol.solve(); } } private void solve() throws IOException { // Read inputs st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); long s = Long.parseLong(st.nextToken()); int[][] sal = new int[n][2]; int R, L; for(int i = 0; i<n; i++) { st = new StringTokenizer(br.readLine()); sal[i][0] = Integer.parseInt(st.nextToken()); sal[i][1] = Integer.parseInt(st.nextToken()); } Arrays.sort(sal, (int[] a, int[] b) -> a[0]-b[0]); L = sal[n/2][0]; Arrays.sort(sal, (int[] a, int[] b) -> a[1]-b[1]); R = sal[n/2][1]; int k = n/2 + 1; PriorityQueue<Integer> pq = new PriorityQueue(k); while(L<R){ int mid = (L+R+1)/2; pq.clear(); long out = 0; for(int[] sala : sal) { if(sala[1]>=mid){ pq.add(sala[0]); out += (long)Math.max(mid,sala[0]); if(pq.size()>k){ int next = pq.poll(); out += (long)next - Math.max(next, mid); } } else { out += (long)sala[0]; } } if (pq.size() == k && out <= s) L = mid; else R = mid-1; } System.out.println(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.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt();long s=sc.nextLong(); int[][]ranges=new int[n][2]; for(int i=0;i<n;i++) { ranges[i][0]=sc.nextInt();ranges[i][1]=sc.nextInt(); } int lo=1,hi=(int)1e9; int ans=0; while(lo<=hi) { int mid=(lo+hi)>>1; LinkedList<Integer>less=new LinkedList<Integer>(); LinkedList<Integer>more=new LinkedList<Integer>(); LinkedList<Integer>both=new LinkedList<Integer>(); for(int i=0;i<n;i++) { if(ranges[i][1]<mid) { less.add(i); } else { if(ranges[i][0]>mid) { more.add(i); } else { both.add(i); } } } if(less.size()>n/2) { hi=mid-1; continue; } if(more.size()>n/2) { lo=mid+1; continue; } long sum=0; PriorityQueue<Integer>pq=new PriorityQueue<Integer>(); for(int i:both) { pq.add(ranges[i][0]); } for(int i=0;i<(n/2)-less.size();i++) { sum+=pq.poll(); } sum+=pq.size()*1l*mid; while(!less.isEmpty()) { sum+=ranges[less.removeFirst()][0]; } while(!more.isEmpty()) { sum+=ranges[more.removeFirst()][0]; } if(sum<=s) { ans=Math.max(ans,mid); lo=mid+1; } else { hi=mid-1; } } pw.println(ans); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
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 com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class AS4 { public static void main(String[] Args){ FastReader scan=new FastReader(); int t=scan.nextInt(); StringBuilder print=new StringBuilder(); while(t-->0){ int n=scan.nextInt(); long s=scan.nextLong(); sal[] arr=new sal[n]; long la=Long.MIN_VALUE; for (int i = 0; i <n ; i++) { arr[i]=new sal(scan.nextInt(),scan.nextInt()); la=Math.max(la,arr[i].r); } Arrays.sort(arr); int lr=n/2+1; long sm=arr[n/2].l; long ans=sm; while(sm<=la){ long mid=(sm+la)/2; boolean[] vis=new boolean[n]; int mk=0; long v=0; for(int i=0;i<n;i++){ if(arr[i].r>=mid&&mk<lr){ vis[i]=true; if(arr[i].l<mid){ v+=mid; } else{ v+=arr[i].l; } mk++; } } if(mk==lr){ int flag=0; for(int j=0;j<n;j++){ if(!vis[j]){ if(arr[j].l<=mid){ v+=arr[j].l; } else{ flag=1; } } } if(flag==1||v>s){ la=mid-1; } else{ ans=mid; sm=mid+1; } } else{ la=mid-1; } } print.append(ans+"\n"); } System.out.println(print); } static class sal implements Comparable<sal>{ long l; long r; sal(long l,long r){ this.l=l; this.r=r; } @Override public int compareTo(sal o) { if(this.l>o.l){ return -1; } else if(this.l<o.l){ return 1; } else{ if(this.r>o.r){ return -1; } else{ return 1; } } } } static 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
import sys #import heapq as hq #sys.stdin = open('in', 'r') readline = sys.stdin.readline rdw = lambda: readline().split() rdwl = lambda: list(readline().split()) rdi = lambda: int(readline()) rdis = lambda: map(int, readline().split()) rdisl = lambda: list(map(int, readline().split())) rdrows = lambda cnt: [tuple(rdis()) for _ in range(cnt)] def solve(): n,s = rdis() cm = (n + 1) >> 1 a = rdrows(n) a.sort() l,r = a[n >> 1][0], 10**9 + 1 res = l while l <= r: m = (l + r) >> 1 need = 0 cnt = 0 for i in range(n-1, -1, -1): li,ri = a[i] if li >= m: need += li cnt += 1 elif cnt < cm and ri >= m: need += m cnt += 1 else: need += li if cnt >= cm and need <= s: res = m l = m + 1 else: r = m - 1 print(res) tests = 1 tests = rdi() for testnum in range(tests): solve() #n = rdi() #n,m = rdis() #a = rdisl() #op, *s = rdw() #print(*res, sep='\n') #sys.stdout.write('YES\n') #sys.stdout.write(f'{res}\n') #sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.InputMismatchException; import java.io.IOException; import java.util.AbstractCollection; import java.util.SplittableRandom; 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; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DSalaryChanging solver = new DSalaryChanging(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DSalaryChanging { public void solve(int testNumber, FastReader in, PrintWriter out) { // debug = new Debug(out); int n = in.nextInt(); long S = in.nextLong(); DSalaryChanging.Pair[] p = new DSalaryChanging.Pair[n]; long[] a = new long[n]; for (int i = 0; i < n; ++i) { p[i] = new DSalaryChanging.Pair(in.nextLong(), in.nextLong()); a[i] = p[i].L; S -= a[i]; } a = ArrayUtils.sort(a); long low = a[n / 2] - 1; long high = (long) 1e9 + 1; // debug.tr(low, high); while (high - low > 1) { long mid = (high + low) >>> 1; if (possible(p, S, mid)) { low = mid; } else { high = mid; } } while (possible(p, S, low)) ++low; out.println(Math.max(low - 1, a[n / 2])); } private boolean possible(DSalaryChanging.Pair[] p, long sum, long median) { int count = 0; int n = p.length; PriorityQueue<Long> needs = new PriorityQueue<>(); for (DSalaryChanging.Pair pair : p) { if (pair.R < median) continue; long nowCost = Math.max(0, median - pair.L); needs.add(nowCost); } while (!needs.isEmpty()) { long cur = needs.poll(); if (cur <= sum) { sum -= cur; ++count; } else break; } return count >= (n + 1) / 2; } static class Pair { long L; long R; public Pair(long l, long r) { L = l; R = r; } public String toString() { return "Pair{" + "L=" + L + ", R=" + R + '}'; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public String next() { return nextString(); } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = pread(); while (isSpaceChar(c)) c = pread(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = pread(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class ArrayUtils { public static long[] sort(long[] a) { a = shuffle(a, new SplittableRandom()); Arrays.sort(a); return a; } public static long[] shuffle(long[] a, SplittableRandom gen) { for (int i = 0, n = a.length; i < n; i++) { int ind = gen.nextInt(n - i) + i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } } }
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 + 50; struct Node { int l, r; bool operator<(const Node& b) const { return l > b.l; } }; Node a[N]; bool check(int x, int n, long long s) { int m = 0; long long sum = 0; for (int i = 1; i <= n; i++) { if (a[i].l > x) { m++; sum += a[i].l; } else { if (m < n / 2 + 1 && x <= a[i].r) { m++; sum += x; } else { sum += a[i].l; } } } return m == n / 2 + 1 && sum <= s; } int main() { int t; scanf("%d", &t); while (t--) { int n; long long s; scanf("%d%lld", &n, &s); for (int i = 1; i <= n; i++) { scanf("%d%d", &a[i].l, &a[i].r); } sort(a + 1, a + 1 + n); int l = a[n / 2 + 1].l, r = (int)1e9, ans = l; while (l <= r) { int m = (l + r) >> 1; if (check(m, n, s)) { ans = m; l = m + 1; } else { r = m - 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.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { Problems problems = new Problems(); problems.solve(); } } class Problems { Parser parser = new Parser(); void solve() { int t = parser.parseInt(); for (int i = 0; i < t; i++) { Problem problem = new Problem(); problem.solve(); } } class Problem { void solve() { int n = parser.parseInt(); long s = parser.parseLong(); List<Range> ranges = new ArrayList<>(); for (int i = 0; i < n; i++) { int l = parser.parseInt(); int r = parser.parseInt(); ranges.add(new Range(l, r)); } ranges.sort((o1, o2) -> { if(o1.l != o2.l) { return Integer.compare(o1.l, o2.l); } return Integer.compare(o1.r, o2.r); }); long l = -1; long r = 1_000_000_009; while (l + 1 < r) { long m = (l + r) / 2; if (ok(ranges, m, s)) l = m; else r = m; } System.out.println(l); } boolean ok(List<Range> ranges, long v, long s) { int size = ranges.size(); long now = 0; int count = 0; for (Range range : ranges) { if (range.r < v) { now += range.l; } else if (range.l > v) { now += range.l; count += 1; } } for (int i = size - 1; i >= 0; i--) { Range range = ranges.get(i); if (range.l > v || range.r < v) continue; if (count < (size + 1) / 2) { count += 1; now += v; } else { now += range.l; } } return count >= (size + 1) / 2 && s >= now; } class Range { int l, r; public Range(int l, int r) { this.l = l; this.r = r; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Range range = (Range) o; return l == range.l && r == range.r; } @Override public int hashCode() { return Objects.hash(l, r); } @Override public String toString() { return "Range{" + "l=" + l + ", r=" + r + '}'; } } } } class Parser { private final Iterator<String> stringIterator; private final Deque<String> inputs; Parser() { this(System.in); } Parser(InputStream in) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); stringIterator = br.lines().iterator(); inputs = new ArrayDeque<>(); } void fill() { while (inputs.isEmpty()) { if (!stringIterator.hasNext()) throw new NoSuchElementException(); inputs.addAll(Arrays.asList(stringIterator.next().split(" "))); while (!inputs.isEmpty() && inputs.getFirst().isEmpty()) { inputs.removeFirst(); } } } Integer parseInt() { fill(); if (!inputs.isEmpty()) { return Integer.parseInt(inputs.pollFirst()); } throw new NoSuchElementException(); } Long parseLong() { fill(); if (!inputs.isEmpty()) { return Long.parseLong(inputs.pollFirst()); } throw new NoSuchElementException(); } Double parseDouble() { fill(); if (!inputs.isEmpty()) { return Double.parseDouble(inputs.pollFirst()); } throw new NoSuchElementException(); } String parseString() { fill(); return inputs.removeFirst(); } }
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 N = 2000005; const long long M = 1e9 + 7; int n; long long s; vector<pair<int, int> > v; vector<int> a, b; bool check(int x) { vector<int> t; int a = 0, b = 0; long long ss = 0; for (int i = 0; i < n; i++) { if (v[i].second < x) { a++; ss += v[i].first; } else if (v[i].first > x) { b++; ss += v[i].first; } else t.push_back(i); } for (auto i : t) { if (a < n / 2) a++, ss += v[i].first; else b++, ss += x; } return (a == n / 2 && ss <= s); } void solve() { v.clear(); a.clear(); b.clear(); cin >> n >> s; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; v.push_back(make_pair(x, y)); a.push_back(x); b.push_back(y); } sort((a).begin(), (a).end()); sort((b).begin(), (b).end()); sort((v).begin(), (v).end()); int low = a[n / 2], high = b[n / 2]; while (high - low > 1) { int mid = (low + high) >> 1; if (check(mid)) low = mid; else high = mid; } if (check(high)) cout << high << "\n"; else cout << low << "\n"; return; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; cin >> t; for (int i = 1; i <= t; i++) { 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.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; static int n, l[], r[]; static long s; static boolean f(int mid) { long sum = 0; int cnt = 0; for(int i = 0;i < n;i++) { if (r[i] < mid) { cnt++; sum += l[i]; } if (l[i] >= mid) { sum += l[i]; } } ArrayList<pair> a = new ArrayList<>(); for(int i = 0;i < n;i++) { if (l[i] < mid && r[i] >= mid) a.add(new pair(l[i], r[i])); } Collections.sort(a, new pair()); for(pair i : a) { if (cnt < n / 2) { sum += i.l; cnt++; }else sum += mid; } if (cnt > n / 2) return false; return sum <= s; } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pw = new PrintWriter(System.out); for(int test = sc.nextInt();test > 0;test--) { n = sc.nextInt(); s = sc.nextLong(); l = new int[n]; r = new int [n]; for(int i = 0;i < n;i++) { l[i] = sc.nextInt(); r[i] = sc.nextInt(); } int left = -1; int right = inf; while(right - left > 1) { int mid = (left + right) / 2; if (f(mid)) left = mid; else right = mid; } pw.println(left); } pw.close(); } static Scanner sc; static PrintWriter pw; static class Scanner { BufferedReader br; StringTokenizer st = new StringTokenizer(""); Scanner(InputStream in) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(in)); } Scanner(String in) throws FileNotFoundException { br = new BufferedReader(new FileReader(in)); } String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } } class pair implements Comparator<pair>{ int l, r; pair(int l, int r) { this.l = l; this.r = r; } pair() {} @Override public int compare(pair o1, pair o2) { return Integer.compare(o1.l, o2.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 sys,os,io input = sys.stdin.readline PI = 3.141592653589793238460 INF = float('inf') MOD = 1000000007 # MOD = 998244353 def bin32(num): return '{0:032b}'.format(num) def add(x,y): return (x+y)%MOD def sub(x,y): return (x-y+MOD)%MOD def mul(x,y): return (x*y)%MOD def gcd(x,y): if y == 0: return x return gcd(y,x%y) def lcm(x,y): return (x*y)//gcd(x,y) def power(x,y): res = 1 x%=MOD while y!=0: if y&1 : res = mul(res,x) y>>=1 x = mul(x,x) return res def mod_inv(n): return power(n,MOD-2) def prob(p,q): return mul(p,power(q,MOD-2)) def ii(): return int(input()) def li(): return [int(i) for i in input().split()] def ls(): return [i for i in input().split()] for t in range(ii()): t+=1 n,s = li() store = [] l = [0 for i in range(n)] r = [0 for i in range(n)] for i in range(n): l[i] , r[i] = li() store.append([l[i] , r[i]]) store.sort() store.reverse() l.sort() L = l[n//2] R = s + 1 # print(L , R) # print(store ) while R-L > 1: # print(L , R) mid = (L + R + 1)//2 sal = 0 cnt = 0 for i in range(n): if store[i][0] <= mid <= store[i][1] : if cnt < n //2 + 1: cnt+=1 sal += mid else: sal+=store[i][0] elif store[i][0] > mid: cnt+=1 sal+=store[i][0] elif store[i][1] < mid: sal+=store[i][0] if sal <= s and cnt == n//2 + 1: 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
/* Rajkin Hossain */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class D{ FastInput k = new FastInput(System.in); //FastInput k = new FastInput("C:/Users/rajkin.h/Desktop/input.txt"); FastOutput z = new FastOutput(); int n; long s; Pair [] cor; long check(long mid) { long sum = 0; int left = 0; int right = 0; boolean first = true; for(int i = 0; i<cor.length; i++) { Pair p = cor[i]; if(p.right < mid) { sum += p.left; left++; } else if(p.left > mid) { sum += p.left; right++; } } if(left > n/2) { return Long.MAX_VALUE; // take smaller mid } if(right > n/2) { // take bigger mid return 0; } int lR = (n/2) - left; for(int i = 0; i<cor.length; i++) { Pair p = cor[i]; if(p.left <= mid && p.right >= mid) { if(lR > 0) { lR--; sum += p.left; } else { sum += mid; } } } return sum; } void startAlgo() { long low = 1; long high = (long)(1e9) + 1; long ans = 0; while(low <= high) { if(low == high) { long sum = check(low); if(sum <= s) { ans = low; } break; } long mid = (low + high) / 2; long sum = check(mid); if(sum > s) { high = mid; } else { ans = mid; low = mid + 1; } } z.println(ans); } void startProgram() { int q = k.nextInt(); while(q-->0) { n = k.nextInt(); s = k.nextLong(); cor = new Pair[n]; for(int i = 0; i<n; i++) { cor[i] = new Pair(k.nextInt(), k.nextInt()); } Arrays.sort(cor); startAlgo(); } z.flush(); System.exit(0); } class Pair implements Comparable<Pair>{ Integer left, right; public Pair(int left, int right) { super(); this.left = left; this.right = right; } @Override public int compareTo(Pair arg0) { return this.left - arg0.left; } } public static void main(String [] args) throws IOException { new Thread(null, new Runnable(){ public void run(){ try{ new D().startProgram(); } catch(Exception e){ e.printStackTrace(); } } },"Main",1<<28).start(); } /* MARK: FastInput and FastOutput */ class FastInput { BufferedReader reader; StringTokenizer tokenizer; FastInput(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); } FastInput(String path){ try { reader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } String next() { return nextToken(); } String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } boolean hasNext(){ try { return reader.ready(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.valueOf(nextToken()); } double nextDouble() { return Double.valueOf(nextToken()); } } class FastOutput extends PrintWriter { FastOutput() { super(new BufferedOutputStream(System.out)); } public void debug(Object...obj) { System.err.println(Arrays.deepToString(obj)); } } }
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 os import sys from atexit import register from io import BytesIO sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') t = int(input()) def check(v,arr,s,n): l1 = 0 l2 = 0 num = 0 cand = [] for i in range(n): if arr[i][0]>v: l2 += 1 num += arr[i][0] elif arr[i][1]<v: l1 += 1 num += arr[i][0] else: cand.append(i) if l1>=n/2+1 or l2>=n/2+1: return False l3 = max(n/2-l1,0) for i in cand[:l3]: num += arr[i][0] for i in cand[l3:]: num += v # print l1,l2,l3 # print v,num,s if num <=s: return True else: return False for _ in range(t): n,s = map(int,input().split(" ")) tmp = [] for _l in range(n): l,r = map(int,input().split(" ")) tmp.append((l,r)) tmp.sort() low,high = tmp[n/2][0],int(1e9+1) ans = [] while low<=high: mid = (low+high)/2 if check(mid,tmp,s,n): ans.append(mid) low = mid+1 else: high = mid-1 print max(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; typedef int (*uniopi)(int); typedef long long (*uniopl)(long long); typedef int (*binopi)(int, int); typedef long long (*binopl)(long long, long long); typedef int (*tupopi)(int, int, int); typedef long long (*tupopl)(long long, long long, long long); const long double PI = acos(0) * 2; const int INF = 0x3f2f1f0f; const long long LINF = 1ll * INF * INF; int X4[] = {-1, 0, 1, 0}, Y4[] = {0, -1, 0, 1}; int X8[] = {-1, -1, -1, 0, 1, 1, 1, 0}, Y8[] = {-1, 0, 1, 1, 1, 0, -1, -1}; template <typename T> inline bool uax(T& a, T b) { return a < b ? (a = b, 1) : 0; } template <typename T> inline bool uin(T& a, T b) { return a > b ? (a = b, 1) : 0; } template <typename T1, typename T2> istream& operator>>(istream& is, pair<T1, T2>& p) { return is >> p.first >> p.second; } template <typename T1, typename T2> ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << '(' << p.first << ", " << p.second << ")"; } template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { for (int i = 0; i < (int)v.size(); i++) { os << v[i]; if (i + 1 < (int)v.size()) os << ' '; } return os; } const int MAX_N = 2e5 + 20; int A[MAX_N], B[MAX_N], AB[MAX_N], NA, NB, NAB; long long L[MAX_N], R[MAX_N], N; int ispos(long long m, long long s) { int n = N, h = (1 + n) / 2; NA = NB = NAB = 0; for (int i = 0; i < (n); i++) { if (L[i] <= m) { if (R[i] >= m) AB[NAB++] = i; else A[NA++] = i; } else B[NB++] = i; } if (NA >= h) return 0; if (NB >= h) return 1; long long cost = 0; for (int j = 0; j < (NA); j++) cost += L[A[j]]; for (int j = 0; j < (NB); j++) cost += L[B[j]]; sort(AB, AB + NAB, [](const int a, const int b) { return L[a] < L[b]; }); for (int j = 0; j < (h - 1 - NA); j++) cost += L[AB[j]]; cost += (h - NB) * m; return cost <= s; } int main() { ios::sync_with_stdio(0); cin.tie(nullptr); cout << std::setprecision(10); cout << fixed; int q; cin >> q; while (q--) { long long s; cin >> N >> s; for (int i = 0; i < (N); i++) cin >> L[i] >> R[i]; long long bl = *min_element(L, L + N), br = *max_element(R, R + N), bm; while (bl < br) { bm = (bl + br + 1) >> 1; if (ispos(bm, s)) bl = bm; else br = bm - 1; } cout << bl << 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.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collections; 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 { public void solve(int testNumber, InputReader in, PrintWriter out) { int T = in.nextInt(); for (int iter = 0; iter < T; iter++) { int N = in.nextInt(); long S = in.nextLong(); ArrayList<Seg> segments = new ArrayList<>(); for (int i = 0; i < N; i++) { long l = in.nextLong(); long r = in.nextLong(); S -= l; segments.add(new Seg(l, r)); } Collections.sort(segments, new Comparator<Seg>() { public int compare(Seg seg, Seg t1) { return Long.compare(t1.l, seg.l); } }); int low = 1; int high = (int) (1e9); while (low < high) { int mid = (low + high + 1) / 2; long tempS = S; int cnt = 0; for (Seg s : segments) { if (s.l >= mid) { cnt++; } else if (s.r >= mid) { tempS -= mid - s.l; cnt++; } if (tempS < 0) { cnt--; break; } } if (cnt >= (N + 1) / 2) { low = mid; } else { high = mid - 1; } } out.println(low); } } class Seg { long l; long r; Seg(long l, long r) { this.l = l; this.r = r; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
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.*; public class Main{ public static void main (String args[])throws IOException{ Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(), r=1, l=(int)1e9, mid; long s = sc.nextLong(); Pair arr[] = new Pair[n]; for(int i=0; i<n; i++) { arr[i]= new Pair(sc.nextInt(), sc.nextInt()); l=min(arr[i].x, l); r=max(arr[i].y, r); } r++; while(l+1<r) { //out.println(l+" "+r); mid=l+(r-l)/2; if(check(arr, s, n, mid)) l=mid; else r=mid; } out.println(l); out.flush(); } } static boolean check(Pair[] arr,long s,int n,int mid) { int cnt=0; ArrayList<Integer> arr1 = new ArrayList(); for(int i=0; i<n; i++) { if(arr[i].x>=mid) { cnt++; s-=arr[i].x; } else if(arr[i].y<mid) s-=arr[i].x; else arr1.add(arr[i].x); } int need=max(n/2+1-cnt,0); if(arr1.size()<need) return false; Collections.sort(arr1); for(int i=0; i<arr1.size()-need; i++) s-=arr1.get(i); s-=(long)need*mid; if(s<0) return false; return true; } static void print(int[] arr) { for(int i=0; i<arr.length; i++) System.out.print(arr[i]+" "); System.out.println(); } public static int abs(int x) {return ((x > 0) ? x : -x);} public static int max(int a, int b) {return Math.max(a, b);} public static int min(int a, int b) {return Math.min(a, b);} static int[] primeGenerator(int num) { int length=0, arr[]=new int[num], a=num, factor=1; if(num%2==0) { while(num%2==0) { num/=2; factor*=2; } arr[length++]=factor; } for(int i=3; i*i<=a; i++) { factor=1; if(num%i==0) { while(num%i==0) { num/=i; factor*=i; } arr[length++]=factor; } } if(num>1) arr[length++]=num; return Arrays.copyOfRange(arr, 0, length); } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop 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 class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } } class Pair{ int x; int y; Pair(int a, int b){ x=a; y=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
import sys import math from collections import defaultdict from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : map(int, input().split()) def write(*args, sep="\n"): for i in args: sys.stdout.write("{}".format(i) + sep) INF = float('inf') MOD = int(1e9 + 7) for t in range(int(input())): n, x= read() lr = sorted([list(read()) for i in range(n)], reverse = True) s = 0 e = 1<<32 while s <= e: m = (s + e) // 2 money = 0 a, b, c = [], [], [] for l, r in lr: if l > m: c.append((l, r)) money += l elif r < m: a.append((l, r)) money += l else: b.append((l, r)) if money > x or len(a) >= n//2 + 1: e = m - 1 continue need = n//2 + 1 - len(c) cnt = 0 #print(money, a,b,c,m, sep="\n") for l, r in b: #print(money, cnt, need, l, r) if cnt < need: money += m cnt += 1 else: money += l if money <= x: s = m + 1 else: e = m - 1 write(e)
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 mx = 200005; bool comparator(pair<long long, long long> A, pair<long long, long long> B) { return A.first < B.first; } int main() { ios::sync_with_stdio(0); long long q; cin >> q; while (q--) { long long n, s; long long l; long long r; long long ans = 0; vector<pair<long long, long long>> intv; vector<long long> Min, Max; cin >> n >> s; for (int i = 1; i <= n; ++i) { int l, r; cin >> l >> r; intv.push_back(make_pair(l, r)); Min.push_back(l); Max.push_back(r); } sort(Min.begin(), Min.end()); sort(Max.begin(), Max.end()); l = Min[n / 2]; r = Max[n / 2]; while (l <= r) { long long m = (l + r) / 2; long long cost = m; long long cntLeft = 0; long long cntRight = 0; vector<pair<int, int>> both; for (int i = 0; i < n; ++i) { if (intv[i].second < m) cost += intv[i].first, ++cntLeft; else if (intv[i].first > m) cost += intv[i].first, ++cntRight; else if (intv[i].first <= m && intv[i].second >= m) both.push_back(intv[i]); } sort(both.begin(), both.end(), comparator); for (int i = 0; i < both.size() && cntLeft < n / 2; ++i) cost += both[i].first, ++cntLeft; for (int i = both.size() - 1; i >= 0 && cntRight < n / 2; --i) cost += m, ++cntRight; if (cost <= s) { ans = max(ans, m); l = m + 1; } else { r = m - 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
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 2; pair<long long, long long> sal[N]; bool solve(long long m, long long to, long long n) { long long sum = 0; int cnt = 0, rem, i; vector<long long> ss; for (i = 0; i < n; i++) { if (sal[i].second < m) sum += sal[i].first; else if (sal[i].first >= m) sum += sal[i].first, cnt++; else ss.push_back(sal[i].first); } rem = max(0LL, ((n + 1) / 2) - cnt); if (rem > ss.size()) return false; for (i = ss.size() - 1; i > -1; i--) { if (rem > 0) sum += m, rem--; else sum += ss[i]; } return (sum <= to ? true : false); } int main() { long long t, n, i, lo, hi, to, mid; scanf("%lld", &t); while (t--) { scanf("%lld %lld", &n, &to); for (i = 0; i < n; i++) scanf("%lld %lld", &sal[i].first, &sal[i].second); sort(sal, sal + n); lo = 1, hi = to; while (lo <= hi) { mid = (lo + hi) / 2; if (solve(mid, to, n)) lo = mid + 1; else hi = mid - 1; } printf("%lld\n", lo - 1); } 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; using ll = long long; struct par { ll l; ll r; }; int n; ll s; par mas[200100]; bool cmp(par a, par b) { return (a.l < b.l); } bool good(ll m) { vector<par> grp1; vector<par> grp2; vector<par> grp3; for (int i = 0; i < n; i++) { if (mas[i].r < m) grp1.push_back(mas[i]); else if (m <= mas[i].l) grp2.push_back(mas[i]); else grp3.push_back(mas[i]); } int rem = max(0, (n + 1) / 2 - (int)grp2.size()); if (rem > grp3.size()) return false; ll sum = 0; for (auto el : grp1) sum += el.l; for (auto el : grp2) sum += el.l; if (grp3.size() > 0) sort(grp3.begin(), grp3.end(), cmp); for (int i = 1; i <= rem; i++) sum += m; for (int i = 0; i < grp3.size() - rem; i++) sum += grp3[i].l; return (sum <= s); } ll bin_s() { ll l = 1, r = 1e9; ll m; while (l < r) { m = (l + r + 1) / 2; if (good(m)) l = m; else r = m - 1; } return l; } void solve() { cin >> n >> s; for (int i = 0; i < n; i++) { cin >> mas[i].l >> mas[i].r; } ll med = bin_s(); cout << med << '\n'; return; } int main() { ios_base::sync_with_stdio(0); cout.tie(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
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class D1251 { public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution s = new Solution(); int tc; tc = in.nextInt(); s.solve(tc, in, out); out.close(); } static class Solution { static int n; static Seg[] arr; public void solve(int tc, InputReader in, PrintWriter out){ while(tc-- > 0){ n = in.nextInt(); Long s; s = in.nextLong(); arr = new Seg[n]; for(int i = 0; i < n; i++){ arr[i] = new Seg(); arr[i].l = in.nextInt(); arr[i].r = in.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; } } out.println(ans); } } static class Seg { int l; int r; } static class SortByLeft implements Comparator<Seg> { public int compare(Seg a, Seg b){ return a.l - b.l; } } 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 InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public Long nextLong() { return Long.parseLong(next()); } } }
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 + 5; int t, n; long long s; pair<int, int> x[N]; bool valid(int mid) { int cnt = (n + 1) / 2; long long sum = s; for (int i = n - 1; ~i; --i) { if (cnt && mid <= x[i].second) --cnt, sum -= max(x[i].first, mid); else sum -= x[i].first; } return sum >= 0 && !cnt; } int solve() { int l = 0, r = 1e9 + 5; while (l < r) { int mid = l + (r - l + 1) / 2; if (valid(mid)) l = mid; else r = mid - 1; } return l; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; while (t--) { cin >> n >> s; for (int i = 0; i < n; ++i) cin >> x[i].first >> x[i].second; sort(x, x + n, [](pair<int, int>& a, pair<int, int>& b) { return a.first < b.first; }); cout << solve() << '\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 sys readline = sys.stdin.readline read = sys.stdin.read ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): n, s = nm() m = (n + 1)//2 emp = [tuple(nm()) for _ in range(n)] emp.sort(reverse=True) ok = emp[m-1][0] ng = s + 1 while ng - ok > 1: x = (ok + ng) // 2 cur = 0 t = 0 for l, r in emp: if r >= x and t < m: cur += max(x, l) t += 1 else: cur += l if t == m and cur <= s: ok = x else: ng = x print(ok) return # solve() T = ni() for _ in range(T): solve()
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; long long n, s; vector<pair<long long, long long> > r; bool comp(pair<long long, long long> a, pair<long long, long long> b) { return a.first < b.first; } bool poss(long long cost) { long long i; long long tc = 0; vector<pair<long long, long long> > rem; long long cl = 0, cr = 0; for (i = (0); i < (n); i++) { if (r[i].first > cost) { tc += r[i].first; cr++; } else if (r[i].second < cost) { tc += r[i].first; cl++; } else { rem.push_back(r[i]); } } if ((cl >= ((n + 1) / 2)) || (cr >= ((n + 1) / 2))) { return false; } sort((rem).begin(), (rem).end(), comp); long long remm = ((n + 1) / 2 - cl); long long tot = (n - cl - cr - remm + 1); for (i = (0); i < (remm - 1); i++) { tc += (rem[i].first); } tc += (tot * cost); return (tc <= s); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); long long i, j, k; long long t; cin >> t; while (t--) { cin >> n >> s; r.clear(); r.resize(n); for (i = (0); i < (n); i++) { cin >> r[i].first >> r[i].second; } vector<long long> v1; for (i = (0); i < (n); i++) v1.push_back(r[i].first); sort((v1).begin(), (v1).end()); long long l = v1[n / 2]; vector<long long> v2; for (i = (0); i < (n); i++) v2.push_back(r[i].second); sort((v2).begin(), (v2).end()); long long r = v2[n / 2]; if (l > r) { } while ((r - l) > 1) { long long mid = ((l + r) / 2); if (poss(mid)) { l = mid; } else { r = mid - 1; } } if (poss(r)) cout << r << '\n'; else 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
import java.util.*; import java.io.*; public class Pmain0 { static int t, n; static long s; static Pair a[]; static boolean v[]; static FastReader input = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static boolean p(int m) { int more = (n + 1) / 2; long tmps = s; for (int i = n - 1; i >= 0 && more > 0; i--) { if (a[i].y >= m) { tmps -= Math.max(a[i].x, m); more--; v[i] = true; } } int less = n / 2; for (int i = 0; i < n && less > 0; i++) { if (a[i].x <= m && !v[i]) { tmps -= a[i].x; less--; v[i] = true; } } if (tmps < 0 || more != 0) { return false; } return true; } public static void main(String[] args) throws NumberFormatException, IOException { t = input.nextInt(); while (t-- > 0) { n = input.nextInt(); s = input.nextLong(); a = new Pair[n]; for (int i = 0; i < n; i++) { a[i] = new Pair(input.nextInt(), input.nextInt()); } Arrays.sort(a); int l = 0; int r = (int) 1e9; while (l < r) { int mid = l + (r - l + 1) / 2; v = new boolean[n]; if (p(mid)) { l = mid; } else { r = mid - 1; } } out.println(l); } out.flush(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (this.x == o.x) return this.y - o.y; return this.x - o.x; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; str = br.readLine(); 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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.util.Comparator; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DSalaryChanging solver = new DSalaryChanging(); solver.solve(1, in, out); out.close(); } static class DSalaryChanging { static int n; static long money; static DSalaryChanging.Employee[] arr; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = sc.nextInt(); while (q-- > 0) { n = sc.nextInt(); money = sc.nextLong(); arr = new DSalaryChanging.Employee[n]; for (int i = 0; i < n; i++) arr[i] = new DSalaryChanging.Employee(sc.nextInt(), sc.nextInt()); Arrays.sort(arr, new Comparator<DSalaryChanging.Employee>() { public int compare(DSalaryChanging.Employee o1, DSalaryChanging.Employee o2) { if (o1.low != o2.low) return o1.low - o2.low; return o1.high - o2.high; } }); //pw.println(Arrays.toString(arr)); pw.println(bs()); } } private int bs() { int l = 1, h = (int) 1e9; while (l <= h) { int mid = l + (h - l) / 2; if (check(mid)) l = mid + 1; else h = mid - 1; } return l - 1; } private boolean check(long mid) { long clone = money; for (int i = 0; i < arr.length; i++) clone -= arr[i].low; int req = (n + 1) / 2; for (int i = arr.length - 1; i >= 0 && req > 0; i--) { if (arr[i].high >= mid) { req--; clone -= Math.max(0, mid - arr[i].low); } } return clone >= 0 && req == 0; } static class Employee { int low; int high; Employee(int low, int high) { this.low = low; this.high = high; } public String toString() { return low + " " + high; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
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> #pragma GCC optimize("O3", "unroll-loops") #pragma GCC target("avx2") using namespace std; template <class T, class U> inline void checkmin(T &x, U y) { if (y < x) x = y; } template <class T, class U> inline void checkmax(T &x, U y) { if (y > x) x = y; } template <class T, class U> inline bool ifmax(T &x, U y) { if (y > x) return x = y, true; return false; } template <class T, class U> inline bool ifmin(T &x, U y) { if (y < x) return x = y, true; return false; } template <class T> inline void sort(T &a) { sort(a.begin(), a.end()); } template <class T> inline void rsort(T &a) { sort(a.rbegin(), a.rend()); } template <class T> inline void reverse(T &a) { reverse(a.begin(), a.end()); } template <class T, class U> inline istream &operator>>(istream &str, pair<T, U> &p) { return str >> p.first >> p.second; } template <class T> inline istream &operator>>(istream &str, vector<T> &a) { for (auto &i : a) str >> i; return str; } template <class T> inline T sorted(T a) { sort(a); return a; } void read(int &x) { static char c; while ((c = getchar()) >= '0') x = (x << 3) + (x << 1) + (c - '0'); } void read(long long &x) { static char c; while ((c = getchar()) >= '0') x = (x << 3) + (x << 1) + (c - '0'); } void print(int x) { if (x >= 10) { print(x / 10); putchar(x % 10 + '0'); } else { putchar(x + '0'); } } void solve() { int n = 0; long long second = 0; read(n); read(second); vector<int> l(n), r(n), ind(n); for (int i = 0; i < n; ++i) read(l[i]), read(r[i]), ind[i] = i; sort(ind.begin(), ind.end(), [&](int i, int j) { return l[i] > l[j]; }); int left = 0, right = 1e9 + 1; while (right - left > 1) { int m = right + left >> 1; long long check = 0, cnt = n / 2 + 1; for (auto i : ind) { int add = l[i]; if (r[i] >= m && cnt) { --cnt; checkmax(add, m); } check += add; } if (cnt || check > second) right = m; else left = m; } print(left); putchar('\n'); } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(94385); int t = 0; read(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; struct node { int l, r; friend bool operator<(node a, node b) { return a.l < b.l; } } ee[200005]; int get(int n, int x, long long k) { long long sum = 0; int cnt = n / 2 + 1; for (int i = n; i >= 1; i--) { if (ee[i].l <= x && ee[i].r >= x && cnt) { sum += x; cnt--; } else { sum += ee[i].l; if (ee[i].l > x) cnt--; } } if (sum > k || cnt > 0) return 0; else return 1; } int main() { int n, t; long long k; scanf("%d", &t); while (t--) { scanf("%d%lld", &n, &k); int maxs = 0; for (int i = 1; i <= n; i++) { scanf("%d%d", &ee[i].l, &ee[i].r); maxs = max(maxs, max(ee[i].l, ee[i].r)); } sort(ee + 1, ee + n + 1); int l = ee[n / 2 + 1].l, r = maxs, ans = l; while (l <= r) { int mid = (l + r) >> 1; if (get(n, mid, k)) { l = mid + 1; ans = mid; } else { r = mid - 1; } } printf("%d\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
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; struct Node { long long l, r; } dict[maxn]; long long N, s; inline bool check(long long mid) { long long cnt = 0, cost = 0; priority_queue<long long, vector<long long>, greater<long long>> q; for (int i = 1; i <= N; ++i) { cost += dict[i].l; if (dict[i].l < mid && dict[i].r >= mid) { q.push(mid - dict[i].l); } else if (dict[i].l >= mid) { ++cnt; } } while (!q.empty() && cnt < (N + 1) / 2) { cost += q.top(); q.pop(); cnt++; } return cost <= s && cnt >= (N + 1) / 2; } int main() { int T; scanf("%d", &T); while (T--) { scanf("%lld%lld", &N, &s); for (int i = 1; i <= N; ++i) { scanf("%lld%lld", &dict[i].l, &dict[i].r); } long long l = 1, r = 1e14, ans; while (l <= r) { long long 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
#!/usr/bin/env python3 import sys INF = 10**9 sys.setrecursionlimit(10**8) input = sys.stdin.buffer.readline t = int(input()) for i in range(t): n, s = [int(item) for item in input().split()] lr = [] for j in range(n): l, r = [int(item) for item in input().split()] lr.append((l, r)) lft = 0; rgt = 10**9+1 while rgt - lft > 1: mid = (lft + rgt) // 2 minimum_cost = 0 takable = [] for l, r in lr: minimum_cost += l if mid <= r: takable.append(max(l - mid, 0) - l) if len(takable) < (n // 2 + 1): rgt = mid continue takable.sort() cost = sum(takable[:n//2 + 1]) + minimum_cost + mid * (n // 2 + 1) if cost <= s: lft = mid else: rgt = mid print(lft)
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; struct Sal { int32_t min, max; }; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int32_t tests; cin >> tests; for (int32_t test = 0; test < tests; test++) { int32_t count; int64_t total; cin >> count >> total; Sal sals[count]; int32_t max_sal = 1000000001; int32_t min_sal = 0; for (int32_t i = 0; i < count; i++) { cin >> sals[i].min >> sals[i].max; if (sals[i].max > max_sal) { max_sal = sals[i].max; } if (sals[i].min < min_sal) { min_sal = sals[i].min; } } sort(sals, sals + count, [](const Sal& s1, const Sal& s2) { return s1.min < s2.min; }); while (max_sal - min_sal > 1) { bool possible = true; int32_t mid_sal = (max_sal + min_sal) / 2; int64_t sum = 0; int32_t count_left = (count + 1) / 2; vector<int32_t> undetermined; for (int32_t i = 0; i < count; i++) { if (mid_sal > sals[i].max) { sum += sals[i].min; } else if (mid_sal <= sals[i].min) { sum += sals[i].min; count_left--; } else { undetermined.push_back(i); } } count_left = max(0, count_left); if ((int32_t)undetermined.size() < count_left) { possible = false; } else { for (int32_t i = 0; i < (int32_t)undetermined.size(); i++) { if (i < (int32_t)undetermined.size() - count_left) { sum += sals[undetermined[i]].min; } else { sum += mid_sal; } } if (sum > total) { possible = false; } } if (possible) { min_sal = mid_sal; } else { max_sal = mid_sal; } } cout << min_sal << "\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 double pai = acos(-1); const double eps = 1e-10; const long long mod = 1e9 + 7; const int MXN = 1e6 + 5; long long a[MXN], b[MXN]; int vis[MXN]; int n; long long s; struct no { long long l, r, p; }; bool operator<(const no &x, const no &y) { return x.l > y.l; } bool check(long long mid) { vector<no> v; for (int i = 1; i <= n; i++) { if (b[i] >= mid) v.push_back(no{a[i], b[i], i}); vis[i] = 0; } if ((int)v.size() < n / 2 + 1) return 0; sort(v.begin(), v.end()); while ((int)v.size() > n / 2 + 1) v.pop_back(); long long need = 0; for (auto i : v) need += max(mid, i.l), vis[i.p] = 1; for (int i = 1; i <= n; i++) if (!vis[i]) need += a[i]; return need <= s; } void Main(int avg) { cin >> n >> s; for (int i = 1; i <= n; i++) { int sa, sb; scanf("%d %d", &sa, &sb); a[i] = sa, b[i] = sb; } long long l = 1, r = 1e9, ans; while (l <= r) { long long mid = (l + r) / 2; if (check(mid)) ans = mid, l = mid + 1; else r = mid - 1; } cout << ans << '\n'; } int main() { int cas; cin >> cas; for (int i = 1; i <= cas; i++) Main(i); 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; template <class T> int read(T& x) { int c = getchar(), f = (x = 0); while (~c && (c < 48 || c > 57)) { if (c == '-') { f = 1; } c = getchar(); } if (!~c) { return 0; } while (c > 47 && c < 58) { x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); } if (f) { x = -x; } return 1; } template <class T, class U> inline int read(T& a, U& b) { return read(a) && read(b); } template <class T, class U, class V> inline int read(T& a, U& b, V& c) { return read(a) && read(b) && read(c); } inline int read(double& _, double& __) { return scanf("%lf%lf", &_, &__); } inline int read(char* _) { return scanf("%s", _); } inline int read(double& _) { return scanf("%lf", &_); } inline void print(long long _) { printf("%lld ", _); } inline void print(int _) { printf("%d ", _); } inline void println(long long _) { printf("%lld\n", _); } inline void println(int _) { printf("%d\n", _); } template <class T> inline void cmax(T& _, T __) { if (_ < __) _ = __; } template <class T> inline void cmin(T& _, T __) { if (_ > __) _ = __; } const int maxn = 2e5 + 10, INF = 0x3f3f3f3f; const long long LINF = (long long)INF << 32 | INF; long long mid; struct Node { long long L, R; Node(long long a = 0, long long b = 0) : L(a), R(b) {} bool operator<(const Node& T) const { return L > T.L; } } a[maxn]; long long T, n, tot, L = 0, R = INF; bool Judge() { int cnt = 0; long long tmp = tot; for (int i = 1; i <= (n); i++) { if (a[i].L >= mid) { ++cnt; continue; } if (a[i].R < mid) continue; if (tmp < mid - a[i].L) break; tmp -= mid - a[i].L; ++cnt; } return cnt >= (n + 1) / 2; } int main() { int T; read(T); while (T--) { read(n, tot); L = 0, R = tot; for (int i = 1; i <= (n); i++) { read(a[i].L, a[i].R); tot -= a[i].L; } sort(a + 1, a + n + 1); while (L < R) { mid = L + (R - L + 1) / 2; if (Judge()) L = mid; else R = mid - 1; } printf("%lld\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
import bisect import os, sys, atexit from io import BytesIO, StringIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline _OUTPUT_BUFFER = StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def solve(): t = int(input()) for _ in range(t): n,s = map(int,input().split()) ranges = [] for _ in range(n): l,r = map(int,input().split()) ranges.append([r,l]) ranges.sort() sumli =[0] li,ri=[],[] for r,l in ranges: sumli.append(sumli[-1]+l) li.append(l) ri.append(r) left,right = 0,ri[n//2] # print(ri,li) while left!=right: mid = (left+right+1)//2 total = 0 # print ("binaries",left,mid,right) riIndex = bisect.bisect_left(ri,mid) if (n-riIndex>n//2): total += sumli[riIndex] # print (total) sortedLi = sorted(li[riIndex:]) # print ("sorted li ",sortedLi) liIndex = bisect.bisect_left(sortedLi,mid) total+=sum(sortedLi[liIndex:]) # print (total) countN2 = max((n+1)//2-(len(sortedLi)-liIndex),0) total += countN2*mid+sum(sortedLi[:liIndex-countN2]) # print (total) if total>s: right = mid-1 else: if countN2==0: left = sortedLi[-(n//2+1)] else: left = mid else: right = mid-1 print ((left+right)//2) try: solve() except Exception as e: print (e) # solve()
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
def main(): def getLowestPossibleMedian(lr,n): lr.sort(key=lambda x:x[0]) # sort by l asc return lr[n//2][0] def checkPossibleMedian(lr,guess,n,s): potentialUpper=[] # potential candidates for the upper half lower=[] lowerCnts=n//2 upperCnts=n-lowerCnts for l,r in lr: if r>=guess: potentialUpper.append([l,r]) else: lower.append([l,r]) if len(potentialUpper)<upperCnts: return False potentialUpper.sort(key=lambda x:x[0],reverse=True) # sort by l desc # for the upper, take the ones with the highest l, leaving the rest for lower for i in range(upperCnts,len(potentialUpper)): lower.append(potentialUpper[i]) assert(len(lower))==lowerCnts requiredSalary=0 for l,r in lower: requiredSalary+=l for i in range(upperCnts): requiredSalary+=max(guess,potentialUpper[i][0]) return requiredSalary<=s t=int(input()) allans=[] for _ in range(t): n,s=readIntArr() lr=[] for __ in range(n): lr.append(readIntArr()) m=getLowestPossibleMedian(lr,n) ans=m b=s while b>0: while checkPossibleMedian(lr,ans+b,n,s): ans+=b b//=2 allans.append(ans) multiLineArrayPrint(allans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m]) dv=defaultVal;da=dimensionArr if len(da)==1:return [dv for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x,y): print('? {} {}'.format(x,y)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 MOD=998244353 for _abc in range(1): 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; const long long M = 1e9 + 7; const long long N = 2e5; long long po(long long, long long); vector<pair<long long, long long>> v; long long n, s; bool check(long long mid) { long long sum = 0; long long c = 0; for (long long i = n - 1; i >= 0; i--) { if (mid >= v[i].first && mid <= v[i].second) { if (c < n / 2 + 1) { sum += mid; c++; } else { sum += v[i].first; } } else if (mid < v[i].first) { if (c < n / 2 + 1) { sum += v[i].first; c++; } else { sum += v[i].first; } } else { sum += v[i].first; } } if (c == n / 2 + 1 && sum <= s) { return 1; } else return 0; } void solve() { cin >> n >> s; v.clear(); for (long long i = 0; i < n; i++) { long long l, r; cin >> l >> r; v.push_back({l, r}); } sort((v).begin(), (v).end()); long long l = v[n / 2].first; long long r = s + 5; while (l < r - 1) { long long mid = l + (r - l) / 2; if (check(mid)) { l = mid; } else { r = mid; } } cout << l << "\n"; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long t = 1; cin >> t; for (long long i = 1; i < t + 1; i++) { solve(); } return 0; } long long po(long long a, long long b) { if (b == 0) return 1; long long ans = 1; if (b % 2 == 0) { ans = po(a, b / 2) % M; ans = (ans % M * ans % M) % M; } else { ans = po(a, (b - 1) / 2) % M; ans = (ans % M * ans % M * a) % M; } return ans % M; }
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.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; public class Salary_changing_simple_binary_search { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); FastScanner s = new FastScanner(in); PrintWriter out = new PrintWriter(System.out); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); long sum = s.nextLong(); long[][] arr = new long[n][2]; for (int i = 0; i < n; i++) { arr[i][0] = s.nextLong(); arr[i][1] = s.nextLong(); } long lo = 1; long hi = 1000000000; long ans = -1; while (lo <= hi) { long mid = (lo + hi) / 2; if (check(mid, arr, sum)) { lo = mid + 1; ans = mid; } else { hi = mid - 1; } } System.out.println(ans); } } private static boolean check(long x, long[][] arr, long sum) { int lc = 0; int rc = 0; long ls = 0; long rs = 0; int n = arr.length; ArrayList<Long[]> ar = new ArrayList<Long[]>(); for (int i = 0; i < n; i++) { if (arr[i][1] < x) { lc++; ls = ls + arr[i][0]; } else if (arr[i][0] > x) { rc++; rs = rs + arr[i][0]; } else { Long[] temp = new Long[2]; temp[0] = arr[i][0]; temp[1] = arr[i][1]; ar.add(temp); } } if (lc > (n / 2)) { return false; } Collections.sort(ar, new com()); long rem = Math.max(0, (n+1)/2 - rc); rs = rs + (rem) * x; rc += rem; for (int i = 0; i < ar.size() -rem; i++) { lc++; ls = ls + ar.get(i)[0]; if (lc == n / 2) { break; } } if (ls + rs > sum) return false; return true; } public static class com implements Comparator<Long[]> { public int compare(Long[] one, Long[] two) { return (int) (one[0] - two[0]); } } public static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } } }
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 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); rem = v.size() - need; sort(v.begin(), v.end(), comp1); reverse(v.begin(), v.end()); while (rem--) { cost += v.back().first; v.pop_back(); } while (need--) { cost += max(mid, v.back().first); 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
#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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.*; public class Main { static Comparator<long[]> comparator_r = new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { return Long.compare(o2[1], o1[1]); } }; static Comparator<long[]> comparator_l = new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { return Long.compare(o2[0], o1[0]); } }; static int[] a; static int n; static ArrayList<long[]> edges; public static boolean isOK(long index, long key) { ArrayList<long[]> edge_over_k = new ArrayList<long[]>(); ArrayList<long[]> edge_under_k = new ArrayList<long[]>(); for (long[] tmp : edges) { if (index<=tmp[1]) { edge_over_k.add(tmp); } else { edge_under_k.add(tmp); } } Collections.sort(edge_over_k, comparator_l); long sum = 0L; for (int i=0;i<n/2+1;i++) { sum += Math.max(index, edge_over_k.get(i)[0]); } for (int i=n/2+1;i<edge_over_k.size();i++) { sum += edge_over_k.get(i)[0]; } for (int i=0;i<edge_under_k.size();i++) { sum += edge_under_k.get(i)[0]; } // System.out.println("sum: " + sum + " key: " + key); if (sum <= key) return true; else return false; } public static long binary_search(long min_k, long max_k, long key) { // long left = min_k-1; // long right = max_k+1; long left = max_k+1; long right = min_k-1; while (Math.abs(right - left) > 1) { long mid = left + (right - left) / 2; if (isOK(mid, key)) right = mid; else left = mid; } return right; } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); // Comparator<long[]> comparator = new Comparator<long[]>() { // @Override // public int compare(long[] o1, long[] o2) { // return Long.compare(o2[1], o1[1]); // } // }; // a = new int[8]; // a[0]=10; // a[1]=9; // a[2]=7; // a[3]=7; // a[4]=7; // a[5]=7; // a[6]=7; // a[7]=6; // a[0]=6; // a[1]=7; // a[2]=7; // a[3]=7; // a[4]=7; // a[5]=7; // a[6]=9; // a[7]=10; // out.println("binary_search: " + binary_search((long)7)); int t = in.nextInt(); for (int i=0;i<t;i++) { n = in.nextInt(); long s = in.nextLong(); edges = new ArrayList<long[]>(); for (int j=0;j<n;j++) { long l = in.nextLong(); long r = in.nextLong(); long[] add = {l, r}; edges.add(add); } Collections.sort(edges, comparator_l); long min_k = edges.get(n/2)[0]; Collections.sort(edges, comparator_r); long max_k = edges.get(n/2)[1]; // out.println("min_k: " + min_k + " max_k: " + max_k); out.println(binary_search(min_k, max_k, s)); // Collections.sort(edges, comparator); // PriorityQueue<long[]> left = new PriorityQueue<long[]>(comparator_l); // PriorityQueue<long[]> right = new PriorityQueue<long[]>(comparator_r); // long left_sum = 0L; // long right_sum = 0L; // for (long[] ed : edges) { // out.println("edges: " + Arrays.toString(ed)); // } // for (int j=0;j<n;j++) { // if (j>=0 && j<n/2+1) { // right.add(edges.get(j)); // if (j==n/2) { // right_sum+=edges.get(j)[1]*(n/2+1); // } // } else { // left.add(edges.get(j)); // left_sum+=edges.get(j)[0]; // } // } // while (!right.isEmpty()) { // long[] rig = right.remove(); // System.out.println("right " + Arrays.toString(rig)); // } // while (!left.isEmpty()) { // long[] lef = left.remove(); // System.out.println("left " + Arrays.toString(lef)); // } // System.out.println(right); // System.out.println(left); // int lll = 0; // out.println("left_sum" + left_sum); // out.println("right_sum" + right_sum); // while(right_sum+left_sum>s) { // long[] le = left.remove(); // long[] ri = right.remove(); // right_sum -= (ri[1]-le[1])*(n/2+1); // left_sum += (ri[0]-le[0]); // right.add(le); // left.add(ri); // out.println("left_sum" + left_sum); // out.println("right_sum" + right_sum); // lll++; // if (lll==11) { // break; // } // } // out.println(right_sum/(n/2+1)); // out.println(right_sum/(n/2+1)); // out.println(right_sum/(n/2+1)); // out.println(right_sum/(n/2+1)); // out.println(right_sum/(n/2+1)); } out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
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 e2 { public static void print(String str,long val){ System.out.println(str+" "+val); } public long gcd(long a, long b) { if (b==0L) return a; return gcd(b,a%b); } public static void debug(long[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(int[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(arr[i]); } } public static void print(int[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(Object[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(long[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String path) throws FileNotFoundException { br = new BufferedReader(new FileReader(path)); } 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; } } public static void main(String[] args) { FastReader s=new FastReader(); int t = s.nextInt(); for(int tt=0;tt<t;tt++){ int n = s.nextInt(); long sum = s.nextLong(); pair[] coord = new pair[n]; for(int i=0;i<n;i++){ int l = s.nextInt(); int r = s.nextInt(); coord[i] = new pair(l,r); } System.out.println(solve(n,sum,coord)); } } static int solve(int n,long sum,pair[] coord){ Comparator<pair> comp = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if(o1.l<o2.l){ return -1; } else if(o1.l>o2.l){ return 1; } else { if(o1.r<o2.r){ return -1; } else if(o1.r>o2.r){ return 1; } return 0; } } }; Arrays.sort(coord,comp); int start = coord[0].l; int end = (int)(1e9); // print(check(68,sum,coord,n)+"",0); while (end-start>1){ int mid = (start+end)/2; if(check(mid,sum,coord,n)){ start = mid; } else { end = mid-1; } } if(check(end,sum,coord,n)){ return end; } return start; } static boolean check(int k,long s,pair[] coor,int n){ long sum =0; ArrayList<Integer> third_type = new ArrayList<>(); int count =0; for(int i=0;i<n;i++){ if(coor[i].r<k){ sum+=coor[i].l*1l; } else if(coor[i].l>=k){ sum+=coor[i].l*1l; count++; } else { third_type.add(coor[i].l); } } int need = Math.max(0,((n+1)/2)-count); if(need>third_type.size()){ return false; } for(int i=0;i<third_type.size();i++){ if(i<(third_type.size()-need)){ sum+=(third_type.get(i))*1l; } else { sum+=k*1l; } } return (sum<=s); } static class pair{ int l; int r; pair(int l,int r){ this.l = l; this.r = r; } } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((arr[i]+" ").getBytes()); // } // out.flush(); // long start_time = System.currentTimeMillis(); // long end_time = System.currentTimeMillis(); // System.out.println((end_time - start_time) + "ms"); }
JAVA