Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.io.*; import java.util.*; public class MainClass { public static void main(String[] args)throws IOException { Reader in = new Reader(); int t = in.nextInt(); StringBuilder stringBuilder = new StringBuilder(); while (t-- > 0) { int n = in.nextInt(); long s = in.nextLong(); long[] L = new long[n]; long[] R = new long[n]; long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; for (int i=0;i<n;i++) { L[i] = in.nextLong(); R[i] = in.nextLong(); min = Math.min(min, L[i]); max = Math.max(max, R[i]); } long l = min; long r = max; long ans = -1; while (l <= r) { long mid = (l + r) / 2; if (check(L, R, mid, s)) { ans = mid; l = mid + 1; } else r = mid - 1; } stringBuilder.append(ans).append("\n"); } System.out.println(stringBuilder); } public static boolean check(long[] L, long[] R, long x, long s) { int c1 = 0; int c2 = 0; int c3 = 0; int n = L.length; long sum = 0L; TreeMap<Long, Integer> h = new TreeMap<>(); for (int i=0;i<n;i++) { if (R[i] < x) { c1++; sum += L[i]; } else if (x <= L[i]) { c2++; sum += Math.max(x, L[i]); } else { if (!h.containsKey(L[i])) h.put(L[i], 1); else h.put(L[i], h.get(L[i]) + 1); c3++; } } if (c2 + c3 < (n + 1) / 2) return false; else { int req = Math.max(0, (n + 1) / 2 - c2); sum += req * x; for (int i=0;i<req;i++) { long key = h.lastKey(); h.put(key, h.get(key) - 1); if (h.get(key) == 0) h.remove(key); } Iterator iterator = h.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry)iterator.next(); long key = (long)element.getKey(); int val = (int)element.getValue(); sum += key * val; } if (sum <= s) return true; return false; } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
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 + 10; struct node { int l; int r; } a[N]; bool cmp(node a, node b) { if (a.l == b.l) return a.r > b.r; return a.l > b.l; } long long n, s; int check(int x) { int k = n / 2, cnt = 0; long long sum = 0; for (int i = 0; i < n; i++) { if (a[i].r >= x && cnt <= k) { if (a[i].l <= x) { sum += x; } else { sum += a[i].l; } cnt++; } else { sum += a[i].l; } } return (sum <= s) && cnt == k + 1; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%lld%lld", &n, &s); for (int i = 0; i < n; i++) { scanf("%d%d", &a[i].l, &a[i].r); } sort(a, a + n, cmp); int l = 1, r = 1e9; while (l < r) { int mid = (l + r + 1) >> 1; if (check(mid)) { l = mid; } else { r = mid - 1; } } printf("%d\n", l); } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
// package Quarantine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import javafx.util.Pair; public class SalaryChanging { public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int test=Integer.parseInt(br.readLine()); StringBuilder print=new StringBuilder(); while(test--!=0){ StringTokenizer st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); long s=Long.parseLong(st.nextToken()); Pair<Integer,Integer> salaries[]=new Pair[n]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); int l=Integer.parseInt(st.nextToken()); int r=Integer.parseInt(st.nextToken()); salaries[i]=new Pair<>(l,r); } long ans=1; long low=1,high=s; while (low<=high){ long mid=(low+high)/2; if(isPossible(salaries,mid,s,n)){ ans=mid; low=mid+1; } else{ high=mid-1; } } print.append(ans+"\n"); } System.out.print(print.toString()); } public static boolean isPossible(Pair<Integer,Integer> a[],long val,long s,int n){ long sum=0; int reqd=(n+1)/2; ArrayList<Integer> rem=new ArrayList<>(); for(int i=0;i<a.length;i++){ Pair<Integer,Integer> curr=a[i]; int l=curr.getKey(); int r=curr.getValue(); if(r<val){ sum+=l; continue; } if(l>val){ sum+=l; reqd--; continue; } rem.add(l); } // System.out.println(reqd+" "+rem.size()+" "+val); if(reqd<0){ return true; } if(rem.size()<reqd){ return false; } Collections.sort(rem,Collections.reverseOrder()); for(int i=0;i<reqd;i++){ sum+=val; } for(int i=reqd;i<rem.size();i++){ sum+=rem.get(i); } // System.out.println(sum+" "+val); return sum<=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
from sys import stdin, stdout def getmaximummediansalary(lra, n, s): l = 0 h = s while l < h: m = (l + h + 1)//2 #print(m) if candistribute(m, lra, s): l = m else: h = m-1 return l def candistribute(m, lra, s): cntl = 0 cntm = 0 cnth = 0 sum = 0 target = [] for lr in lra: if m > lr[1]: sum += lr[0] cntl += 1 elif m < lr[0]: sum += lr[0] cnth += 1 else: target.append(lr[0]) cntm += 1 #print(cntl) #print(cntm) #print(cnth) mi = len(lra) // 2 if cntl + cntm < mi: return True if cntm + cnth <= mi: return False need = mi - cntl #print(need) for i in range(len(target)): if i < need: sum += target[i] else: sum += m return sum <= s if __name__ == '__main__': t = int(stdin.readline()) for i in range(t): ns = list(map(int, stdin.readline().split())) n = ns[0] s = ns[1] lra = [] for j in range(n): lra.append(list(map(int, stdin.readline().split()))) lra.sort(key=lambda x: x[0]) res = getmaximummediansalary(lra, n, s) #test = candistribute(3, lra, s) #test = candistribute(11, lra, s) #test = candistribute(12, lra, s) #test = candistribute(20, lra, s) #stdout.write(str(test) + '\n') stdout.write(str(res) + '\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 sys def I(): return sys.stdin.readline().rstrip() for _ in range( int( I() ) ): n, s = map( int, I().split() ) half = n // 2 lows = 0 l, r = [], [] for _ in range( n ): x, y = map( int, I().split() ) lows += x l.append( x ) r.append( y ) money = 0 t = 1 while t <= 1e9: t *= 2 t //= 2 while t > 0: people = 0 new_money = money + t left = [] for low, high in zip( l, r ): if low <= new_money <= high: left.append( new_money - low ) elif new_money < low: people += 1 left.sort() people = half + 1 - people if people <= 0 or len( left ) >= people and lows + sum( left[:people] ) <= s: money += t t //= 2 print( money )
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, s, up, down, mid, mx, mn, a, b, k, l, r, ans, raod; pair<long long, long long> p[300005]; int main() { cin >> t; while (t--) { cin >> n >> S; mn = 1e10; mx = 0; for (k = 1; k <= n; k++) { cin >> a >> b; p[k].first = a; mn = min(mn, a); p[k].second = b; mx = max(mx, b); } ans = 0; sort(p + 1, p + n + 1); l = mn; r = mx; while (l <= r) { long long mid = (l + r + 1) / 2; up = 0; down = 0; s = 0; for (k = 1; k <= n; k++) if (p[k].first > mid) up++; else if (p[k].second < mid) down++; if (up >= n / 2 + 1) { l = mid + 1; } else if (down >= n / 2 + 1) r = mid - 1; else { raod = 0; for (k = n; k >= 1; k--) { if (raod <= n / 2 & p[k].second >= mid) { raod++; s += max(mid, p[k].first); } else s += p[k].first; } if (s <= S) { ans = mid; l = mid + 1; } else r = mid - 1; } } cout << ans << endl; } }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > v; bool check(long long mid, int cnt, long long total) { int i, c = 0, c1 = 0; long long sum = 0; vector<long long> tmp; for (i = 0; i < v.size(); i++) { if (v[i].second < mid) sum += v[i].first; else if (mid < v[i].first) { c++; sum += v[i].first; } else { c1++; tmp.push_back(v[i].first); } } int rem = max(0, cnt - c); if (c1 < rem) return 0; sort(tmp.begin(), tmp.end()); for (i = 0; i < c1; i++) { if (i < c1 - rem) sum += min(tmp[i], mid); else sum += mid; } if (total < sum) return 0; return 1; } void solve() { int i, t; long long total; cin >> t >> total; v.clear(); for (i = 0; i < t; i++) { int l, r; cin >> l >> r; v.push_back({l, r}); } int cnt = (t + 1) / 2; long long hi, lo, mid; lo = 1, hi = total; while (hi - lo >= 4) { mid = (hi + lo) / 2; if (check(mid, cnt, total)) lo = mid; else hi = mid; } for (i = hi; i >= lo; i--) { if (check(i, cnt, total)) { cout << i << "\n"; break; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int test; cin >> test; while (test--) solve(); return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); StringBuilder sb=new StringBuilder(); int t=s.nextInt(); for(int i=0;i<t;i++) { int n=s.nextInt(); long sum=s.nextLong(); pair[] arr=new pair[n]; for(int j=0;j<n;j++) { int l=s.nextInt(); int r=s.nextInt(); pair p=new pair(l,r); arr[j]=p; } Arrays.sort(arr,new comp()); long res=-1; long start=0; long end=sum; while(start<=end) { long mid=(start+end)/2; if(check(arr,mid,sum,n)) { res=mid; start=mid+1; } else { end=mid-1; } } sb.append(res); sb.append("\n"); } System.out.println(sb); } public static boolean check(pair[] arr,long mid,long sum,int n) { int count=0; int have=0; for(int i=0;i<n;i++) { if(arr[i].l>=mid) { count++; } else if(arr[i].l<mid&&arr[i].r>=mid) { have++; } } int p=0; have=have-(((n+1)/2)-count); if(have<0) p=1; for(int i=0;i<n;i++) { if(arr[i].r<mid) { sum=sum-arr[i].l; } else if(arr[i].l>=mid) { sum=sum-Math.max(mid,arr[i].l); } else { if(have>0) { sum=sum-arr[i].l; have--; } else { sum=sum-mid; } } } if(sum<0) p=1; if(p==0) { return true; } else { return false; } } } class pair { int l; int r; public pair(int l,int r) { this.l=l; this.r=r; } } class comp implements Comparator<pair> { public int compare(pair a,pair b) { if(a.l<b.l) return -1; else if(a.l==b.l) return a.l-b.l; else return 1; } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
from sys import stdin, stdout raw_input = stdin.readline pr = stdout.write def fun(x,n,arr,sal): c1,c2=0,0 sm=0 temp=[] for i in xrange(n): if arr[i][1]<x: c1+=1 sm+=arr[i][0] elif arr[i][0]>=x: sm+=arr[i][0] else: temp.append(list(arr[i])) #temp.sort() v1=n/2 v2=v1+1 v1-=c1 if v1<0: return 0 #print x,temp,v1 for l1,r1, in temp: if v1: v1-=1 sm+=l1 else: sm+=x if sm<=sal: return 1 return 0 for t in xrange(input()): n,s=map(int,raw_input().split()) arr=[] r=0 for i in xrange(n): x=(map(int,raw_input().split())) r=max(r,x[1]) arr.append(x) arr.sort() l=0 ans=0 while l<=r: mid=(l+r)/2 if fun(mid,n,arr,s): ans=mid l=mid+1 else: r=mid-1 pr(str(ans)+'\n')
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; int takemod(int a, int mod) { a %= mod; if (a < 0) a += mod; return a; } int fast_exp(int base, int expo, int mod) { int res = 1; while (expo > 0) { if (expo & 1) res = (res * base) % mod; base = (base * base) % mod; expo >>= 1; } return res; } int modinv(int a, int mod) { return takemod(fast_exp(takemod(a, mod), mod - 2, mod), mod); } const long long N = 1e15 + 5, A = 1e5 + 10, md = 1e9 + 7; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { long long n, s; cin >> n >> s; vector<pair<int, int> > a; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; a.push_back(make_pair(x, y)); s -= x; } int k = (n + 1) / 2; long long l = 1, r = N; while (l <= r) { long long m = (l + r) / 2; vector<long long> b; for (int i = 0; i < n; i++) { if (a[i].second >= m) { b.push_back(a[i].first); } } bool check = 0; if (b.size() >= k) { sort(b.begin(), b.end()); long long cost = 0; for (int i = 0; i < k; i++) { cost += max(0ll, m - b[b.size() - i - 1]); } if (cost <= s) { check = 1; } } if (check) { l = m + 1; } else { r = m - 1; } } cout << l - 1 << 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
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=Int(); for(int t=0;t<T;t++){ int n=Int();long sum=Long(); int A[][]=new int[n][2]; for(int i=0;i<n;i++){ A[i][0]=Int(); A[i][1]=Int(); } Solution sol=new Solution(); sol.solution(out,A,sum); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ public void solution(PrintWriter out,int A[][],long sum){ Arrays.sort(A,(a,b)->{ return a[1]-b[1]; }); int res=-1; int l=Integer.MAX_VALUE,r=Integer.MIN_VALUE; for(int i=0;i<A.length;i++){ l=Math.min(l,A[i][0]); r=Math.max(r,A[i][1]); } while(l<=r){ int mid=l+(r-l)/2; if(check(A,sum,mid)){ res=mid; l=mid+1; } else{ r=mid-1; } } // check(A,sum,68); out.println(res); } public boolean check(int A[][],long money,int mid){ int n=A.length;// (n-1)/2<=mid (n+1)/2>=mid long sum=0; PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->{ return a[0]-b[0]; }); for(int i=0;i<A.length;i++){ if(A[i][1]>=mid){ sum+=Math.max(mid,A[i][0]); pq.add(new int[]{A[i][0],Math.max(mid,A[i][0])}); } else{ sum+=A[i][0]; } } if(pq.size()<(n+1)/2)return false; while(pq.size()>(n+1)/2){ int top[]=pq.poll(); sum-=top[1]; sum+=top[0]; } return sum<=money; } }
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; pair<long long, long long> ara[200005]; int n; long long s; bool cheak(long long m) { long long rem = s; for (int i = 0; i < n; i++) rem -= ara[i].first; int p = (n + 1) >> 1; for (int i = 0; i < n && p; i++) { if (ara[i].first >= m) p--; else if (ara[i].second >= m && (m - ara[i].first) <= rem) rem -= (m - ara[i].first), p--; } return (!p); } long long mn, mx; long long bs() { long long lo = mn, hi = mx, res; while (lo <= hi) { long long mid = (lo + hi) >> 1; if (cheak(mid)) res = mid, lo = mid + 1; else hi = mid - 1; } return res; } int main() { int ts; scanf("%d", &ts); while (ts--) { scanf("%d %lld", &n, &s); mn = 1000000009; mx = 0; for (int i = 0; i < n; i++) scanf("%lld %lld", &ara[i].first, &ara[i].second), mn = min(mn, ara[i].first), mx = max(mx, ara[i].second); sort(ara, ara + n, greater<pair<long long, long long> >()); printf("%lld\n", bs()); } 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 INF = 1001001001; const long long LINF = 1e17; const double pi = 3.1415926535897932; const string endstr = "\n"; template <typename T> T gcd(T a, T b) { return (a == 0) ? b : gcd(b % a, a); } template <typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; } bool p_comp_fs(const pair<long long, long long> p1, const pair<long long, long long> p2) { return p1.first < p2.first; }; bool p_comp_fg(const pair<long long, long long> p1, const pair<long long, long long> p2) { return p1.first > p2.first; }; bool p_comp_ss(const pair<long long, long long> p1, const pair<long long, long long> p2) { return p1.second < p2.second; }; bool p_comp_sg(const pair<long long, long long> p1, const pair<long long, long long> p2) { return p1.second > p2.second; }; template <typename T> vector<T> uniquen(vector<T> vec) { sort((vec).begin(), (vec).end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } inline long long popcnt(long long x) { return __builtin_popcountll((unsigned long long)x); }; template <class T> bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template <class T> bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } bool check(long long x, long long s, vector<pair<long long, long long> > &P) { long long N = P.size(); long long lcnt = 0, rcnt = 0, lsum = 0, rsum = 0; vector<pair<long long, long long> > midx; for (auto p : P) { if (p.second < x) { lcnt++; lsum += p.first; } else if (p.first > x) { rcnt++; rsum += p.first; } else { midx.push_back(p); } } if (lcnt > N / 2) return false; if (rcnt > N / 2) return true; long long sum = lsum + rsum; for (long long i = 0; i < N / 2 - lcnt; i++) sum += midx[i].first; long long rem = N - (lcnt + rcnt + (N / 2 - lcnt)); sum += x * rem; return sum <= s; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); long long T; cin >> T; for (long long _ = 0; _ < T; _++) { long long N, S; cin >> N >> S; vector<pair<long long, long long> > PS(N); for (long long i = 0; i < N; i++) cin >> PS[i].first >> PS[i].second; sort((PS).begin(), (PS).end()); long long ok = -1, ng = LINF; while (abs(ok - ng) > 1) { long long mid = (ok + ng) / 2; if (check(mid, S, PS)) ok = mid; else ng = mid; } cout << ok << endstr; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; 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); DSalaryChanging solver = new DSalaryChanging(); solver.solve(1, in, out); out.close(); } static class DSalaryChanging { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); long amount = in.nextLong(); Salary[] salaries = new Salary[n]; for (int i = 0; i < n; i++) { salaries[i] = new Salary(in.nextInt(), in.nextInt()); } out.println(solve(salaries, amount)); } } private long solve(Salary[] salaries, long amount) { Arrays.sort(salaries, (o1, o2) -> o2.base - o1.base); int lo = 0; // int hi = 20; int hi = 1000000000; long baseCost = 0; for (Salary salary : salaries) { baseCost += salary.base; } while (lo < hi) { int median = lo + (hi - lo + 1) / 2; if (isValid(salaries, median, baseCost, amount)) { lo = median; } else { hi = median - 1; } } return lo; } private boolean isValid(Salary[] salaries, int median, long baseCost, long amount) { int n = salaries.length; int threshold = n / 2 + 1; int count = 0; long cost = baseCost; int i = 0; while (i < n && count < threshold) { if (median <= salaries[i].max) { cost += Math.max(median - salaries[i].base, 0); count++; } i++; } if (cost <= amount && count == threshold) { return true; } return false; } } static class Salary { public int base; public int max; public Salary(int base, int max) { this.base = base; this.max = max; } } 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 Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { FastReader fr =new FastReader(System.in); PrintWriter op =new PrintWriter(System.out); int T =fr.nextInt() ; while (T-->0) solve(fr , op); op.flush(); op.close(); } }, "1", 1 << 26).start(); } static void solve (FastReader fr , PrintWriter op) { int N =fr.nextInt() ,i ,delta ; long S =fr.nextLong() ,left ,mid ,right ,median ,dummy ,sumOfL[] =new long[N+1] ,salary[][] =new long[N+1][2] ; for (i =1 ; i<=N ; ++i) { salary[i][0] =fr.nextLong() ; salary[i][1] =fr.nextLong() ; } sort(salary,1,N) ; for (i =1 ; i<=N ; ++i) sumOfL[i] =sumOfL[i-1]+salary[i][0] ; left =1l ; right =S ; median =-1l ; while (left<=right) { mid =(left+right)/2l ; dummy =0l ; for (i =N ; i>0 && salary[i][0]>mid ; --i) ; //System.out.println(i+" "+mid) ; if (i<=N/2) { left =mid+1 ; continue ; } dummy =sumOfL[N]-sumOfL[i] ; delta =N/2-(N-i) + 1 ; dummy += sumOfL[i] ; for (; i>0 && delta>0 ; --i) { if (salary[i][1]>=mid) { dummy -= salary[i][0] ; dummy += mid ; --delta ; } } if (delta!=0 || dummy>S) { right =mid-1l ; continue ; } median =mid ; left =mid+1l ; } op.println(median) ; } public static void sort(long[][] arr , int l , int u) { int m ; if(l < u){ m =(l + u)/2 ; sort(arr , l , m); sort(arr , m + 1 , u); merge(arr , l , m , u); } } public static void merge(long[][]arr , int l , int m , int u) { long[][] low = new long[m - l + 1][2]; long[][] upr = new long[u - m][2]; int i ,j =0 ,k =0 ; for(i =l;i<=m;i++){ low[i - l][0] =arr[i][0]; low[i - l][1] =arr[i][1]; } for(i =m + 1;i<=u;i++){ upr[i - m - 1][0] =arr[i][0]; upr[i - m - 1][1] =arr[i][1]; } i =l; while((j < low.length) && (k < upr.length)) { if(low[j][0] < upr[k][0]) { arr[i][0] =low[j][0]; arr[i++][1] =low[j++][1]; } else { if(low[j][0] > upr[k][0]) { arr[i][0] =upr[k][0]; arr[i++][1] =upr[k++][1]; } else { if(low[j][1] < upr[k][1]) { arr[i][0] =low[j][0]; arr[i++][1] =low[j++][1]; } else { arr[i][0] =upr[k][0]; arr[i++][1] =upr[k++][1]; } } } } while(j < low.length) { arr[i][0] =low[j][0]; arr[i++][1] =low[j++][1]; } while(k < upr.length) { arr[i][0] =upr[k][0]; arr[i++][1] =upr[k++][1]; } } static class FastReader { private final InputStream is; private final StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private final byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastReader(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int nextInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long nextLong() { return Long.parseLong(readString()) ; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } }
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 = [list(read()) for i in range(n)] 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 sorted(b, reverse = True): #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 sys.stdout.write(f"{e}\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.*; import java.util.*; public class r75p4 { private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private static PrintWriter pw = new PrintWriter(System.out); private static void next()throws IOException{ if(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private static int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private static long nextLong()throws IOException{ next(); return Long.parseLong(tk.nextToken()); } private static String readString()throws IOException{ next(); return tk.nextToken(); } private static double nextDouble()throws IOException{ next(); return Double.parseDouble(tk.nextToken()); } private static int[] intArray(int n)throws IOException{ next(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } private static long[] longArray(int n)throws IOException{ next(); long arr[] = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } private static int n; private static long s; private static R arr[]; static class R implements Comparable<R>{ long l, r; R(long l, long r){ this.l = l; this.r = r; } public int compareTo(R o){ if(l < o.l) return -1; else if(l == o.l) return 0; return 1; } } private static boolean possible(long val){ int cnt[] = {0, 0}; ArrayList<Long> tmp = new ArrayList<>(); long sum = 0; for(int i=0; i<n; i++){ if(arr[i].r < val){ cnt[0]++; sum += arr[i].l; } else if(arr[i].l > val){ cnt[1]++; sum += arr[i].l; } else tmp.add(arr[i].l); } if(cnt[0]>n/2 || cnt[1]>n/2) return false; for(int i=0; i<n/2-cnt[0]; i++) sum += tmp.get(i); sum += val*((n/2)+1-cnt[1]); return sum <= s; } private static void solve()throws IOException{ n = nextInt(); s = nextLong(); arr = new R[n]; for(int i=0; i<n; i++) arr[i] = new R(nextLong(), nextLong()); Arrays.sort(arr); long low = arr[n/2].l, high = (long)1e9 + 10; while(low <= high){ long mid = low + (high-low)/2; if(possible(mid)) low = mid + 1; else high = mid - 1; } pw.println(+high); } public static void main(String args[])throws IOException{ int t = nextInt(); while(t-->0) solve(); pw.flush(); pw.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 input = sys.stdin.readline def solve(mid): ans = 0 cnt = 0 tmp = [] for i in range(n): l, r = info[i] if r < mid: ans += l elif mid < l: ans += l cnt += 1 else: tmp.append(l) tmp.sort(reverse = True) nokori = (n+1) // 2 - cnt for i in tmp: if nokori > 0: ans += mid nokori -= 1 else: ans += i if ans <= s and nokori <= 0: return True else: return False q = int(input()) for _ in range(q): n, s = map(int, input().split()) info = [list(map(int, input().split())) for i in range(n)] ok = 0 ng = s + 1 while abs(ok - ng) > 1: mid = (ok + ng) // 2 if solve(mid): ok = mid else: ng = mid 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.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; public class Main { private static final String NO = "No"; private static final String YES = "Yes"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 1000000007; void solve() { int T = ni(); for (int i = 0; i < T; i++) solve(i); } void solve(int nth) { int n = ni(); long s = nl(); long[][] a = nl(n, 2); long l = 0; long r = s+1; while (l < r - 1) { long m = (l + r) / 2; if (check(a, m) <= s) { l = m; } else r = m; } out.println(l); } private long check(long[][] a, long m) { long s = 0; List<long[]> l = new ArrayList<long[]>(); int c0 = 0; int c1 = 0; for (long[] e : a) { if (e[1] < m) { s += e[0]; c0++; } else if (e[0] >= m) { s += e[0]; c1++; } else l.add(e); } if (2 * c0 < a.length) { Collections.sort(l, (x, y) -> Long.signum(x[0] - y[0])); for (int i = 0; i < l.size(); i++) { if (2 * c0 < a.length - 1) { c0++; s += l.get(i)[0]; } else { c1++; s += m; } } } else return Long.MAX_VALUE; // tr(m,s); return s; } // a^b long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private char[] nc(int n) { char[] ret = new char[n]; for (int i = 0; i < n; i++) ret[i] = nc(); return ret; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n) { if (!(isSpaceChar(b))) buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private Integer[] na2(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private int ni() { 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(); } } private Long[] nl2(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[][] nl(int n, int m) { long[][] a = new long[n][]; for (int i = 0; i < n; i++) a[i] = nl(m); return a; } private long nl() { 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(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; long long int a[200010][2]; bool check(long long int m, long long int n, long long int s) { long long int aa = 0, bb = 0; long long int sal = 0; vector<pair<int, int>> v; for (int i = 0; i < n; i++) { if (a[i][1] < m) aa++, sal = sal + a[i][0]; else if (a[i][0] >= m) bb++, sal = sal + a[i][0]; else v.push_back({a[i][0], a[i][1]}); } long long int p = (n / 2) - aa; long long int q = (n / 2) + 1 - bb; if (bb >= ((n / 2) + 1)) { for (long long int i = 0; i < v.size(); i++) sal = sal + v[i].first; if (sal <= s) return true; else return false; } else if (p >= 0 && q >= 0) { sort(v.begin(), v.end()); for (int i = 0; i < p; i++) sal = sal + v[i].first; sal = sal + (q * m); if (sal <= s) return true; else return false; } else return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { long long int n, s; cin >> n >> s; long long int l = INT_MAX, r = 0; for (int i = 0; i < n; i++) { cin >> a[i][0] >> a[i][1]; r = max(r, a[i][1]); l = min(l, a[i][0]); } long long int ans = 0; while (l <= r) { long long int m = (l + r) / 2; if (check(m, n, s)) ans = m, l = m + 1; else r = m - 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
import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int T = Integer.parseInt(st.nextToken()); for(int t = 0; t < T; t++) { st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); long s = Long.parseLong(st.nextToken()); Range[] rangs = new Range[n]; long[] mins = new long[n]; for(int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); long a = Long.parseLong(st.nextToken()); long b = Long.parseLong(st.nextToken()); rangs[i] = new Range(a, b); mins[i] = a; } Arrays.sort(mins); long a = mins[n/2], b = s+1; while(b - a > 1) { long c = (a+b)/2; if(process(rangs, n, s, c)) a = c; else b = c; } System.out.println(a); } } private static boolean process(Range[] rangs, int n, long tot, long c) { int ind = n / 2; ArrayList<Range> valid = new ArrayList<>(); for(Range r: rangs) { if(r.s > c) { tot -= r.s; } else if(r.t < c) { tot -= r.s; ind--; } else { valid.add(r); } } if(ind < 0 || ind >= valid.size()) return false; Collections.sort(valid); for(int i = 0; i < ind; i++) { tot -= valid.get(i).s; } long rest = ((long)(valid.size() - ind)) * c; return tot - rest >= 0; } static class Range implements Comparable<Range>{ long s, t; public Range(long s, long t) { this.s = s; this.t = t; } @Override public int compareTo(Range r) { long dif = s - r.s; if(dif < 0) return -1; else if(dif > 0) return 1; else return 0; } public String toString() { return s+" "+t; } } }
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 = 233333; long long suml = 0, n, s; struct node { int l, r; } e[maxn]; bool cmp(node a, node b) { if (a.l == b.l) return a.r < b.r; return a.l < b.l; } int vis[maxn]; bool check(int x) { long long now = suml; int cnt = 0; for (int i = n; i >= 1; i--) { if (e[i].l >= x) cnt++; else if (e[i].r >= x) { cnt++; now += (x - e[i].l); } if (cnt == (n + 1) / 2) { if (now <= s) return true; else return false; } } return false; } int main() { int T; cin >> T; while (T--) { cin >> n >> s; int l, r = -999; suml = 0; for (int i = 1; i <= n; i++) { cin >> e[i].l >> e[i].r; r = max(r, e[i].r); suml += e[i].l; } sort(e + 1, e + 1 + n, cmp); int mid = (n + 1) / 2; l = e[mid].l; int ct = 1; while (l <= r) { mid = (l + r) >> 1; if (check(mid)) l = mid + 1; else r = mid - 1; } int ans = r; if (check(l)) ans = max(ans, l); if (check(l + 1)) ans = max(ans, l + 1); if (check(mid)) ans = max(ans, mid); if (check(mid + 1)) ans = max(ans, mid + 1); if (check(r + 1)) ans = max(ans, r + 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
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t= Integer.parseInt(br.readLine()); for(int i=0;i<t;i++){ StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); long sal = Long.parseLong(st.nextToken()); int[][] range = new int[n][2]; for(int j=0;j<n;j++){ st = new StringTokenizer(br.readLine()); range[j][0] = Integer.parseInt(st.nextToken()); range[j][1] = Integer.parseInt(st.nextToken()); } Arrays.sort(range,(a,b)->{ if(a[0] == b[0]) return a[1]-b[1]; return a[0]-b[0]; }); findMedian(range,out,sal); } out.close(); } public static void findMedian(int[][] range, PrintWriter out,long sal){ int mid = range.length/2; int high = -1; for(int i=0;i<=mid;i++){ sal-=range[i][0]; high = Math.max(range[i][1],high); } for(int i=mid+1;i<range.length;i++) sal-=range[i][0]; long val = binarySearch(range,sal,high,mid); out.println(val); } public static long binarySearch(int[][] range,long sal,int high,int i){ int low= range[i][0]; while(low < high){ int mid = (low+high)/2; if(check(sal,mid,range) > 0) low = mid+1; else high = mid; } low = (check(sal,low,range) >= 0) ? (low) : low-1; return low; } public static long check(long sal,int mid,int[][] range){ int left = 0; int right = 0; int max= range.length/2+1; for(int i=range.length-1;i>=0 && right <= max;i--){ if(range[i][1] < mid) left++; else if(range[i][0]> mid) right++; else{ if(right == max)continue; right++; sal-=(mid-range[i][0]); } } if(sal < 0 || left>=max || right > max) return -1; return sal; } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 5; struct Node { int L, R; bool operator<(const Node &other) const { return L < other.L; } }; int N, H; long long S; vector<Node> v; bool possible(int median) { long long sum = 0; for (Node &s : v) sum += s.L; int count = 0; for (int i = N - 1; i >= 0 && count < H; i--) if (v[i].R >= median) { sum += max(median - v[i].L, 0); count++; } return count == H && sum <= S; } int main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int T; cin >> T; while (T--) { cin >> N >> S; H = (N + 1) / 2; v.resize(N); for (Node &s : v) cin >> s.L >> s.R; sort(v.begin(), v.end()); int l = 0, r = INF, ans; while (l <= r) { int mid = (l + r) / 2; if (possible(mid)) { 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; int N, N2; long long S; const int MAXN = 2e5 + 15; pair<long long, long long> A[MAXN]; long long I[MAXN]; bool check(long long m) { int c2 = 0, n = 0; long long sum = 0; for (int i = 0; i < N; ++i) if (A[i].second < m) { sum += A[i].first; } else if (A[i].first >= m) { ++c2; sum += A[i].first; } else { I[n++] = A[i].first; } int need = max(0, N2 - c2); if (need > n) return false; for (int i = 0; i < n; ++i) if (i < n - need) sum += I[i]; else sum += m; return sum <= S; } int main() { ios::sync_with_stdio(false); int T; cin >> T; while (T--) { cin >> N >> S; N2 = (N + 1) / 2; long long bb = 1, ee = 1e9 + 1; for (int i = 0; i < N; ++i) { long long a, b; cin >> a >> b; A[i] = make_pair(a, b); } sort(A, A + N); while (ee - bb > 1) { long long m = (bb + ee) / 2; if (check(m)) bb = m; else ee = m; } cout << bb << 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.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.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, r = s + 1; 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 java.util.*; import java.io.*; import java.math.BigInteger; public class tr0 { static PrintWriter out; static StringBuilder sb; static final double EPS = 1e-9; static long mod = (int) 1e9 + 7; static int inf = (int) 1e9 + 2; static long[] fac; static int[] si; static ArrayList<Integer> primes; static ArrayList<Integer>[] ad; static ArrayList<pair>[] d; static edge[] ed; static boolean[] vis; static int[] l, ch; static int[] occ; static Queue<Integer>[] can; static String s; static long[][] memo; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); long s=sc.nextLong(); qu [] a=new qu[n]; for(int i=0;i<n;i++) { a[i]=new qu(sc.nextLong(), sc.nextLong()); } //Arrays.sort(a); //System.out.println(Arrays.toString(a)); long ty=0; // for(int i=0;i<n;i++) // ty+=a[i].i; ty=a[n/2].i; long lo=0; long hi=s; long ans=0; while(lo<=hi) { long mid=(lo+hi)/2l; boolean valid=true; long low=0; long ss=s; // System.out.println(mid+" x "+ty); PriorityQueue<Long> pq=new PriorityQueue<>(); for(int i=0;i<n;i++) { if(a[i].j<mid) { ss-=a[i].i; low++; } else if(a[i].i>=mid) { ss-=a[i].i; // low++; } else { pq.add(a[i].i); } if(ss<0) valid=false; // if(mid==6) // System.out.println(ss+" ss"); } if(low>n/2) valid=false; while(!pq.isEmpty()) { if(low==n/2) { pq.remove(); ss-=mid; } else { ss-=pq.remove(); low++; } } if(ss<0) valid=false; if(valid) { ans=mid; lo=mid+1; } else { hi=mid-1; } } out.println(ans); } out.flush(); } static long inver(long x, long kk) { int a = (int) x; long e = (kk - 2); long res = 1; while (e > 0) { if ((e & 1) == 1) { // System.out.println(res*a); res = (int) ((1l * res * a) % kk); } a = (int) ((1l * a * a) % kk); e >>= 1; } // out.println(res+" "+x); return res % kk; } static TreeSet<Integer> trr; static class qu implements Comparable<qu> { long i, j; qu(long l, long r) { i = l; j = r; } public String toString() { return i + " " + j; } public int compareTo(qu o) { if(o.j==j) { if(i>o.i) return 1; return -1; } if(j>o.j) return 1; return -1; } } static class pair { int to; int number; pair(int t, int n) { number = n; to = t; } public String toString() { return to + " " + number; } } static double modPow(double a, int e) { double res = 1; while (e > 0) { if ((e & 1) == 1) res = (res * a); a = (a * a); e >>= 1; } return res; } static boolean[] in; /* * static void mst() { Arrays.sort(ed); UnionFind uf=new UnionFind(n); for(int * i=0;i<m;i++) { edge w=ed[i]; if(!uf.union(w.from, w.to)) continue; * in[i]=true; } } */ static class edge implements Comparable<edge> { int from; int to; int number; edge(int f, int t, int n) { from = f; to = t; number = n; } public String toString() { return from + " " + to + " " + number; } public int compareTo(edge f) { return number - f.number; } } static class seg implements Comparable<seg> { int a; int b; seg(int s, int e) { a = s; b = e; } public String toString() { return a + " " + b; } public int compareTo(seg o) { // if(a==o.a) return o.b - b; // return } } static long power(int i) { // if(i==0) // return 1; long a = 1; for (int k = 0; k < i; k++) a *= i; return a; } static void seive(int N) { si = new int[N]; primes = new ArrayList<>(); si[1] = 1; for (int i = 2; i < N; i++) { if (si[i] == 0) { si[i] = i; primes.add(i); } for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++) si[primes.get(j) * i] = primes.get(j); } } static long fac(int n) { if (n == 0) return fac[n] = 1; if (n == 1) return fac[n] = 1; long ans = 1; for (int i = 1; i <= n; i++) fac[i] = ans = (i % mod * ans % mod) % mod; return ans % mod; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class unionfind { int[] p; int[] size; unionfind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } Arrays.fill(size, 1); } int findSet(int v) { if (v == p[v]) return v; return p[v] = findSet(p[v]); } boolean sameSet(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; return false; } int max() { int max = 0; for (int i = 0; i < size.length; i++) if (size[i] > max) max = size[i]; return max; } boolean combine(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; if (size[a] > size[b]) { p[b] = a; size[a] += size[b]; } else { p[a] = b; size[b] += size[a]; } return false; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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
import java.io.*; import java.util.*; public class MainClass { public static void main(String[] args)throws IOException { Reader in = new Reader(); int t = in.nextInt(); StringBuilder stringBuilder = new StringBuilder(); while (t-- > 0) { int n = in.nextInt(); long s = in.nextLong(); long[] L = new long[n]; long[] R = new long[n]; long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; for (int i=0;i<n;i++) { L[i] = in.nextLong(); R[i] = in.nextLong(); min = Math.min(min, L[i]); max = Math.max(max, R[i]); } long l = min; long r = max; long ans = -1; while (l <= r) { long mid = (l + r) / 2; if (check(L, R, mid, s)) { ans = mid; l = mid + 1; } else r = mid - 1; } stringBuilder.append(ans).append("\n"); } System.out.println(stringBuilder); } public static boolean check(long[] L, long[] R, long x, long s) { int c1 = 0; int c2 = 0; int c3 = 0; int n = L.length; long sum = 0L; TreeMap<Long, Integer> h = new TreeMap<>(); for (int i=0;i<n;i++) { if (R[i] < x) { c1++; sum += L[i]; } else if (x <= L[i]) { c2++; sum += Math.max(x, L[i]); } else { if (!h.containsKey(L[i])) h.put(L[i], 1); else h.put(L[i], h.get(L[i]) + 1); c3++; } } if (c2 + c3 < (n + 1) / 2) return false; else { int req = (n + 1) / 2 - c2; sum += req * x; for (int i=0;i<req;i++) { long key = h.lastKey(); h.put(key, h.get(key) - 1); if (h.get(key) == 0) h.remove(key); } Iterator iterator = h.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry)iterator.next(); long key = (long)element.getKey(); int val = (int)element.getValue(); sum += key * val; } if (sum <= s) return true; return false; } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; int main() { int q; scanf("%d", &q); while (q--) { int n; long long s; scanf("%d %I64d", &n, &s); long long deb = 0, fin = s; int l[n], r[n]; for (int i = 0; i < n; i++) { scanf("%d %d", &l[i], &r[i]); s -= l[i]; } while (deb < fin) { long long mid = (deb + fin + 1) / 2; priority_queue<int> suiv; for (int i = 0; i < n; i++) { if (r[i] >= mid) suiv.push(l[i]); } if ((int)suiv.size() < (n + 1) / 2) { fin = mid - 1; continue; } long long spend = 0; for (int i = 0; i < (n + 1) / 2; i++) { spend += max(0ll, mid - suiv.top()); suiv.pop(); } if (spend <= s) deb = mid; else fin = mid - 1; } printf("%I64d\n", deb); } 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.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } 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; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static HashMap<Long, Pair> sort(HashMap<Long, Pair> hm) { // Create a list from elements of HashMap List<Map.Entry<Long, Pair> > list = new LinkedList<Map.Entry<Long, Pair> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Long, Pair> >() { public int compare(Map.Entry<Long, Pair> o1, Map.Entry<Long, Pair> o2) { return (int) ((o1.getValue().y)-(o2.getValue().y)); } }); // put data from sorted list to hashmap HashMap<Long, Pair> temp = new LinkedHashMap<Long, Pair>(); for (Map.Entry<Long, Pair> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static long ncr(long n, int k) { long m=(long)1e9+7; long C[] = new long[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = (C[j]%m + C[j-1]%m)%m; } return C[k]%m; } static long high(long n) { long p = (long)(Math.log(n) / Math.log(2L)); return (long)Math.pow(2L, p); } static int findd(int a){ if (parent[a]!=a){ parent[a] = findd(parent[a]); } return parent[a]; } static int parent[]; static ArrayList<Integer>list=new ArrayList<Integer>(); static HashMap<Integer,Integer>map; static boolean find(int n,int f) { if(map.containsKey(n)) { if(map.get(n)>=f) { map.put(n, map.get(n)-f); if(map.get(n)==0) map.remove(n); return true; } else { f-=map.get(n); map.remove(n); if(find(n/2,2*f)) return true; else return false; } } else if(n>1) { if(find(n/2,2*f)) return true; else return false; } else return false; } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static ArrayList<Character>li=new ArrayList<Character>(); static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } for(int i=0;i<len;i++) System.out.println(tailTable[i]); return len; } static int common(ArrayList gp[],int a,int b) { int ans=0; for(int i=0;i<gp[a].size();i++) { if(gp[b].contains(gp[a].get(i))) ans++; } return ans; } static long power(long x, long y) { long mod=1000000007L; if (y == 0) return 1; else if (y % 2 == 0) return (power(x, y / 2)%mod * power(x, y / 2)%mod)%mod; else return (x%mod * power(x, y / 2)%mod * power(x, y / 2)%mod)%mod; } static int sum(int n) { int ans=0; while(n>0) { ans+=n%10; n/=10; } return ans; } static int isPrime[]; static void sieve() { isPrime[1]=1; isPrime[0]=1; for(int i=2;i*i<=300;i++) { if(isPrime[i]==0) { for(int j=i*i;j<300;j+=i)isPrime[j]=1; } } } static ArrayList<Integer>v; static long dp[][][][];static long k; static long memo(String s,int index,int sum,int rem,int tight) { if(index==s.length()) { if(isPrime[sum]==0&&rem==0) return 1; return 0; } if(dp[index][sum][rem][tight]!=-1) return dp[index][sum][rem][tight]; //int limit=0; int limit=(tight==1)?s.charAt(index):9; if(tight==1) limit=s.charAt(index)-'0'; else limit=9; int ans=0; for(int i=0;i<=limit;i++) { int ct=0; if(i==s.charAt(index)-'0') ct=tight; ans+=memo(s,index+1,sum+i,(int)((10*rem+i)%k),ct); } return dp[index][sum][rem][tight]=ans; } static long solve(long n) { for(int i=0;i<15;i++) { for(int j=0;j<200;j++) { for(int k=0;k<4001;k++) { for(int l=0;l<2;l++) { dp[i][j][k][l]=-1; } } } } return memo(String.valueOf(n),0,0,0,1); } static boolean check(int n) { int sum=0; while(n>0) { sum+=n%10; n=n/10; } if(isPrime[sum]==0)return true; return false; } static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret%mod; } static class Pair implements Comparable<Pair>{ long x;long y; Pair(long x,long y){ this.x=x; this.y=y; // this.i=i; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if(x==o.x) return Long.compare(y, o.y); return Long.compare(x, o.x); } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); //ArrayList<String>list=new ArrayList<String>(); TreeMap<Integer,Integer>map=new TreeMap<Integer,Integer>(); HashMap<Integer,Integer>mp=new HashMap<Integer,Integer>(); ArrayList<Integer>list=new ArrayList<Integer>(); // TreeSet<Integer>set=new TreeSet<Integer>(); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); long mon=in.nextLong(); Pair a[]=new Pair[n]; for(int i=0;i<n;i++) { long x=in.nextLong(); long y=in.nextLong(); a[i]=new Pair(x,y); } Arrays.sort(a); long r=mon;long l=0;long ans=0; while(l<r) { // System.out.println(l+" "+r); long mid=(r+l+1)/2;long sum=0; ans=mid; for(int i=0;i<n;i++) sum+=a[i].x; int ct=0; for(int i=n-1;i>=0&&ct<((n/2)+1);i--) { if(a[i].y>=mid) { ct++; sum+=Math.max(0, mid-a[i].x); } } if(ct==((n/2)+1)&&sum<=mon) l=mid; else r=mid-1; } out.println(l); out.flush(); } } }
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 INF = 1e9 + 200ll; bool can(vector<pair<int, int>> a, long long tar, int n, long long s) { int cnt = 0; long long sum = 0ll; vector<int> use; for (int i = 0; i < n; ++i) { if (a[i].second < tar) { sum += (long long)a[i].first; } else if (a[i].first >= tar) { sum += (long long)a[i].first; cnt++; } else { use.push_back(a[i].first); } } int want = max(0, (n + 1) / 2 - cnt); if (want > use.size()) return false; for (int i = 0; i < use.size(); ++i) { if (i < use.size() - want) { sum += (long long)use[i]; } else { sum += tar; } } return sum <= s; } int main() { ios::sync_with_stdio(0); int t; cin >> t; while (t--) { int n; long long s; cin >> n >> s; vector<pair<int, int>> a(n); for (int i = 0; i < n; ++i) { cin >> a[i].first >> a[i].second; } sort(a.begin(), a.end()); long long ans = 0ll; long long l = 0ll, r = INF; while (l <= r) { long long mid = (l + r) / 2ll; if (can(a, mid, n, s)) { l = mid + 1ll; ans = mid; } else { r = mid - 1ll; } } 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.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } 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; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static HashMap<Long, Pair> sort(HashMap<Long, Pair> hm) { // Create a list from elements of HashMap List<Map.Entry<Long, Pair> > list = new LinkedList<Map.Entry<Long, Pair> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Long, Pair> >() { public int compare(Map.Entry<Long, Pair> o1, Map.Entry<Long, Pair> o2) { return (int) ((o1.getValue().y)-(o2.getValue().y)); } }); // put data from sorted list to hashmap HashMap<Long, Pair> temp = new LinkedHashMap<Long, Pair>(); for (Map.Entry<Long, Pair> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static long ncr(long n, int k) { long m=(long)1e9+7; long C[] = new long[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = (C[j]%m + C[j-1]%m)%m; } return C[k]%m; } static long high(long n) { long p = (long)(Math.log(n) / Math.log(2L)); return (long)Math.pow(2L, p); } static int findd(int a){ if (parent[a]!=a){ parent[a] = findd(parent[a]); } return parent[a]; } static int parent[]; static ArrayList<Integer>list=new ArrayList<Integer>(); static HashMap<Integer,Integer>map; static boolean find(int n,int f) { if(map.containsKey(n)) { if(map.get(n)>=f) { map.put(n, map.get(n)-f); if(map.get(n)==0) map.remove(n); return true; } else { f-=map.get(n); map.remove(n); if(find(n/2,2*f)) return true; else return false; } } else if(n>1) { if(find(n/2,2*f)) return true; else return false; } else return false; } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static ArrayList<Character>li=new ArrayList<Character>(); static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } for(int i=0;i<len;i++) System.out.println(tailTable[i]); return len; } static int common(ArrayList gp[],int a,int b) { int ans=0; for(int i=0;i<gp[a].size();i++) { if(gp[b].contains(gp[a].get(i))) ans++; } return ans; } static long power(long x, long y) { long mod=1000000007L; if (y == 0) return 1; else if (y % 2 == 0) return (power(x, y / 2)%mod * power(x, y / 2)%mod)%mod; else return (x%mod * power(x, y / 2)%mod * power(x, y / 2)%mod)%mod; } static int sum(int n) { int ans=0; while(n>0) { ans+=n%10; n/=10; } return ans; } static int isPrime[]; static void sieve() { isPrime[1]=1; isPrime[0]=1; for(int i=2;i*i<=300;i++) { if(isPrime[i]==0) { for(int j=i*i;j<300;j+=i)isPrime[j]=1; } } } static ArrayList<Integer>v; static long dp[][][][];static long k; static long memo(String s,int index,int sum,int rem,int tight) { if(index==s.length()) { if(isPrime[sum]==0&&rem==0) return 1; return 0; } if(dp[index][sum][rem][tight]!=-1) return dp[index][sum][rem][tight]; //int limit=0; int limit=(tight==1)?s.charAt(index):9; if(tight==1) limit=s.charAt(index)-'0'; else limit=9; int ans=0; for(int i=0;i<=limit;i++) { int ct=0; if(i==s.charAt(index)-'0') ct=tight; ans+=memo(s,index+1,sum+i,(int)((10*rem+i)%k),ct); } return dp[index][sum][rem][tight]=ans; } static long solve(long n) { for(int i=0;i<15;i++) { for(int j=0;j<200;j++) { for(int k=0;k<4001;k++) { for(int l=0;l<2;l++) { dp[i][j][k][l]=-1; } } } } return memo(String.valueOf(n),0,0,0,1); } static boolean check(int n) { int sum=0; while(n>0) { sum+=n%10; n=n/10; } if(isPrime[sum]==0)return true; return false; } static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret%mod; } static class Pair implements Comparable<Pair>{ long x;long y; Pair(long x,long y){ this.x=x; this.y=y; // this.i=i; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if(x==o.x) return Long.compare(y, o.y); return Long.compare(x, o.x); } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); //ArrayList<String>list=new ArrayList<String>(); TreeMap<Integer,Integer>map=new TreeMap<Integer,Integer>(); HashMap<Integer,Integer>mp=new HashMap<Integer,Integer>(); ArrayList<Integer>list=new ArrayList<Integer>(); // TreeSet<Integer>set=new TreeSet<Integer>(); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); long mon=in.nextLong(); Pair a[]=new Pair[n]; for(int i=0;i<n;i++) { long x=in.nextLong(); long y=in.nextLong(); a[i]=new Pair(x,y); } Arrays.sort(a); long r=mon;long l=0;long ans=0; while(l<=r) { // System.out.println(l+" "+r); long mid=(r+l)/2;long sum=0; ans=mid; for(int i=0;i<n;i++) sum+=a[i].x; int ct=0; for(int i=n-1;i>=0&&ct<((n/2)+1);i--) { if(a[i].y>=mid) { ct++; sum+=Math.max(0, mid-a[i].x); } } if(ct==((n/2)+1)&&sum<=mon) l=mid+1; else r=mid-1; } out.println(l-1); out.flush(); } } }
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; pair<long long, long long> a[200010]; long long n, s; bool ok(long long x) { long long cnt = 0, left = s; for (long long i = 0; i < n; i++) left -= a[i].first; for (long long i = 0; i < n; i++) { if (a[i].first >= x) cnt++; else if (a[i].second >= x) { if (cnt <= n / 2) if (left - (x - a[i].first) >= 0) left -= (x - a[i].first), cnt++; } } return (cnt > n / 2); } signed main() { long long t; cin >> t; while (t--) { cin >> n >> s; for (long long i = 0; i < n; i++) cin >> a[i].first >> a[i].second; sort(a, a + n, greater<pair<long long, long long>>()); long long ub = 1000000001, lb = 0; while (ub - lb > 1) { long long mid = ub + lb >> 1; if (ok(mid)) lb = mid; else ub = mid; } cout << lb << 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; long long n, s; vector<pair<long long, long long> > arr; bool can(long long x) { long long ans = 0; vector<pair<long long, long long> > todo; for (long long i = 0; i < n; i++) { if (arr[i].second < x) todo.push_back(arr[i]); } for (long long i = 0; i < n; i++) { if (arr[i].second >= x) todo.push_back(arr[i]); } long long ct = 0; for (ct = 0; ct < n; ct++) { pair<long long, long long> aux = todo[ct]; if (ct < n / 2) { ans += aux.first; } if (ct >= n / 2) { if (aux.second < x) return false; ans += max(x, aux.first); } } return ans <= s; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long T; cin >> T; while (T--) { cin >> n >> s; arr.clear(); arr.resize(n); for (long long i = 0; i < n; i++) { cin >> arr[i].first >> arr[i].second; } sort(arr.begin(), arr.end()); long long low = 1, high = s, ans = 0, mid; while (low <= high) { mid = (low + high) / 2; if (can(mid)) { ans = mid; low = mid + 1; } else { high = 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 inf = 0x3f3f3f3f; const int N = 2e5 + 10; int n; long long s; struct node { int l, r; bool operator<(const node& a) const { return l < a.l; } } p[N]; vector<int> g; int judge(long long x) { g.clear(); long long sum = 0, cnt1 = 0, cnt2 = 0; for (int i = 1; i <= n; i++) { if (p[i].r < x) sum += p[i].l, cnt1++; else if (p[i].l > x) sum += p[i].l, cnt2++; else g.push_back(i); } if (cnt1 > n / 2) return 0; if (cnt2 > n / 2) return 1; for (int i = 0; i < n / 2 - cnt1; i++) { sum += p[g[i]].l; } sum += (n / 2 + 1 - cnt2) * x; if (sum <= s) return 1; return 0; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%lld", &n, &s); for (int i = 1; i <= n; i++) scanf("%d%d", &p[i].l, &p[i].r); sort(p + 1, p + n + 1); long long left = 0, right = 1e9, mid, ans; while (right >= left) { mid = (left + right) >> 1; if (judge(mid)) ans = mid, left = mid + 1; else right = mid - 1; } printf("%lld\n", ans); } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
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 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
import sys input=sys.stdin.buffer.readline def check(num): count1 = 0 count2 = 0 spent = 0 left = [] for i in l: if i[0] > num: count2 += 1 spent += i[0] elif i[1] < num: count1 += 1 spent += i[0] else: left.append(i) if count2 > n // 2 + 1: return True elif count1 > n // 2: return False else: # print (num,left,spent,count2,count1) for i in left: if count2 != n // 2 + 1: spent += num count2 += 1 else: spent += i[0] count1 += 1 # print (num,left,spent,count2,count1) if count2 == n // 2 + 1 and count1 == n // 2 and spent <= s: return True return False for nt in range(int(input())): n, s = map(int, input().split()) l = [] for i in range(n): a, b = map(int, input().split()) l.append((a, b)) l.sort(reverse=True) if n == 1: print(min(l[0][1], s)) continue low = 0 high = 10 ** 10 while low < high: mid = (low + high) // 2 if check(mid): low = mid + 1 else: high = mid - 1 if check(low): print(low) else: print(low - 1)
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; 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 long long MOD = (long long)(1e9 + 7); const long long N = 200007; vector<pair<long long, long long>> v; long long s; int n; int sure(long long median) { long long cnt1 = 0; long long cnt2 = 0; long long cnt3 = 0; long long sum = 0; vector<long long> tmp; for (auto ele : v) { long long l = ele.first; long long r = ele.second; if (r < median) { cnt1 += 1; sum += l; } else if (l > median) { cnt3 += 1; sum += l; } else { cnt2 += 1; tmp.push_back(l); } } long long mn = (n - 1) / 2; if (cnt1 > mn) { return 0; } else if (cnt3 > mn) { return 2; } int idx = 0; while (cnt1 < mn) { cnt1 += 1; sum += tmp[idx]; idx += 1; } for (int i = idx; i < tmp.size(); i++) { sum += median; } if (sum > s) { return 0; } else if (cnt2 != 0) { return 1; } else { return 2; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ; int tt; cin >> tt; for (int t = 1; t <= tt; t++) { v.clear(); cin >> n >> s; for (int i = 0; i < n; i++) { long long x, y; cin >> x >> y; v.push_back({x, y}); } sort(v.begin(), v.end()); long long l = 1; long long r = MOD; long long ans = 0; while (l <= r) { long long mid = (l + r) / 2; if (sure(mid) == 1) { ans = mid; l = mid + 1; } else if (sure(mid) == 2) { 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; using ll = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { ll n, s; cin >> n >> s; vector<array<int, 2>> ranges(n); for (int i = 0; i < n; i++) { cin >> ranges[i][0] >> ranges[i][1]; } int l = 0, r = 1e9 + 1; auto check = [&](ll x) { int ok = 1; int rlessmid = 0, lgreatemid = 0; ll curs = s; vector<int> l; for (int i = 0; i < n; i++) { if (ranges[i][1] < x) rlessmid++, curs -= ranges[i][0]; else if (ranges[i][0] >= x) lgreatemid++, curs -= ranges[i][0]; else { l.push_back(ranges[i][0]); } } if (rlessmid > n / 2) return 0; if (lgreatemid > n / 2) return 1; sort(l.begin(), l.end()); int need = n / 2 - rlessmid; for (int j = 0; j < need; j++) { curs -= l[j]; } if (curs >= x * (l.size() - need)) return 1; return 0; }; while (r - l > 1) { int mid = l + (r - l) / 2; if (check(mid)) l = mid; else r = mid; } 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
#include <bits/stdc++.h> using namespace std; const int64_t MOD = 1000000007; int64_t l[200001]; int64_t r[200001]; int64_t get(int64_t x, int64_t s, int64_t n) { vector<int64_t> arr; int64_t a = 0, b = 0; for (int64_t i = 1; i <= n; i++) { if (r[i] < x) s -= l[i], a++; else if (l[i] >= x) s -= l[i], b++; else arr.push_back(l[i]); } if (s < 0 || a > n / 2) return false; sort(arr.begin(), arr.end()); for (int64_t i = 0; i < arr.size() && a < (n / 2); i++) s -= arr[i], a++; s -= (n - a - b) * x; if (s < 0) return false; return true; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); int64_t t; cin >> t; while (t--) { int64_t n, s; cin >> n >> s; for (int64_t i = 1; i <= n; i++) cin >> l[i] >> r[i]; int64_t lo = 0, hi = s; while (lo <= hi) { int64_t mi = (lo + hi) >> 1; if (get(mi, s, n)) lo = mi + 1; else hi = mi - 1; } cout << hi << "\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
// @uthor -: puneet // TimeStamp -: 11:27 PM - 31/10/19 import java.io.*; import java.math.BigInteger; import java.util.*; public class Bserach implements Runnable { public void solve() { int t=in.ni(); while (t-->0){ ArrayList<Pair> list=new ArrayList<>(); int n=in.ni(); long s=in.nl(); for(int i=0;i<n;++i){ list.add(new Pair(in.nl(),in.nl())); } Collections.sort(list); // out.println(list); long low=1L,high=(long)2E14+1L; while (low< high){ long mid=(low+high)>>1L; if(isOk(s,mid,list)){ low=mid+1; }else { high=mid; } } out.println(low-1); } } boolean isOk(long s,long m,ArrayList<Pair> list){ int n=list.size(); long sum=0L; int cnt=0; ArrayList<Long> remain = new ArrayList<>(); for(int i=0;i<n;++i){ if(list.get(i).r<m) sum+=list.get(i).l; else if(list.get(i).l>m) { sum += list.get(i).l; cnt++; }else { remain.add(list.get(i).l); } } int need=Math.max(0,(n+1)/2-cnt); if(need>remain.size() || need<0) return false; for(int i=0;i<remain.size();++i){ if(i < remain.size() - need) sum += remain.get(i); else sum += m; } return s>=sum; } class Pair implements Comparable<Pair> { long l,r; public Pair(long l, long r) { this.l = l; this.r = r; } @Override public int compareTo(Pair pair) { return Long.compare(l,pair.l); } @Override public String toString() { return l+" "+r; } } /* -------------------- Templates and Input Classes -------------------------------*/ @Override public void run() { long time = System.currentTimeMillis(); try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.flush(); System.err.println(System.currentTimeMillis() - time); } private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { // new Thread(null, new Q4(), "Main", 1 << 26).start(); new Bserach().run(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (System.getProperty("user.name").equals("puneet")) { outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt"); inputStream = new FileInputStream("/home/puneet/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } private void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } public long ModPow(long x, long y, long MOD) { long res = 1L; x = x % MOD; while (y >= 1) { if ((y & 1) > 0) res = (res * x) % MOD; x = (x * x) % MOD; y >>= 1; } return res; } public int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastInput { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastInput(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String ns() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(ns()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nc() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nd() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, ni()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, ni()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String next() { return ns(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] intarr(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } public double[] doublearr(int n) { double arr[] = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nd(); } return arr; } public double[][] doublearr(int n, int m) { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nd(); } } return arr; } public int[][] intarr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = ni(); } } return arr; } public long[][] longarr(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nl(); } } return arr; } public long[] longarr(int n) { long arr[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; const long long inf = 1e14 + 5; inline long long min(long long a, long long b) { return a < b ? a : b; } struct Node { int l, r; } a[MAXN]; inline bool cmp_l(const Node &p, const Node &q) { return p.l < q.l; } int n; long long s; bool chk(int mid) { int cntl = n >> 1, cntr = (n + 1) >> 1; long long res = 0; for (int i = 1; i <= n; ++i) { if (a[i].r < mid) { --cntl; if (cntl < 0) return 0; res += a[i].l; } else if (a[i].l > mid) { --cntr; if (cntr < 0) return 0; res += a[i].l; } if (res > s) return 0; } for (int i = 1; i <= n; ++i) if (a[i].l <= mid && mid <= a[i].r) { if (cntl) { --cntl; res += a[i].l; } else { --cntr; res += mid; } if (res > s) return 0; } return 1; } void solve(void) { cin >> n >> s; for (int i = 1; i <= n; ++i) cin >> a[i].l >> a[i].r; sort(a + 1, a + n + 1, cmp_l); int l = a[(n >> 1) + 1].l, r = 1e9; while (l < r) { int mid = (l + r + 1) >> 1; if (chk(mid)) l = mid; else r = mid - 1; } printf("%d\n", l); } int main(void) { int T; scanf("%d", &T); while (T--) solve(); return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; bool prime[1000001]; long long spf[10000001]; long long f[300005]; long long pow1(long long x, long long y) { long long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if (y & 1) res = (res * x) % mod; y = y >> 1; x = (x * x) % mod; } return res; } long long divide(long long n) { return pow1(n, mod - 2); } long long ncr(long long n, long long r) { if (n < r) return 0; return (f[n] * ((divide(f[r]) * divide(f[n - r])) % mod)) % mod; } void sieve() { memset(prime, true, sizeof(prime)); for (long long i = 2; i * i <= 1000000; i++) if (prime[i]) for (long long j = i * i; j <= 1000000; j += i) prime[j] = false; prime[0] = prime[1] = false; } void fastsieve() { spf[1] = 1; for (int i = 2; i <= 1e7; i++) spf[i] = i; for (int i = 4; i <= 1e7; i += 2) spf[i] = 2; for (int i = 3; i * i <= 1e7; i++) { if (spf[i] == i) { for (int j = i * i; j <= 1e7; j += i) if (spf[j] == j) spf[j] = i; } } } vector<long long> factorize(long long n) { long long count = 0; vector<long long> fac; while (!(n % 2)) { n >>= 1; count++; } if (count % 2) fac.push_back(2ll); for (long long i = 3; i <= sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count % 2) fac.push_back(i); } if (n > 2) fac.push_back(n); return fac; } vector<long long> fastfactorize(long long n) { vector<long long> v; long long prev = 0, cnt = 0; while (n != 1) { if (prev == spf[n]) cnt++; else { if (cnt % 2) v.push_back(prev); cnt = 1; prev = spf[n]; } n /= spf[n]; if (n == 1) { if (cnt % 2) v.push_back(prev); cnt = 1; prev = spf[n]; } } return v; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long t; cin >> t; while (t--) { long long n, s, i, ans = 0; cin >> n >> s; vector<pair<long long, long long>> v; for (i = 0; i < n; i++) { long long l, r; cin >> l >> r; v.push_back({l, r}); } sort(v.begin(), v.end()); long long l = 0, r = 1e9 + 1; while (l <= r) { long long mid = (l + r) / 2, cnt = 0, sum = 0; for (i = n - 1; i >= 0; i--) { if (mid <= v[i].second && cnt < (n + 1) / 2) { cnt++; sum += max(mid, v[i].first); } else sum += v[i].first; } if (cnt < (n + 1) / 2 || sum > s) r = mid - 1; else l = mid + 1, ans = mid; } 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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; 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; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.nextInt(); long s = in.nextLong(); Items items[] = new Items[N]; for (int i = 0; i < N; i++) { items[i] = new Items(in.nextInt(), in.nextInt(), i); } Arrays.sort(items, new Comparator<Items>() { public int compare(Items o1, Items o2) { if (o1.left != o2.left) { return o1.left - o2.left; } if (o1.right != o2.right) { return o1.right - o2.right; } return o1.index - o2.index; } }); long low = 0, high = s; long ans = 0; while (low <= high) { long mid = (low + high) / 2; if (possible(mid, items, s)) { low = mid + 1; ans = mid; } else { high = mid - 1; } } out.printLine(ans); } public boolean possible(long x, Items items[], long s) { int N = items.length; long sum = 0; ArrayList<Integer> b = new ArrayList<>(); for (int i = 0; i < N; i++) { sum += items[i].left; if (items[i].right < x) { continue; } b.add(items[i].left); } if (b.size() <= N / 2) { return false; } int count = 0; for (int i = b.size() - 1; count < N / 2 + 1; i--) { if (b.get(i) < x) { sum += x - b.get(i); } count++; } return sum <= s; } class Items { int left; int right; int index; public Items(int left, int right, int index) { this.left = left; this.right = right; this.index = index; } } } static class OutputWriter { PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { BufferedReader in; StringTokenizer tokenizer = null; public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } 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; bool isok(vector<pair<long long, long long> > &A, long long mid, long long s) { long long sum = 0, c = 0, left = 0, n = A.size(); vector<char> visited(n, 0); for (long long i = 0; i < (n); i++) { if (A[i].second < mid) { c++; sum += A[i].first; visited[i] = 1; } if (c > (n - 1) / 2) return false; } left = (n - 1) / 2 - c; for (long long i = 0; i < (n); i++) { if (A[i].second >= mid && A[i].first <= mid) { if (left) { sum += A[i].first; left--; } else sum += mid; } else if (A[i].second >= mid) sum += A[i].first; } if (sum > s) return false; return true; } int main() { long long(t); scanf("%lld", &(t)); ; while (t--) { long long(n); scanf("%lld", &(n)); ; long long(s); scanf("%lld", &(s)); ; vector<pair<long long, long long> > A(n); long long high = 1, low = 1e9; for (long long i = 0; i < (n); i++) { scanf("%lld%lld", &A[i].first, &A[i].second); high = max(high, A[i].second); low = min(low, A[i].first); } sort((A).begin(), (A).end()); while (low <= high) { long long mid = low + (high - low) / 2; if (isok(A, mid, s)) low = mid + 1; else high = mid - 1; } printf("%lld\n", high); } 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 def solve(mid): ans = 0 cnt = 0 tmp = [] for i in range(n): l, r = info[i] if r < mid: ans += l elif mid < l: ans += l cnt += 1 else: tmp.append(l) tmp.sort(reverse = True) nokori = (n+1) // 2 - cnt for i in tmp: if nokori > 0: ans += mid nokori -= 1 else: ans += i if ans <= s and nokori <= 0: return True else: return False q = int(input()) ans = [0]*q for qi in range(q): n, s = map(int, input().split()) info = [list(map(int, input().split())) for i in range(n)] ok = 0 ng = s + 1 while abs(ok - ng) > 1: mid = (ok + ng) // 2 if solve(mid): ok = mid else: ng = mid ans[qi] = ok print('\n'.join(map(str, 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; const int N = 2 * 1e5 + 1; struct Emp { int l, r; } emp[N]; bool search(int m, int n, long long s) { long long sum = 0, cnt = 0; for (int i = n - 1; i >= 0; i--) { if (emp[i].l >= m) cnt++; else if (emp[i].l <= m && emp[i].r >= m && cnt <= n / 2) { sum += m - emp[i].l; cnt++; } } return sum <= s && (cnt >= n / 2 + 1); } void solve() { int n; long long s; cin >> n >> s; for (int i = 0; i < n; i++) { int l, r; cin >> l >> r; emp[i].l = l; emp[i].r = r; s -= l; } sort(emp, emp + n, [](const Emp &x, const Emp &y) { return x.l < y.l; }); int l = 0, r = 1e9 + 1; while (l < r - 1) { int m = l + (r - l) / 2; bool f = search(m, n, s); if (f) l = m; else r = m; } cout << l << "\n"; } int t; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; cin >> t; while (t--) solve(); return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
from sys import stdin, stdout def fun1(n,m,l,s): cl=0 cr=0 cm=0 for i in range(n): if l[i][1]<m: s-=l[i][0] cl+=1 elif l[i][0]>m: s-=l[i][0] cr+=1 else: cm+=1 if (cm+cr)<=1+n//2: s-=m else: s-=l[i][0] if (s<0 or cr>n//2 or cl>n//2): return(0) return(1) def search(n,low,high,l,su): l1=l[::-1] while(low<high): mid=(low+high)//2 if fun1(n,mid,l1,su): low=mid+1 else: high=mid if fun1(n,low,l1,su): return(low) return(low-1) def main(): for _ in range(int(stdin.readline())): n,su=[int(x) for x in stdin.readline().split()] l=[[-1,-1] for i in range(n)] l2=[-1 for i in range(n)] for i in range(n): inp=[int(j) for j in stdin.readline().split()] l[i]=inp l2[i]=inp[0] l.sort() low=int(l[n//2][0]) stdout.write(str((search(n,low,(10**9)+1,l,su)))+'\n') if __name__ == "__main__" : main()
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; long long n, s, curs; const long long maxn = 2e5 + 10; pair<long long, long long> vec[maxn]; long long v[maxn]; bool check(long long mid) { if (mid == s + 1) return false; long long sz = 0; for (long long i = 0; i < n; i++) { if (vec[i].second >= mid) v[sz++] = vec[i].first; } if (sz <= n / 2) return false; long long ans = 0; for (long long i = 1; i <= n / 2 + 1; i++) { if (v[sz - i] < mid) { ans += mid - v[sz - i]; } } return ans <= curs; } int main() { long long t; scanf("%lld", &t); while (t--) { scanf("%lld%lld", &n, &s); curs = s; for (long long i = 0; i < n; i++) { long long a, b; scanf("%lld%lld", &a, &b); vec[i] = make_pair(a, b); curs -= vec[i].first; } sort(vec, vec + n); long long l = vec[n / 2].first, r = s + 1; while (r - l > 1) { long long mid = (r + l) >> 1; if (check(mid)) l = mid; else r = 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
def main(): from array import array import sys input1 = sys.stdin.readline for _ in range(int(input1())): n, s = map(int, input1().split()) n1 = (n + 1) // 2 z = array('i', (0,)) ls = z * n rs = z * n for i in range(n): ls[i], rs[i] = map(int, input1().split()) for l_ in ls: s -= l_ lbs, rbs = 1, 1000000001 while lbs + 1 < rbs: m = (lbs + rbs) // 2 st = sorted((min(l_, m) for (l_, r) in zip(ls, rs) if r >= m), reverse=True) if len(st) >= n1 and m * n1 <= s + sum(st[:n1]): lbs = m else: rbs = m sys.stdout.write(f'{lbs}\n') 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
from sys import stdin input = stdin.readline q = int(input()) for rwre in range(q): n, s = map(int,input().split()) przed = [list(map(int,input().split())) for i in range(n)] przed.sort() przed.reverse() l = 1 p = 10 ** 9 while abs(p - l) > 0: mozna = 1 sr = (p + l + 1) // 2 #try to make median >= sr duze = [przed[i] for i in range(n) if przed[i][1] >= sr ] male = [przed[i] for i in range(n) if przed[i][1] < sr ] if len(duze) <= n // 2: mozna = 0 else: spent = 0 dudes = 0 for i in range(n//2 + 1): spent += max(sr, duze[i][0]) dudes = n//2 + 1 duze = duze[(n//2+1):] for du in duze: spent += du[0] for ma in male: spent += ma[0] if spent > s: mozna = 0 if mozna == 1: l = sr else: p = sr - 1 print((p+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
//Better and correct way to implement comparartor import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); long sum=sc.nextLong(); Pair a[]=new Pair[n]; for( int i=0;i<n;i++) { a[i]=new Pair(sc.nextLong(),sc.nextLong()); } Arrays.sort(a, new myComparator()); /**for( int i=0;i<n;i++) { System.out.println(a[i].x+" "+a[i].y); }*/ long low=0; long high=1000000007; long mid=0; while(low<high) { mid=(low+high+1)/2; //System.out.println(mid); if(possible(mid,a,sum)) { low=mid; } else { high=mid-1; } } System.out.println(low); } } public static boolean possible(long val,Pair a[],long S) { int n=a.length;long sum=0;int cnt=(n+1)/2; for( int i=0;i<n;i++) { sum+=a[i].x; } int count=0;int f=0; for( int i=n-1;i>=0;i--) { if(a[i].x>val) { count++; } if(count==cnt) { f=1;break; } if(val>=a[i].x&&val<=a[i].y) { count++; sum+=Math.max(val-a[i].x,0); } if(count==cnt) { f=1;break; } } if(f==1&&sum<=S) return true; else return false; } } class myComparator implements Comparator<Pair> { public int compare(Pair a, Pair b) { if(Long.compare(a.x,b.x)!=0) return (int)Long.compare(a.x,b.x); else return (int)Long.compare(a.y,b.y); } } class Pair { long x, y; Pair(long x, long y) { this.x=x; this.y=y; } }
JAVA
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 _1251d_salaryChanging { public static class node implements Comparable<node>{ int l,r; public node(int l,int r) { this.l=l; this.r=r; } @Override public int compareTo(node o) { if(this.l<o.l) return -1; else if(this.l==o.l && this.r<o.r) return -1; else if(this.l==o.l && this.r==o.r) return 0; else return 1; } } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-- !=0) { String str=br.readLine(); StringTokenizer st=new StringTokenizer(str); int n=Integer.parseInt(st.nextToken()); long s=Long.parseLong(st.nextToken()); node[]arr=new node[n]; int max=0; for(int i=0;i<n;i++) { String str2=br.readLine(); StringTokenizer st2=new StringTokenizer(str2); node nn=new node( Integer.parseInt(st2.nextToken()), Integer.parseInt(st2.nextToken())); arr[i]=nn; if(nn.r>max) max=nn.r; } Arrays.sort(arr); int lo=0,hi=max; int ans=1; while(lo<=hi) { int mid=(lo+hi)/2; int cnt=(n+1)/2; long sum=0; for(int i=n-1;i>=0;i--) { if(arr[i].r>=mid && cnt>0) { sum+=Math.max(arr[i].l,mid); cnt--; }else { sum+=arr[i].l; } } if(sum<=s && cnt==0) { lo=mid+1; ans=mid; }else hi=mid-1; } System.out.println(ans); } } }
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 io import BytesIO, IOBase from collections import Counter import math as mt 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) def gcd(a, b): if a == 0: return b return gcd(b % a, a) def lcm(a, b): return (a * b) / gcd(a, b) mod = int(1e9) + 7 def power(k, n): if n == 0: return 1 if n % 2: return (power(k, n - 1) * k) % mod t = power(k, n // 2) return (t * t) % mod def totalPrimeFactors(n): count = 0 if (n % 2) == 0: count += 1 while (n % 2) == 0: n //= 2 i = 3 while i * i <= n: if (n % i) == 0: count += 1 while (n % i) == 0: n //= i i += 2 if n > 2: count += 1 return count # #MAXN = int(1e7 + 1) # # spf = [0 for i in range(MAXN)] # # # def sieve(): # spf[1] = 1 # for i in range(2, MAXN): # spf[i] = i # for i in range(4, MAXN, 2): # spf[i] = 2 # # for i in range(3, mt.ceil(mt.sqrt(MAXN))): # if (spf[i] == i): # for j in range(i * i, MAXN, i): # if (spf[j] == j): # spf[j] = i # # # def getFactorization(x): # ret = 0 # while (x != 1): # k = spf[x] # ret += 1 # # ret.add(spf[x]) # while x % k == 0: # x //= k # # return ret # Driver code # precalculating Smallest Prime Factor # sieve() def main(): for _ in range(int(input())): n, s = map(int, input().split()) lr = [] for i in range(n): lr.append(list(map(int, input().split()))) lr.sort() l = 0 r = 10 ** 9 + 1 ans = 0 nb2 = n >> 1 while r-l>1: mid = (l + r) >> 1 low = 0 high = 0 common = [] now = mid for i in lr: if i[1] < mid: low += 1 now += i[0] elif i[0] > mid: high += 1 now += i[0] elif i[0] <= mid <= i[1]: common.append(i) f = 1 if low > nb2 or high > nb2: if low > nb2: f = 0 else: for i in range(nb2 - low): now += common[i][0] now += (nb2 - high) * mid if now > s: f = 0 if f: l = mid ans = max(ans, mid) else: r = mid print(ans) return if __name__ == "__main__": main()
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; int main() { long long t; cin >> t; while (t--) { long long n, k; cin >> n >> k; vector<pair<int, int> > v; for (int i = 0; i < n; i++) { int a, b; cin >> a >> b; v.push_back({a, b}); } sort(v.begin(), v.end()); long long second = 0, e = 2e14; long long mid; while (e - second > 1) { long long cnt = 0, flag = 0, sum = 0; mid = second + (e - second) / 2; vector<int> a; for (int i = 0; i < n; i++) { if (v[i].second < mid) sum += v[i].first; else if (v[i].first >= mid) { sum += v[i].first; cnt++; } else a.push_back(v[i].first); } long long req = max(0LL, (n + 1) / 2 - cnt); if (req > a.size()) flag = 1; else for (int i = 0; i < a.size(); i++) { if (i < a.size() - req) sum += a[i]; else sum += mid; } if (sum <= k && flag == 0) second = mid; else e = mid; } cout << second << 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; long long l[300100], r[300100]; long long n, sal; signed main() { long long t; scanf("%lld", &t); while (t--) { scanf("%lld %lld", &n, &sal); for (long long i = 1; i <= n; i++) scanf("%lld %lld", &l[i], &r[i]); long long bg = 1, nd = 1e9; while (bg < nd) { long long mid = (bg + nd + 1) >> 1ll; multiset<pair<long long, long long>> s, b; for (long long i = 1; i <= n; i++) if (mid <= r[i]) s.emplace(l[i], r[i]); else if (l[i] < mid) b.emplace(l[i], r[i]); long long cnt = (n + 1) / 2; while (s.size() > cnt) { if (s.begin()->first < mid) b.emplace(*s.begin()); s.erase(s.find(*s.begin())); } if (s.size() < (long long)cnt) { nd = mid - 1ll; continue; } long long aux = 0; cnt = (n - 1) / 2; for (auto u : b) { if (cnt == 0) break; aux += 0ll + u.first; cnt--; } for (auto u : s) aux += max(u.first, mid); if (0ll + aux <= 0ll + sal) bg = mid; else nd = mid - 1; } printf("%lld\n", bg); } }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; long long n; struct node { long long l, r; } a1[200005], a2[200005], e[200005]; inline long long read() { long long x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; return x * f; } inline bool cmp1(node x, node y) { return x.r < y.r; } inline bool cmp2(node x, node y) { return x.l < y.l; } inline long long calc(long long x) { long long sum = 0, n1 = 0, n2 = 0; for (long long i = 1; i <= n; i++) if (e[i].r < x) sum += e[i].l, n1++; for (long long i = 1; i <= n; i++) if (e[i].l > x) sum += e[i].l, n2++; if (n1 > n / 2) return (1ll << 60); if (n2 > n / 2) return 0; long long tp = n / 2 - n1; for (long long i = 1; i <= n; i++) if (a1[i].l <= x && a1[i].r >= x) { if (tp) sum += a1[i].l, tp--; else sum += x; } return sum; } int main() { long long T = read(); while (T--) { n = read(); long long s = read(); for (long long i = 1; i <= n; i++) { e[i].l = a1[i].l = a2[i].l = read(); e[i].r = a1[i].r = a2[i].r = read(); } sort(a1 + 1, a1 + n + 1, cmp2); if (n == 1) { cout << min(s, e[1].r) << endl; continue; } long long l = 1, r = (long long)(1e9), ans = 0; while (l <= r) { long long mid = l + r >> 1; if (calc(mid) <= s) ans = mid, l = mid + 1; else r = mid - 1; } printf("%I64d\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; struct node { int l, r; } a[200009]; int n; long long k; bool cmp(node aa, node bb) { if (aa.l == bb.l) return aa.r < bb.r; else return aa.l < bb.l; } int check(int x) { long long ans = 0; int w = 0; for (int i = n; i >= 1; i--) { if (w <= n / 2) { if (a[i].r < x) ans += a[i].l; else { ans += max(a[i].l, x); w++; } } else { ans += a[i].l; } } if (w != (n / 2 + 1)) return 0; if (ans <= k) return 1; else return 0; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%lld", &n, &k); for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].l, &a[i].r); sort(a + 1, a + 1 + n, cmp); int l = 0, r = 1e9; while (l < r) { int mid = (l + r + 1) / 2; if (check(mid) == 1) l = mid; else r = mid - 1; } printf("%d\n", l); } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> const double PI = 3.141592653589793238460; using namespace std; pair<long long int, long long int> ar[200001]; bool isPossible(long long int mid, long long int s, long long int n) { long long int sum = 0; int cnt = 0; vector<int> va, vb, vc; for (int i = 1; i <= n; i++) { if (ar[i].second < mid) va.push_back(i), sum += ar[i].first; else if (ar[i].first > mid) vb.push_back(i), sum += ar[i].first, cnt++; else vc.push_back(i); } int rem = max((long long int)0, n / 2 + 1 - cnt); if (rem > vc.size()) return false; while (vc.size() > 0) { if (rem) sum += mid, rem--; else sum += ar[vc.back()].first; vc.pop_back(); } return sum <= s; } long long int getAns(long long int n, long long int s) { long long int L = ar[1].first; long long int H = 1000000000; long long int res = 1; while (L <= H) { long long int mid = (L + H) / 2; if (isPossible(mid, s, n)) res = max(res, mid), L = mid + 1; else H = mid - 1; } return res; } bool comp(pair<long long int, long long int> a, pair<long long int, long long int> b) { return a.first < b.first; } int main() { long long int t, n, s; cin >> t; while (t--) { cin >> n >> s; for (int i = 1; i <= n; i++) cin >> ar[i].first >> ar[i].second; sort(ar + 1, ar + n + 1, comp); cout << getAns(n, s) << '\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.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]; } if (sum <= key) return true; else return false; } public static long binary_search(long min_k, long max_k, long key) { 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); 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(binary_search(min_k, max_k, s)); } 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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Mufaddal Naya */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DSalaryChanging solver = new DSalaryChanging(); solver.solve(1, in, out); out.close(); } static class DSalaryChanging { public void solve(int testNumber, InputReader c, OutputWriter w) { int tc = c.readInt(); while (tc-- > 0) { int n = c.readInt(); long tot = c.readLong(); Point p[] = new Point[n]; int dummy[] = new int[n]; for (int i = 0; i < n; i++) { int l = c.readInt(), r = c.readInt(); dummy[i] = r; tot -= l; p[i] = new Point(l, r); } Sort.mergeSort(dummy, 0, n); Arrays.sort(p); int upperLimit = dummy[n / 2], lowerLimit = p[n / 2].l; int best = 0; while (lowerLimit <= upperLimit) { int mid = (lowerLimit + upperLimit) / 2; //w.printLine(mid, lowerLimit, upperLimit); int k = query(mid, p, tot); if (k >= mid) { best = k; lowerLimit = mid + 1; } else { upperLimit = mid - 1; } } w.printLine(best); } } private int query(int mid, Point[] p, long tot) { int res[] = new int[p.length]; for (int i = p.length - 1; i >= 0; i--) { if (p[i].l >= mid) { res[i] = p[i].l; continue; } if (p[i].r < mid) { res[i] = p[i].l; continue; } if (mid - p[i].l <= tot) { tot -= (mid - p[i].l); res[i] = mid; } else { res[i] = p[i].l; } } Arrays.sort(res); return res[res.length / 2]; } } static class Point implements Comparable<Point> { int l; int r; public Point(int l, int r) { this.l = l; this.r = r; } public int compareTo(Point o) { if (this.l == o.l) { return this.r - o.r; } return this.l - o.l; } } static class Sort { public static void mergeSort(int[] a, int low, int high) { if (high - low < 2) { return; } int mid = (low + high) >>> 1; mergeSort(a, low, mid); mergeSort(a, mid, high); int[] b = Arrays.copyOfRange(a, low, mid); for (int i = low, j = mid, k = 0; k < b.length; i++) { if (j == high || b[k] <= a[j]) { a[i] = b[k++]; } else { a[i] = a[j++]; } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
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
import java.io.*; import java.util.*; public class Main { static long func(long start,long end,int[][] l,long s) { if(start>end) { return Integer.MIN_VALUE; } long mid=(start+end)/2; long temp=s; int n=l.length; Arrays.sort(l,new Comparator<int[]>() { public int compare(int[] a,int[] b) { if(Math.min(mid, a[1])==Math.min(mid, b[1])) { return Integer.compare(a[0], b[0]); } return Integer.compare(a[1],b[1]); } }); for(int i=0;i<n/2;i++) { s-=l[i][0]; } for(int i=n/2;i<n;i++) { if(l[i][0]<=mid && l[i][1]>=mid) { s-=mid; } else if(mid<=l[i][0]){ s-=l[i][0]; } else if(mid<=l[i][1]){ s-=l[i][1]; } else { s=-1; } } // System.out.println(mid+" "+s); if(s>=0) { return Math.max(mid, func(mid+1,end,l,temp)); } return func(start,mid-1,l,temp); } public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int ttt=1; ttt=f.nextInt(); PrintWriter out=new PrintWriter(System.out); outer:for(int tt=0;tt<ttt;tt++) { int n=f.nextInt(); long s=f.nextLong(); int[][] l=new int[n][2]; for(int i=0;i<n;i++) { l[i]=new int[] {f.nextInt(),f.nextInt()}; } System.out.println(func(0,(long)1e18,l,s)); } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); 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 long long N = 2e5 + 7; const long long INF = 1e9; const long long MOD = INF + 7; long long n, s; vector<pair<long long, long long> > a; bool solve(long long m) { long long idx = (long long)n / 2; long long sm = 0; for (long long i = 0; i < n; i++) { sm += a[i].first; } long long cnt = 0; for (long long i = n - 1; i >= 0 && cnt <= idx; i--) { if (m <= a[i].second) { sm += max(0LL, m - a[i].first); cnt++; } } return cnt == idx + 1 && sm <= s; } void solve() { cin >> n >> s; a.clear(); long long sm = 0; for (long long i = 0, x, y; i < n; i++) { cin >> x >> y; a.push_back({x, y}); sm += x; } sort((a).begin(), (a).end()); long long lo = 0, hi = INF * INF; while (lo < hi) { long long now = sm; long long m = (lo + hi + 1) / 2; if (solve(m)) lo = m; else hi = m - 1; } cout << lo << '\n'; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long t = 1; cin >> t; while (t--) { solve(); } }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; int dirx[] = {1, -1, 0, 0}, diry[] = {0, 0, 1, -1}; long long bigmod(long long x, long long p) { long long res = 1; while (p) { if (p & 1) res = (res * x) % 998244353; x = (x * x) % 998244353; p >>= 1; } return res; } vector<pair<int, int> > inp; int n; long long fun(int mid) { long long sum = mid; multiset<int> both; int low = 0, high = 0; for (int i = 0; i < n; i++) { if (inp[i].second > mid) { sum += inp[i].second; high++; } else if (inp[i].first < mid) { sum += inp[i].second; low++; } else both.insert(inp[i].second); } for (int i = 0; i < n / 2 - low; i++) { sum += *both.begin(); both.erase(both.begin()); } sum += 1LL * mid * (n / 2 - high); return sum; } bool cmp(pair<int, int>& a, pair<int, int>& b) { return a.second < b.second; } int32_t main() { ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) { inp.clear(); cin >> n; long long taka; cin >> taka; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; inp.push_back({y, x}); } sort(inp.begin(), inp.end()); int h = inp[n / 2].first, l, mid, ans; sort(inp.begin(), inp.end(), cmp); l = inp[n / 2].second; while (l <= h) { int mid = (l + h) / 2; if (fun(mid) <= taka) { ans = mid; l = mid + 1; } else h = mid - 1; } cout << ans << "\n"; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import 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()) t = int(input()) while t: t += -1 n, s = map(int, input().split()) l = [] for i in range(n): temp = list(map(int, input().split())) l.append(temp) l.sort() low = 0 high = 10**9 + 10 ans = 0 while 1: ch = 1 mid = (low + high) // 2 cnt = 0 # print(low, high, mid) total = 0 re = 0 for i in range(n): if l[i][1] < mid or mid <= l[i][0]: total += l[i][0] if mid <= l[i][0]: cnt -= -1 if l[i][0] < mid <= l[i][1]: re -= -1 if re < max(0, (n + 1) // 2 - cnt): high = mid - 1 if high < low: ans = low break else: tt = max(0, (n + 1) // 2 - cnt) total += (tt * mid) ddd = 0 for i in range(n): if ddd == re - tt: break if l[i][0] < mid <= l[i][1]: ddd -= -1 total += l[i][0] if total > s: high = mid - 1 if high < low: ans = low break else: low = mid + 1 if high < low: ans = high break # print(ans) mid = max(low, high) # print(l, mid) cnt = 0 total = 0 re = 0 for i in range(n): if l[i][1] < mid or mid <= l[i][0]: total += l[i][0] if mid <= l[i][0]: cnt -= -1 if l[i][0] < mid <= l[i][1]: re -= -1 if re < max(0, (n + 1) // 2 - cnt): ans = min(low, high) else: tt = max(0, (n + 1) // 2 - cnt) total += (tt * mid) ddd = 0 for i in range(n): if ddd == re - tt: break if l[i][0] < mid <= l[i][1]: ddd -= -1 total += l[i][0] if total > s: ans = min(low, high) else: ans = max(low, high) print(ans)
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int t, n; long long s; struct uzi { int l, r; bool operator<(const uzi& t) const { return l > t.l; } } p[N]; int vis[N]; int main() { ios::sync_with_stdio(false); for (cin >> t; t; t--) { cin >> n >> s; long long S = 0; for (int i = 1; i <= n; i++) cin >> p[i].l >> p[i].r, S += p[i].l; sort(p + 1, p + 1 + n); int l = p[n / 2 + 1].l, r = 1e9, ans = 0; while (l <= r) { int mid = l + r >> 1; long long sum = 0; int sz = 0; long long tmp = S; for (int i = 1; i <= n; i++) { if (p[i].l > mid) { sz++; sum += p[i].l; vis[i] = 1; tmp -= p[i].l; } } int tot = 0; for (int i = 1; i <= n; i++) { if (p[i].l <= mid && p[i].r >= mid && sz <= n / 2) { vis[i]++; sz++; tot++; sum += mid; tmp -= p[i].l; } } if (sz <= n / 2) r = mid - 1; else { sum += tmp; if (sum <= s) ans = mid, l = mid + 1; else r = mid - 1; } } cout << ans << '\n'; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import sys from collections import defaultdict def check(l,x,lim): low,high,n=[],[],len(l) for i in range(n): if l[i][1]<x: low.append(l[i][0]) else: high.append(l[i][0]) a,b=len(low),len(high) #high.sort() '''print(x,'x') print(low,'low') print(high,'high') print('-----')''' if b<=n//2: return False s=sum(low) '''if x==79: print(s+(n//2+1)*x,'check') print(low,'low') print(high,'high')''' i=0 for i in range(n//2-a): s+=high[i] for j in range(max(n//2-a,0),b): if high[j]<=x: s+=x else: s+=high[j] if s<=lim: return True return False t=int(sys.stdin.readline()) for _ in range(t): n,s=map(int,sys.stdin.readline().split()) l=[[-1,-1] for _ in range(n)] for i in range(n): u,v=map(int,sys.stdin.readline().split()) l[i]=[u,v] l.sort() high=100000000000000 low,ans=0,-1 while low<=high: mid=(low+high)//2 if check(l,mid,s): ans=max(ans,mid) low=mid+1 else: high=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 itertools import bisect from collections import OrderedDict from sys import stdin, stdout class Solution: def __init__(self, n, s, salary_limits): self.n = n self.half_n = (n-1)//2 self.s = s self.salary_limits = salary_limits # Preprocessing self.l_sorted = sorted(salary_limits, key=lambda limits: limits[0]) self.r_sorted = sorted(salary_limits, key=lambda limits: limits[1]) def cummulative_sum_func(tup1, tup2): return (tup1[0] + tup2[0],) self.l_sorted_sums = [x[0] for x in list(itertools.accumulate( self.l_sorted[::-1], func=cummulative_sum_func))][::-1] self.r_sorted_sums = [x[0] for x in list(itertools.accumulate( self.r_sorted, func=cummulative_sum_func))] self.r_sorted_complementary_sums = self._compute_r_complementary_sums() self.l_sorted_l_projection = list(map(lambda tup: tup[0], self.l_sorted)) self.r_sorted_r_projection = list(map(lambda tup: tup[1], self.r_sorted)) def _compute_r_complementary_sums(self): lo_set = OrderedDict.fromkeys(self.l_sorted[:self.half_n]) for tup in self.l_sorted[:self.half_n]: lo_set[tup] = (1 + lo_set[tup]) if lo_set[tup] is not None else 1 acc = sum(tup[0] for tup in self.l_sorted[:self.half_n]) result = [acc] for sal_limit in self.r_sorted[:self.half_n]: if sal_limit in lo_set: lo_set[sal_limit] -= 1 if lo_set[sal_limit] <= 0: lo_set.pop(sal_limit) acc -= sal_limit[0] else: k, v = lo_set.popitem() if v-1 > 0: lo_set[k] = v-1 acc -= k[0] result.append(acc) return result def _is_possible(self, median_sal): disjoint_sal_limits_overstepping_median = bisect.bisect_right(self.l_sorted_l_projection, median_sal) disjoint_sal_limits_understepping_median = bisect.bisect_left(self.r_sorted_r_projection, median_sal) cost = ( (self.l_sorted_sums[disjoint_sal_limits_overstepping_median] if disjoint_sal_limits_overstepping_median < self.n else 0) + (self.r_sorted_sums[disjoint_sal_limits_understepping_median - 1] if disjoint_sal_limits_understepping_median > 0 else 0) + median_sal * (disjoint_sal_limits_overstepping_median - self.half_n) + self.r_sorted_complementary_sums[disjoint_sal_limits_understepping_median] ) return cost <= self.s def solve(self): ans = self.l_sorted[self.half_n][0] # Binary Search lo = self.l_sorted[self.half_n][0] hi = self.r_sorted[self.half_n][1] while lo <= hi: mid = (lo + hi)//2 if self._is_possible(median_sal=mid): ans = mid lo = mid + 1 else: hi = mid - 1 return ans def main(): t = int(stdin.readline()) for i in range(t): n, s = map(int, stdin.readline().split()) salary_limits = [tuple(map(int, stdin.readline().split())) for i in range(n)] if n == 1: stdout.write(str(min(s, salary_limits[0][1]))) else: solution = Solution(n=n, s=s, salary_limits=salary_limits) stdout.write(str(solution.solve())) stdout.write('\n') # if __name__ == "main": # main() main()
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int q=in.nextInt(); for(int i=0;i<q;i++) { work(); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { int n=in.nextInt(); long s=in.nextLong(); long remain=s; long[][] A=new long[n][]; for(int i=0;i<n;i++) { A[i]=new long[] {in.nextLong(),in.nextLong()}; remain-=A[i][0]; } Arrays.sort(A,new Comparator<long[]>() { public int compare(long[] arr1,long[] arr2) { if(arr1[0]<arr2[0]) { return 1; }else if(arr1[0]>arr2[0]) { return -1; }else { return 0; } } }); long l=A[n/2][0],r=s+1; while(l<r) { long m=(l+r)/2;//中位数 if(check(A,m,remain)) { l=m+1; }else { r=m; } } out.println(l-1); } boolean check(long[][] A,long m,long remain) { int n=A.length; int cnt=0; long cur=0; for(int i=0;i<n;i++) { if(A[i][0]>=m) { cnt++; }else if(A[i][1]>=m) { cnt++; cur+=m-A[i][0]; } if(cur>remain)return false; if(cnt==n/2+1) { return true; } } return false; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } 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
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final int mod = (int)1e9+7; static int N = (int)2e6 + 2; static long[][] salary; public static void main(String[] args) throws Exception { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int test = in.nextInt(); while(test-- > 0) { int n = in.nextInt(); long s = in.nextLong(); salary = new long[n][2]; for(int i = 0; i < n; i++) { salary[i][0] = in.nextInt(); salary[i][1] = in.nextInt(); } Arrays.sort(salary, (long[] a, long[] b) -> Long.compare(a[0], b[0])); long l = 1, r = s, ans = -1; while(l <= r) { long m = (l + r) / 2; if(check(m, n, s)) { ans = m; l = m + 1; } else { r = m - 1; } // out.println(l + " " + r + " " + m); } out.println(ans); } out.flush(); } static boolean check(long m, int n, long s) { Queue<Long> q = new LinkedList(); int left = 0, right = 0; for(int i = 0; i < n; i++) { if(salary[i][0] < m && salary[i][1] < m) { left++; s -= salary[i][0]; } else if(salary[i][0] > m && salary[i][1] > m) { right++; s -= salary[i][0]; } else { q.add(salary[i][0]); } } if(left > n / 2) { return false; } while(q.size() > 0) { if(left < n / 2) { s -= q.poll(); left++; } else { s -= m; q.poll(); break; } } s -= m * q.size(); return s >= 0; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; std::mt19937 rng( (int)std::chrono::steady_clock::now().time_since_epoch().count()); const double EPS = 1e-9; const double PI = acos(-1); const int MOD = 1000000007; vector<pair<long long, long long> > v; int n; long long s; bool test(long long x) { long long sum = 0; for (int i = 0; i < n; i++) sum += v[i].first; int cont = 0; for (int i = n - 1; i >= 0 and cont < (n + 1) / 2; i--) { if (x <= v[i].second) { sum += max(0LL, x - v[i].first); cont++; } } return sum <= s and cont == (n + 1) / 2; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { cin >> n >> s; v.resize(n); for (int i = 0; i < n; i++) { cin >> v[i].first >> v[i].second; } sort(v.begin(), v.end()); long long lo = 0, hi = MOD, ans = -1LL; while (lo <= hi) { long long mi = (lo + hi) / 2LL; if (test(mi)) { ans = mi; lo = mi + 1; } else { hi = mi - 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
def main(): import sys import heapq input = sys.stdin.readline t = int(input()) for _ in range(t): N, S = map(int, input().split()) cost = [] m = [] for _ in range(N): l, r = map(int, input().split()) cost.append((l, r)) m.append(l) m.sort() ok = m[N//2] ng = S+1 mid = (ok+ng)//2 while ng - ok > 1: big = [] small = [] for l, r in cost: if r >= mid: big.append(-l) else: small.append(l) if len(big) < N//2 + 1: ng = mid mid = (ok+ng)//2 continue heapq.heapify(big) C = 0 for i in range(N//2 + 1): C += max(-heapq.heappop(big), mid) for l in big: small.append(-l) C += sum(small) if C <= S: ok = mid else: ng = mid mid = (ok+ng)//2 print(ok) if __name__ == '__main__': main()
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
def main(): t=int(input()) allans=[] for _ in range(t): n,s=readIntArr() lr=[] for __ in range(n): lr.append(readIntArr()) lr.sort(key=lambda x:x[0]) guess=lr[n//2][0] # smallest possible median def isPossible(median): lowerCnt=n//2 upperCnt=n-lowerCnt lower=[] upper=[] unsure=[] for l,r in lr: if r<median: lower.append([l,r]) elif l>=median: upper.append([l,r]) else: unsure.append([l,r]) if len(lower)>lowerCnt: return False elif len(upper)>upperCnt: # should not be possible assert False unsure.sort(key=lambda x:x[0]) for i in range(len(unsure)): if len(lower)<lowerCnt: # move to lower lower.append(unsure[i]) else: # move to upper upper.append(unsure[i]) minRequiredS=0 for l,r in lower: minRequiredS+=l for l,r in upper: minRequiredS+=max(l,median) return s>=minRequiredS b=s while b>0: while isPossible(guess+b): guess+=b b//=2 allans.append(guess) 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 int N = 2e5 + 10; long long s, sum; int T, n; pair<int, int> L[N]; bool judge(long long val) { long long v = s; int num = (n + 1) / 2; for (int i = 1; i <= n; i++) { v -= L[i].first; if (L[i].first >= val) num--; } vector<int> cost; for (int i = 1; i <= n; i++) { if (L[i].first < val and L[i].second >= val) { cost.push_back(val - L[i].first); } } sort(cost.begin(), cost.end()); if (cost.size() < num) return false; for (int i = 0; i < num; i++) v -= cost[i]; return v >= 0; } int main() { cin >> T; while (T--) { cin >> n >> s; sum = 0; for (int i = 1; i <= n; i++) cin >> L[i].first >> L[i].second, sum += L[i].first; sort(L + 1, L + 1 + n); int mid = (n + 1) / 2; long long l = L[mid].first, r = 1e10; long long ans = l; while (l <= r) { long long m = (l + r) / 2; if (judge(m)) { ans = max(ans, m); l = m + 1; } else { r = m - 1; } } cout << ans << endl; } }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; bool isValid(const long long& median, const vector<pair<long long, long long>>& ranges, const long long& s) { long long select_count = 0; long long sum = 0; for (int i = 0; i < ranges.size(); i++) { if (select_count < (ranges.size() + 1) / 2 && ranges[i].second >= median) { sum += max(ranges[i].first, median); select_count++; } else { sum += ranges[i].first; } } if (select_count < (ranges.size() + 1) / 2) { return false; } else { return (sum <= s); } } int main() { int t; cin >> t; for (int tc = 0; tc < t; tc++) { long long n, s; cin >> n >> s; vector<pair<long long, long long>> ranges(n); long long min_low = s; long long max_high = 0; for (int i = 0; i < n; i++) { cin >> ranges[i].first >> ranges[i].second; min_low = min(ranges[i].first, min_low); max_high = max(ranges[i].second, max_high); } sort(ranges.begin(), ranges.end(), greater<pair<long long, long long>>()); long long low = min_low; long long high = max_high; long long middle; while (low < high) { middle = (low + high + 1) / 2; if (isValid(middle, ranges, s)) { low = middle; } else { high = middle - 1; } } cout << low << endl; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import sys input = sys.stdin.readline def judge(x): salary = [] left, right = 0, 0 l = [] for li, ri in lr: if ri<x: salary.append(li) left += 1 elif x<li: salary.append(li) right += 1 else: l.append((li, ri)) if left>(n-1)//2 or right>(n-1)//2: return False l.sort(key=lambda k: k[0]) for i in range(len(l)): if i<(n-1)//2-left: salary.append(l[i][0]) else: salary.append(x) return sum(salary)<=s def binary_search(l): r = 10**10 while l<=r: mid = (l+r)//2 if judge(mid): l = mid+1 else: r = mid-1 return r t = int(input()) for _ in range(t): n, s = map(int, input().split()) lr = [tuple(map(int, input().split())) for _ in range(n)] ls = [li for li, _ in lr] ls.sort() ans = binary_search(ls[n//2]) 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.io.BufferedInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.Scanner; public class DTask { private static final String QUICK_ANSWER = "NO"; private final Scanner in; private final StringBuilder out; private final int n; private final long s; int[] l; int[] r; private int min; private int max; private final Integer[] lOrder; private final Integer[] rOrder; public DTask(Scanner in, StringBuilder out) { this.in = in; this.out = out; n = nextInt(); s = nextLong(); l = new int[n]; r = new int[n]; lOrder = new Integer[n]; rOrder = new Integer[n]; min = Integer.MAX_VALUE; max = -1; for (int i = 0; i < n; ++i) { lOrder[i] = i; rOrder[i] = i; l[i] = nextInt(); r[i] = nextInt(); min = Math.min(min, l[i]); max = Math.max(max, r[i]); } Arrays.sort(lOrder, Comparator.comparingInt(i -> l[i])); Arrays.sort(rOrder, Comparator.comparingInt(i -> r[i])); } public void solve() throws QuickAnswer { int l = this.l[lOrder[n / 2]]; int r = this.r[rOrder[n / 2]] + 1; while (r - l > 1) { int mid = (l + r) / 2; if (test(mid)) l = mid; else r = mid; } print(l); } private boolean test(final long mid) { long req = 0; int cnt = 0; for (int i = 0; i < n; i++) { int index = rOrder[i]; if (r[index] >= mid) break; req += l[index]; ++cnt; } if (cnt > n / 2) return false; for (int i = 0; i < n; i++) { int index = lOrder[i]; if (r[index] < mid) continue; if (cnt++ < n / 2) { req += l[index]; } else req += Math.max(mid, l[index]); } return req <= s; } // Common functions void quickAnswer(String answer) throws QuickAnswer { throw new QuickAnswer(answer); } void quickAnswer() throws QuickAnswer { quickAnswer(QUICK_ANSWER); } static class QuickAnswer extends Exception { private String answer; public QuickAnswer(String answer) { this.answer = answer; } } void print(Object... args) { String prefix = ""; for (Object arg : args) { out.append(prefix); out.append(arg); prefix = " "; } } void println(Object... args) { print(args); out.append("\n"); } void printsp(Object... args) { print(args); out.append(" "); } int nextInt() { return in.nextInt(); } long nextLong() { return in.nextLong(); } String nextString() { String res = in.nextLine(); return res.trim().isEmpty() ? in.nextLine() : res; } int[] nextInts(int count) { int[] res = new int[count]; for (int i = 0; i < count; ++i) { res[i] = in.nextInt(); } return res; } long[] nextLongs(int count) { long[] res = new long[count]; for (int i = 0; i < count; ++i) { res[i] = in.nextInt(); } return res; } public static void main(String[] args) { doMain(System.in, System.out); } static void doMain(InputStream inStream, PrintStream outStream) { Scanner in = new Scanner(new BufferedInputStream(inStream)).useLocale(Locale.ENGLISH); StringBuilder totalOut = new StringBuilder(); int count = 1; count = in.nextInt(); while (count-- > 0) { try { StringBuilder out = new StringBuilder(); new DTask(in, out).solve(); totalOut.append(out.toString()); } catch (QuickAnswer e) { totalOut.append(e.answer); } if (count > 0) { totalOut.append("\n"); } } outStream.print(totalOut.toString()); } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import sys from collections import defaultdict as dd from collections import deque from fractions import Fraction as f def eprint(*args): print(*args, file=sys.stderr) zz=1 from math import * import copy #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') def li(): return [int(x) for x in input().split()] def fi(): return int(input()) def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def bo(i): return ord(i)-ord('a') from copy import * from bisect import * from itertools import permutations t=fi() def can(mid,s): p=s low=high=0 k=[] for i in range(n): if d[i][1]<mid: p-=d[i][0] low+=1 elif d[i][0]>mid: high+=1 p-=d[i][0] else: p-=mid k.append(d[i]) #print(mid,low,high,p) if low>(n-1)//2 : return False if p>=0: return True #print(k,low,(n-1)//2) for i in range(low,(n-1)//2): if i-low>=len(k): break p+=(mid-k[i-low][0]) #print(p,k) return p>=0 while t>0: t-=1 n,s=mi() d=[] for i in range(n): p=li() d.append(p) d.sort() #print(d) l=0 r=10**10 ans=d[n//2][0] while l<=r: mid=l+(r-l)//2 #print(mid,can(mid,s)) if can(mid,s): ans=mid l=mid+1 else: r=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.io.*; import java.util.*; import java.lang.*; import java.math.*; public class Main extends Thread { boolean[] prime; FastScanner sc; PrintWriter pw; long startTime = System.currentTimeMillis(); final class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public long nlo() { return Long.parseLong(next()); } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int ni() { return Integer.parseInt(next()); } public String nli() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nd() { return Double.parseDouble(next()); } } public Main(ThreadGroup t,Runnable r,String s,long d ) { super(t,r,s,d); } public void run() { sc=new FastScanner(); pw=new PrintWriter(System.out); solve(); pw.flush(); pw.close(); } public static void main(String[] args) { new Main(null,null,"",1<<20).start(); } /////////////------------------------------------////////////// ////////////------------------Main-Logic--------////////////// ///////////-------------------------------------////////////// public static class Pair{ long l; long r; Pair(long x,long y) { l=x; r=y; } } public void solve() { int t=sc.ni(); while(t-->0) { int n=sc.ni(); long max=sc.nlo(); ArrayList<Pair> list=new ArrayList(); for(int i=0;i<n;i++) list.add(new Pair(sc.ni(),sc.ni())); Collections.sort(list,new Comparator<Pair>(){ public int compare(Pair b,Pair a) { long k= b.l-a.l; return k>0?1:(k<0?-1:0); } }); long lft=list.get(n/2).l; long rgt=max; long ans=lft; while(lft<=rgt) { long mid=(lft+rgt)/2L; if(f(mid,list,max)) { lft=mid+1L; ans=mid; } else rgt=mid-1L; } pw.println(ans); } } public static boolean f(long val,ArrayList<Pair> list,long sum) { int n=list.size(); ArrayList<Pair> l1=new ArrayList(); ArrayList<Pair> l2=new ArrayList(); ArrayList<Pair> set=new ArrayList(); int i=0; for(Pair t: list) { if(t.l>val) l2.add(t); else if(t.r<val) l1.add(t); else set.add(t); } Collections.sort(set,new Comparator<Pair>(){ public int compare(Pair a,Pair b) { long k=a.l-b.l; return k<0?-1:(k>0?1:0); } }); if(l1.size()>(n/2)) return false; while(l1.size()<(n/2)) { Pair p=set.get(i++); l1.add(p); } for(;i<set.size();i++) l2.add(set.get(i)); long ans=0; for(Pair p:l1) ans+=p.l; for(Pair p:l2) { if(p.l>val) ans+=p.l; else ans+=val; } if(ans>sum) return false; else return true; } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import sys def highest_median(ranges, s): n = len(ranges) ranges = sorted(ranges) low = ranges[n // 2][0] high = sorted(ranges, key=lambda x: x[1])[n // 2][1] + 1 while low + 1 < high: med = low + (high - low) // 2 smaller = 0 larger = 0 total = 0 for l, h in ranges: if l > med: smaller += 1 total += l elif h < med: larger += 1 total += l if smaller > n // 2: low = med continue if larger > n // 2: high = med # this shouldnt happen with my initialization continue for l, h in ranges: if larger == n // 2: break if l <= med <= h: larger += 1 total += l total += med * (n - larger - smaller) if total > s: high = med else: low = med return low # ranges = [ # [1, 1000000000]] # s = 1337 # print(highest_median(ranges, s)) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ t = int(input().strip()) for i in range(t): line = input().strip() vs = [int(v) for v in line.split(' ')] n, s = vs[0], vs[1] ranges = [] for j in range(n): line = input().strip() vs = [int(v) for v in line.split(' ')] ranges.append(vs) print(highest_median(ranges, s))
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; template <class T> bool umin(T &a, T b) { return a > b ? (a = b, true) : false; } template <class T> bool umax(T &a, T b) { return a < b ? (a = b, true) : false; } long long POW(long long a, long long p, long long M) { if (!p) return 1LL; long long T = POW(a, p / 2, M); T = T * T % M; if (p & 1) T = T * (a % M) % M; return T; } long long SQRT(long long a) { long long b = (long long)sqrtl(((double)a) + 0.5); while (b * b < a) ++b; while (b * b > a) --b; return (b * b == a) ? b : -1; } const long long MOD = 1e9 + 7; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.precision(10); cout << fixed; int q; cin >> q; while (q--) { int n; cin >> n; long long s; cin >> s; vector<pair<long long, long long>> v(n); for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second; sort((v).begin(), (v).end()); long long L = v[n / 2].first; long long R = 1e15; long long ff = L; while (L <= R) { long long mid = L + R; mid /= 2; long long f = 0; int ct = 0; bool ps = false; vector<long long> tt; for (auto i : v) { if (i.first > mid) { f += i.first; ct++; } else if (i.second < mid) f += i.first; else tt.push_back(i.first); } if (tt.size()) { ct++; ps = true; f += mid; tt.pop_back(); } while (ct < (n + 1) / 2 && tt.size()) { ct++; f += mid; tt.pop_back(); } for (auto i : tt) f += i; if (f <= s && ps && ct == (n + 1) / 2) { L = mid + 1; ff = mid; } else R = mid - 1; } cout << ff << endl; } cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s\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 eps = 1e-10; const int INF = 0x3f3f3f3f, N = 1000005, M = 2000005, MOD = 2017; int sgn(double x) { return x < -eps ? -1 : (x < eps ? 0 : 1); } int Rand(int x) { return rand() * rand() % x + 1; } struct node { int l, r; bool operator<(const node &x) const { return l > x.l; } }; int n; long long s; vector<node> a; int check(int mid) { long long now = 0; int count = 0; for (auto p : a) now += p.l; for (auto p : a) { if (p.r >= mid && count < (n + 1) / 2) { count++; now += max(0, mid - p.l); } } return count == (n + 1) / 2 && now <= s; } int Solve() { cin >> n >> s; int maxn = 0; for (int i = 1; i <= n; i++) { int l, r; cin >> l >> r; maxn = max(maxn, r); a.push_back({l, r}); } sort(a.begin(), a.end()); int l = 0, r = maxn, mid, ans = -1; while (l <= r) { mid = l + r >> 1; if (check(mid)) ans = mid, l = mid + 1; else r = mid - 1; } cout << ans << endl; a.clear(); return 0; } void Pre() {} int main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); Pre(); int cas; cin >> cas; while (cas--) Solve(); return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const long long MAXN = 2e5 + 5; pair<long long, long long> a[MAXN]; long long s; long long n; bool check(long long x) { long long sum = 0, cnt = 0; vector<long long> nums; for (long long i = 0; i < n; i++) { if (a[i].first >= x) { sum += a[i].first; cnt++; } else { if (a[i].second < x) { sum += a[i].first; } else { nums.push_back(a[i].first); } } } long long left = max((long long)0, (n + 1) / 2 - cnt); if (left > nums.size()) return 0; for (long long i = 0; i < nums.size() - left; i++) { sum += nums[i]; } for (long long i = nums.size() - left; i < nums.size(); i++) { sum += x; } return (sum <= s); } int main() { long long q; cin >> q; while (q--) { cin >> n >> s; for (long long i = 0; i < n; i++) { cin >> a[i].first >> a[i].second; } sort(a, a + n); long long l = 1, r = 1e18; while (l + 1 < r) { long long m = (l + r) >> 1; if (check(m)) { l = m; } else { r = m; } } cout << l << "\n"; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using pp = std::pair<int, int>; int main() { std::ios::sync_with_stdio(false); int t = 0; std::cin >> t; for (int k = 0; k < t; ++k) { int n = 0; long long s = 0, sum = 0; std::cin >> n >> s; pp p[n]; for (int i = 0; i < n; ++i) { std::cin >> p[i].first >> p[i].second; sum += p[i].first; } if (n == 1) { std::cout << std::min(s, (long long)p[0].second) << "\n"; continue; } std::sort(p, p + n, [](pp const& a, pp const& b) { return a.second < b.second; }); int m = n / 2; long long border = s - sum; int a = 0, b = p[m].second; for (; a < b;) { int c = (a + b + 1) / 2; int x = std::lower_bound(p, p + n, (pp){c, c}, [](pp const& a, pp const& b) { return a.second < b.second; }) - p; if (x > m) { b = c - 1; continue; } pp rem[n]; for (int i = x; i < n; ++i) rem[i] = p[i]; std::sort(rem + x, rem + n, [](pp const& a, pp const& b) { return a.first < b.first; }); long long ds = 0; for (int i = m; i < n && rem[i].first < c; ++i) { ds += c - rem[i].first; } if (ds <= border) { a = c; } else { b = c - 1; } } std::cout << a << "\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 long double PI = 2 * acos(0.0); void yes() { cout << "YES\n"; } void no() { cout << "NO\n"; cout << -1 << "\n"; exit(0); } long long m(long long a) { return (a + 1000000007) % 1000000007; } long long cel(long long x1, long long y1) { ; if ((x1 % y1) == 0) return x1 / y1; return x1 / y1 + 1; } long long power(long long a, long long b) { if (b == 0) return 1; long long d = power(a, b / 2); d = m(d * d); if (b & 1) d = m(d * a); return d; } bool check(long long mid, long long s, vector<long long> &l, vector<long long> &r) { long long n = l.size(); vector<pair<long long, long long>> vec; for (long long i = 0; i < n; i++) { s -= l[i]; if (l[i] < mid) { vec.push_back({l[i], r[i]}); } } if (vec.size() <= (n / 2)) return true; sort(vec.begin(), vec.end()); reverse(vec.begin(), vec.end()); long long l1 = vec.size() - (n / 2); long long c = 0; for (long long i = 0; i < vec.size(); i++) { if (c == l1) break; if (vec[i].second >= mid) { s -= (mid - vec[i].first); c++; } } if (s >= 0 && c == l1) return true; return false; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t; cin >> t; while (t--) { long long n, s; cin >> n >> s; vector<long long> l(n), r(n); for (long long i = 0; i < n; i++) { cin >> l[i] >> r[i]; } long long l1 = 0, f = s; long long ans = 0; while (l1 <= f) { long long mid = (l1 + f) / 2; if (check(mid, s, l, r)) { ans = mid; l1 = mid + 1; } else f = 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; const int maxn = 2e5 + 10; long long t, n, m; struct p { long long l, r; bool operator<(const p& tmp) const { return l < tmp.l; } } a[maxn]; bool col(p a, p b) { return a.l < b.l; } bool cor(p a, p b) { return a.r > b.r; } bool isok(long long mid) { priority_queue<p> q; long long temp = 0, k = n / 2 + 1; for (int i = n; i >= 1; i--) { if (a[i].r >= mid && a[i].l <= mid) q.push(a[i]); else if (a[i].l > mid) temp += a[i].l, k--; else temp += a[i].l; } if (k < 0) return false; while (!q.empty()) { p u = q.top(); q.pop(); if (k) k--, temp += mid; else temp += u.l; } if (temp > m || k != 0) return false; else return true; } int main() { cin >> t; while (t--) { long long l = 1e9, r = 0, ans = -1; cin >> n >> m; for (int i = 1; i <= n; i++) cin >> a[i].l >> a[i].r; sort(a + 1, a + 1 + n, col); l = a[n / 2 + 1].l; sort(a + 1, a + 1 + n, cor); r = a[n / 2 + 1].r; while (r >= l) { long long mid = l + r >> 1; if (isok(mid)) l = mid + 1, ans = mid; else r = mid - 1; } cout << ans << endl; } }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.io.BufferedInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.Scanner; public class DTask { private static final String QUICK_ANSWER = "NO"; private final Scanner in; private final StringBuilder out; private final int n; private final long s; int[] l; int[] r; private int min; private int max; private final Integer[] lOrder; private final Integer[] rOrder; private final int[] color; public DTask(Scanner in, StringBuilder out) { this.in = in; this.out = out; n = nextInt(); s = nextLong(); l = new int[n]; r = new int[n]; lOrder = new Integer[n]; rOrder = new Integer[n]; min = Integer.MAX_VALUE; max = -1; for (int i = 0; i < n; ++i) { lOrder[i] = i; rOrder[i] = i; l[i] = nextInt(); r[i] = nextInt(); min = Math.min(min, l[i]); max = Math.max(max, r[i]); } Arrays.sort(lOrder, Comparator.comparingInt(i -> l[i])); Arrays.sort(rOrder, Comparator.comparingInt(i -> r[i])); color = new int[n]; } public void solve() throws QuickAnswer { int l = min - 1; int r = max + 1; while (r - l > 1) { int mid = (l + r) / 2; if (test(mid)) l = mid; else r = mid; } print(l); } private boolean test(final long mid) { long min = 0; long max = 0; int less = 0; int more = 0; for (int i = 0; i < n; i++) { if(l[i] > mid){ more++; color[i] = 1; min += l[i]; max += r[i]; } else if(r[i] < mid){ less++; color[i] = 1; min += l[i]; max += r[i]; } else color[i] = 0; } if(more * 2 > n) return true; if(less * 2 > n ) return false; if(min + (n - less - more) * mid < s){ return true; } else if(max + (n - less - more) * mid > s){ long delta = max + (n - less - more) * mid - s; for (int i = 0; i < n; i++) { if(color[i] == 0) continue; if(l[i] > mid || r[i] < mid) delta -= r[i] - l[i]; } int cnt = n/2 - less; for (int i = 0; i < n / 2; i++) { int index = lOrder[i]; if(color[index] == 1) continue; if(cnt-- == 0) break; delta -= mid - l[index]; } return delta <= 0; } else return true; } // Common functions void quickAnswer(String answer) throws QuickAnswer { throw new QuickAnswer(answer); } void quickAnswer() throws QuickAnswer { quickAnswer(QUICK_ANSWER); } static class QuickAnswer extends Exception { private String answer; public QuickAnswer(String answer) { this.answer = answer; } } void print(Object... args) { String prefix = ""; for (Object arg : args) { out.append(prefix); out.append(arg); prefix = " "; } } void println(Object... args) { print(args); out.append("\n"); } void printsp(Object... args) { print(args); out.append(" "); } int nextInt() { return in.nextInt(); } long nextLong() { return in.nextLong(); } String nextString() { String res = in.nextLine(); return res.trim().isEmpty() ? in.nextLine() : res; } int[] nextInts(int count) { int[] res = new int[count]; for (int i = 0; i < count; ++i) { res[i] = in.nextInt(); } return res; } long[] nextLongs(int count) { long[] res = new long[count]; for (int i = 0; i < count; ++i) { res[i] = in.nextInt(); } return res; } public static void main(String[] args) { doMain(System.in, System.out); } static void doMain(InputStream inStream, PrintStream outStream) { Scanner in = new Scanner(new BufferedInputStream(inStream)).useLocale(Locale.ENGLISH); StringBuilder totalOut = new StringBuilder(); int count = 1; count = in.nextInt(); while (count-- > 0) { try { StringBuilder out = new StringBuilder(); new DTask(in, out).solve(); totalOut.append(out.toString()); } catch (QuickAnswer e) { totalOut.append(e.answer); } if (count > 0) { totalOut.append("\n"); } } outStream.print(totalOut.toString()); } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const long long inf = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const int maxn = 2e6 + 4; const int N = 5e3 + 5; const double eps = 1e-6; const double pi = acos(-1); long long qpow(long long x, long long y) { long long ans = 1; x %= mod; while (y) { if (y & 1) ans = ans * x % mod; x = x * x % mod; y >>= 1; } return ans; } struct node { int l, r; } a[maxn]; int _, n; long long s; bool cmp(node a, node b) { return a.l > b.l; } bool ok(long long m) { long long cnt = 0, res = 0; for (int i = 1; i <= n; i++) { if (a[i].l <= m && m <= a[i].r) { if (cnt < n / 2 + 1) res += m, cnt++; else res += a[i].l; } else { res += a[i].l; if (a[i].l >= m) cnt++; } } if (cnt < n / 2 + 1) return 0; return res <= s; } int main() { for (scanf("%d", &_); _; _--) { 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, cmp); long long l = 0, r = 1e9; long long ans = l; while (l <= r) { long long mid = l + r >> 1; if (ok(mid)) l = mid + 1, ans = mid; else r = mid - 1; } printf("%lld\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
from sys import stdin from operator import itemgetter, attrgetter def check(salary, mid, s): cnt = 0 for i in range(len(salary)): if salary[i][0] > mid: s -= salary[i][0] cnt += 1 elif salary[i][0] <= mid and salary[i][1] >= mid: if cnt < (len(salary) + 1) // 2: s -= mid cnt += 1 else: s -= salary[i][0] elif salary[i][1] < mid: s -= salary[i][0] if cnt >= (len(salary) + 1) // 2 and s >= 0: return True else: return False t = int(stdin.buffer.readline()) for _ in range(t): salary = list() n, s = map(int, stdin.buffer.readline().split()) ansL, ansR = 0x3f3f3f3f3f3f3f3f, -1 for i in range(n): l, r = map(int, stdin.buffer.readline().split()) ansL = min(ansL, l) ansR = max(ansR, r) salary.append((l, r)) salary = sorted(salary, key=itemgetter(0), reverse=True) l = ansL r = ansR ans = None while l <= r: mid = (l + r) // 2 if check(salary, mid, s): ans = mid l = mid + 1 else: r = mid - 1 print(ans)
PYTHON3
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; const long long int infinity = 9e18; pair<bool, long long int> isPossible( vector<pair<long long int, long long int> > &vp, long long int k, long long int s) { long long int n = vp.size(); vector<long long int> v, v1, v2; long long int a = 0, b = 0, c = 0; long long int sum = 0; for (auto i : vp) { if (i.first <= k && k <= i.second) { v.push_back(i.first); } else if (i.second < k) { a++; sum += i.first; } else if (i.first > k) { b++; sum += i.first; } } long long int x = (n + 1) / 2; if (a >= x) { return {1, -1}; } if (b >= x) { return {1, 1}; } long long int y = ((x - 1) - a); sort(v.begin(), v.end()); for (int i = 0; i < y; i++) { sum += v[i]; } sum += k * (v.size() - y); return {sum <= s, 0}; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; for (int idx = 0; idx < t; idx++) { long long int n, s; cin >> n >> s; vector<pair<long long int, long long int> > vp(n); for (int i = 0; i < n; i++) { cin >> vp[i].first >> vp[i].second; } long long int st = 1, end = s; long long int ans = 0; while (st <= end) { long long int mid = (st + end) / 2; pair<bool, long long int> p = isPossible(vp, mid, s); if (p.first) { if (p.second == -1) { end = mid - 1; } else if (p.second == 0) { ans = mid; st = mid + 1; } else if (p.second == 1) { st = mid + 1; } } else { end = mid - 1; } } cout << ans << "\n"; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); long s=input.nextLong(); ArrayList<Pair> list=new ArrayList<>(); for(int i=0;i<n;i++) { int l=input.nextInt(); int r=input.nextInt(); list.add(new Pair(l,r)); } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.l==o2.l) { return o1.r-o2.r; } else { return o1.l-o2.l; } } }); out.println(binarySearch(list,n,s)); } out.close(); } public static int binarySearch(ArrayList<Pair> list,int n,long s) { int i=list.get(n/2).l,j=1000000001; while(i<j) { int mid=(i+j)/2; if(fun(list,mid,n,s)) { i=mid+1; } else { j=mid; } } return i-1; } public static boolean fun(ArrayList<Pair> list,int v,int n,long s) { HashSet<Integer> ind=new HashSet<>(); long sum=0; int n1=n/2+1; for(int i=list.size()-1;i>=0;i--) { int l=list.get(i).l; int r=list.get(i).r; if(n1<=0) { break; } if(r>=v) { ind.add(i); sum+=Math.max(v,l); n1--; } } int flag=0; if(n1>0) { flag=1; } int n2=n/2; for(int i=0;i<list.size();i++) { if(!ind.contains(i)) { if(list.get(i).l<=v) { sum+=list.get(i).l; n2--; } } } if(n2>0) { flag=1; } if(sum>s) { flag=1; } if(flag==1) return false; else return true; } static class Pair { int l,r; Pair(int l,int r) { this.l=l; this.r=r; } } 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 java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; static int mod = 1_000_000_007; static int[] di = {1, 0, 0, -1}; static int[] dj = {0, -1, 1, 0}; static int M = 100005; public static void main(String[] args) throws IOException { int t = in.nextInt(); while(t --> 0) { int n = in.nextInt(); long don = in.nextLong(); Pair[] p = new Pair[n]; for(int i = 0; i < n; ++i) { int l = in.nextInt(); int r = in.nextInt(); p[i] = new Pair(l, r); } Arrays.parallelSort(p); int lo = 1, hi = (int)1e9; int ans = -1; while(lo <= hi) { int mid = (lo + hi) / 2; long need = minDon(p, n, mid); if(don >= need) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } 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
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class DDD { static pair[] dat; static int H=0; static long s=0; public static boolean possible(int median) { long sum=0; for(pair x:dat) { sum+=x.l; } int count=0; for(int i=dat.length-1;i>=0 && count<H;i--) { if(dat[i].r>=median) { sum+=Math.max((median-dat[i].l),0); count++; } } return (count==H && sum<=s); } public static void main(String args[]) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); for(int q=0;q<t;q++) { int n=scan.nextInt(); H=(n+1)/2; s=scan.nextLong(); dat=new pair[n]; for(int i=0;i<n;i++) { dat[i]=new pair(scan.nextInt(),scan.nextInt()); } Arrays.parallelSort(dat,new compare()); int low=0; int high=1000000005; while(low<high) { int mid=(low+high+1)/2; if(possible(mid)) { low=mid; }else { high=mid-1; } } System.out.println(low); } } } class pair{ int l; int r; pair(int x,int y){ l=x; r=y; } } class compare implements 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 { return 0; } } }
JAVA
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.lang.*; import java.io.*; import java.util.*; public class Solution { static int n; static long s; static long arr[][]; static Integer ind[]; public static boolean calc(long x) { long avai=s; int c=0,i; for(i=n-1;i>=0;i--) { if(arr[ind[i]][0]>=x) c++; else { if(arr[ind[i]][1]>=x) { avai-=x-arr[ind[i]][0]; c++; } } if(avai<0) { c--; break; } } if(c>n/2) return true; return false; } public static long binary() { long l=1,r=1000000002,mid; while(l<=r) { if(l==r) return l; if(l+1==r) { if(calc(r)) return r; return l; } mid=(l+r)/2; if(calc(mid)) l=mid; else r=mid-1; } return -1; } public static void main(String[] args) throws IOException { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int i,j; int t=in.nextInt(); while(t-->0) { n=in.nextInt(); s=in.nextLong(); arr=new long[n][2]; ind=new Integer[n]; long sum=0; for(i=0;i<n;i++) { arr[i][0]=in.nextLong(); arr[i][1]=in.nextLong(); sum+=arr[i][0]; } s-=sum; for(i=0;i<n;i++) ind[i]=i; Arrays.sort(ind,(a,b)->Long.compare(arr[a][0],arr[b][0])); sb.append(binary()).append("\n"); } System.out.print(sb); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
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; bool canDoAtLeast(long long m, long long s, vector<pair<long long, long long> > &E) { long long good = 0; vector<long long> P; for (auto [l, r] : E) { s -= l; if (l >= m) good++; else if (m <= r) { P.push_back(m - l); } } sort(P.begin(), P.end()); reverse(P.begin(), P.end()); while (good <= (int)E.size() / 2) { if (P.empty()) return false; good++; s -= P.back(); P.pop_back(); } return s >= 0; } void solve() { long long n, s; cin >> n >> s; vector<pair<long long, long long> > E(n); for (int i = 0; i < n; i++) { cin >> E[i].first >> E[i].second; } long long st = 1; long long fn = s; while (st <= fn) { long long mid = st + (fn - st) / 2; if (canDoAtLeast(mid, s, E)) { st = mid + 1; } else { fn = mid - 1; } } cout << fn << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; for (int i = 0; i < t; i++) solve(); }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using vi = vector<int>; using ll = long long; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; ll s; cin >> n >> s; vi l(n), r(n); for (int i = int(0); i < int(n); i++) cin >> l[i] >> r[i]; for (int i = int(0); i < int(n); i++) s -= l[i]; vi ordered_r = r; sort(ordered_r.begin(), ordered_r.end()); int max_median = ordered_r[n / 2]; vi inds_by_l(n); iota(inds_by_l.begin(), inds_by_l.end(), 0); sort(inds_by_l.begin(), inds_by_l.end(), [&](int i, int j) { return l[i] > l[j]; }); auto can = [&](int median) { ll left_s = s; int cant = 0; for (int i : inds_by_l) if (l[i] >= median) cant++; else if (r[i] >= median) { int dif = median - l[i]; if (left_s >= dif) left_s -= dif, cant++; else break; } return cant > n / 2; }; int lo = 0, hi = max_median; if (can(hi)) { cout << hi << '\n'; continue; } while (hi - lo > 1) { int mid = (lo + hi) / 2; if (can(mid)) lo = mid; else hi = mid; } cout << lo << '\n'; } return 0; }
CPP
1251_D. Salary Changing
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: * the median of the sequence [5, 1, 10, 17, 6] is 6, * the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n ≀ s. Note that you don't have to spend all your s dollars on salaries. You have to answer t test cases. Input The first line contains one integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each query contains two integers n and s (1 ≀ n < 2 β‹… 10^5, 1 ≀ s ≀ 2 β‹… 10^{14}) β€” the number of employees and the amount of money you have. The value n is not divisible by 2. The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^9). It is guaranteed that the sum of all n over all queries does not exceed 2 β‹… 10^5. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. βˆ‘_{i=1}^{n} l_i ≀ s. Output For each test case print one integer β€” the maximum median salary that you can obtain. Example Input 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 Note In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11. In the second test case, you have to pay 1337 dollars to the only employee. In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
2
10
import java.io.*; import java.util.*; public class Main { private static void execute(ContestReader reader, PrintWriter out) { int t = reader.nextInt(); for (int i = 0; i < t; i++) { int n = reader.nextInt(); long s = reader.nextLong(); int[] ls = new int[n]; int[] rs = new int[n]; for (int j = 0; j < n; j++) { ls[j] = reader.nextInt(); rs[j] = reader.nextInt(); } out.println(new Solver(n, s, ls, rs).solve()); } } public static void main(String[] args) { ContestReader reader = new ContestReader(System.in); PrintWriter out = new PrintWriter(System.out); execute(reader, out); out.flush(); } } class Solver { final int n; final long s; final int[] ls, rs; Solver(int n, long s, int[] ls, int[] rs) { this.n = n; this.s = s; this.ls = ls; this.rs = rs; } private boolean accept(int mid) { long restS = s; int countExceed = 0; List<Integer> exceedables = new ArrayList<>(); for (int i = 0; i < n; i++) { restS -= ls[i]; if (ls[i] >= mid) { countExceed++; } else if (rs[i] >= mid) { exceedables.add(mid - ls[i]); } } if (countExceed + exceedables.size() < (n + 1) / 2) { return false; } Collections.sort(exceedables); for (int i = 0; i < (n + 1) / 2 - countExceed; i++) { restS -= exceedables.get(i); if (restS < 0) { return false; } } return true; } public int solve() { int min = 0; int max = 1_000_000_010; while (max - min >= 2) { int mid = (max + min) / 2; if (accept(mid)) { min = mid; } else { max = mid; } } return min; } } class ContestReader { private BufferedReader reader; private StringTokenizer tokenizer; ContestReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new java.util.StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String[] nextArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } public double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } public int[][] nextIntMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextInt(); } } return matrix; } public long[][] nextLongMatrix(int n, int m) { long[][] matrix = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextLong(); } } return matrix; } public double[][] nextDoubleMatrix(int n, int m) { double[][] matrix = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextDouble(); } } return matrix; } } class ModCalculator { private final long mod; private final ModCombinationCache modCombinationCache; ModCalculator(long mod) { this.mod = mod; this.modCombinationCache = new ModCombinationCache(); } public long add(long a, long b) { return (a + b) % mod; } public long sub(long a, long b) { return (a - b + mod) % mod; } public long mul(long a, long b) { return (a * b) % mod; } public long pow(long a, long b) { if (b == 0) { return 1; } long v = pow(mul(a, a), b / 2); if (b % 2 == 1) { return mul(v, a); } else { return v; } } public long inverse(long a) { return pow(a, mod - 2); } public long div(long a, long b) { return mul(a, inverse(b)); } public long getF(int n) { return modCombinationCache.getF(n); } public long getP(int n, int r) { return modCombinationCache.getP(n, r); } public long getC(int n, int k) { return modCombinationCache.getC(n, k); } class ModCombinationCache { private final List<Long> factorialCache; private final List<Long> factorialInverseCache; public ModCombinationCache() { factorialCache = new ArrayList<>(); factorialCache.add(1L); factorialInverseCache = new ArrayList<>(); factorialInverseCache.add(1L); } private void resize(int n) { for (int i = factorialCache.size() - 1; i < n; i++) { long v = mul(factorialCache.get(i), i + 1); factorialCache.add(v); factorialInverseCache.add(inverse(v)); } } long getF(int n) { resize(n); return factorialCache.get(n); } long getP(int n, int r) { resize(n); return mul(factorialCache.get(n), factorialInverseCache.get(n - r)); } long getC(int n, int k) { resize(n); return mul(factorialCache.get(n), mul(factorialInverseCache.get(k), factorialInverseCache.get(n-k))); } } } class Algorithm { private static void swap(Object[] list, int a, int b) { Object tmp = list[a]; list[a] = list[b]; list[b] = tmp; } public static <T extends Comparable<? super T>> boolean nextPermutation(T[] ts) { int rightMostAscendingOrderIndex = ts.length - 2; while (rightMostAscendingOrderIndex >= 0 && ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostAscendingOrderIndex + 1]) >= 0) { rightMostAscendingOrderIndex--; } if (rightMostAscendingOrderIndex < 0) { return false; } int rightMostGreatorIndex = ts.length - 1; while (ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostGreatorIndex]) >= 0) { rightMostGreatorIndex--; } swap(ts, rightMostAscendingOrderIndex, rightMostGreatorIndex); for (int i = 0; i < (ts.length - rightMostAscendingOrderIndex - 1) / 2; i++) { swap(ts, rightMostAscendingOrderIndex + 1 + i, ts.length - 1 - i); } return true; } public static void shuffle(int[] array) { Random random = new Random(); int n = array.length; for (int i = 0; i < n; i++) { int randomIndex = i + random.nextInt(n - i); int temp = array[i]; array[i] = array[randomIndex]; array[randomIndex] = temp; } } public static void shuffle(long[] array) { Random random = new Random(); int n = array.length; for (int i = 0; i < n; i++) { int randomIndex = i + random.nextInt(n - i); long temp = array[i]; array[i] = array[randomIndex]; array[randomIndex] = temp; } } public static void sort(int[] array) { shuffle(array); Arrays.sort(array); } public static void sort(long[] array) { shuffle(array); Arrays.sort(array); } } class UnionFind { int[] parents; int[] ranks; UnionFind(int n) { parents = new int[n]; ranks = new int[n]; for (int i = 0; i < n; i++) { parents[i] = i; } } public int getRoot(int index) { if (parents[index] == index) { return index; } else { parents[index] = getRoot(parents[index]); return parents[index]; } } public boolean sameGroup(int a, int b) { return getRoot(a) == getRoot(b); } public void merge(int a, int b) { int rootA = getRoot(a); int rootB = getRoot(b); if (rootA == rootB) { return; } if (ranks[rootA] < ranks[rootB]) { parents[rootA] = rootB; } else if (ranks[rootB] < ranks[rootA]) { parents[rootB] = rootA; } else { parents[rootA] = rootB; ranks[rootB]++; } } }
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; #pragma GCC optimization("Ofast") #pragma GCC optimization("unroll-loops") #pragma GCC target("avx2,avx,fma") int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; int i, j, t; cin >> t; for (i = 0; i < t; i++) { int n; long long int s; cin >> n >> s; vector<pair<long long int, long long int> > v; long long int l, r; for (j = 0; j < n; j++) { cin >> l >> r; v.push_back(make_pair(l, r)); } sort(v.rbegin(), v.rend()); l = 1; r = s; while (l <= r) { long long int mid = (l + r) / 2; long long int sum = 0; int k = 0; for (j = 0; j < n; j++) { if (v[j].second >= mid && k < n / 2 + 1) { sum += max(v[j].first, mid); k++; } else sum += v[j].first; } if (k < (n / 2 + 1) || sum > s) r = mid - 1; else l = mid + 1; } cout << r << "\n"; } return 0; }
CPP