Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct num {
long long l, r;
} a[200005];
bool cmp(num x, num y) {
if (x.l == y.l) return x.r > y.r;
return x.l > y.l;
}
long long n, s;
long long check(long long m) {
long long br = n / 2 + 1, sum = 0;
for (int i = 0; i < n; i++) {
if (a[i].l <= m && m <= a[i].r && br) {
br--;
sum += m;
} else {
sum += a[i].l;
if (a[i].l > m) br--;
}
}
if (br) return s + 1;
return sum;
}
int main() {
int q;
cin >> q;
while (q--) {
cin >> n >> s;
for (long long i = 0; i < n; i++) {
cin >> a[i].l >> a[i].r;
}
sort(a, a + n, cmp);
long long l = a[n / 2].l + 1, r = s;
while (l <= r) {
long long m = (l + r) >> 1;
if (check(m) <= s)
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 | #include <bits/stdc++.h>
using namespace std;
long long n, s, INI;
pair<long long, long long> a[200010];
bool op(long long meta) {
long long quant = 0, disponivel = s;
for (long long i = n; i >= 1; i--) {
long long vez = meta - a[i].first;
if (a[i].first >= meta) {
quant++;
continue;
}
if (a[i].second < meta) continue;
if (vez > disponivel) continue;
disponivel -= vez;
quant++;
}
long long precisa = n / 2;
precisa++;
if (quant >= precisa)
return true;
else
return false;
}
void solve() {
cin >> n >> INI;
for (long long i = 1; i <= n; i++) cin >> a[i].first >> a[i].second;
sort(a + 1, a + n + 1);
s = INI;
for (long long i = 1; i <= n; i++) s -= a[i].first;
long long ini = 1, fim = 200000000000000;
while (ini <= fim) {
long long meio = (ini + fim) / 2;
if (op(meio)) {
bool prox = op(meio + 1);
if (!prox) {
cout << meio << "\n";
return;
}
ini = meio + 1;
} else {
bool ant = op(meio - 1);
if (ant) {
cout << meio - 1 << "\n";
return;
}
fim = meio - 1;
}
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long t;
cin >> t;
for (long long i = 1; 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 | 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])
print(search(n,low,(10**9)+1,l,su))
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;
const int maxn = 200020;
inline long long read() {
char ch = getchar();
long long x = 0, f = 0;
while (ch < '0' || ch > '9') f |= ch == '-', ch = getchar();
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
return f ? -x : x;
}
struct seg {
int l, r;
bool operator<(const seg &s) const { return l < s.l; }
} s[maxn];
int t, n, tmp[maxn], tl;
long long sum;
bool check(int x) {
long long tot = 0;
int rem = (n + 1) / 2;
tl = 0;
for (int i = (1); i <= (n); i++) {
if (s[i].r < x) tot += s[i].l;
if (s[i].l >= x) tot += s[i].l, rem--;
if (s[i].r >= x && s[i].l < x) tmp[++tl] = s[i].l;
}
rem = max(rem, 0);
if (tl < rem) return false;
sort(tmp + 1, tmp + tl + 1);
for (int i = (1); i <= (tl - rem); i++) tot += tmp[i];
for (int i = (tl - rem + 1); i <= (tl); i++) tot += x;
return tot <= sum;
}
int main() {
t = read();
while (t--) {
n = read();
sum = read();
for (int i = (1); i <= (n); i++) s[i].l = read(), s[i].r = read();
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);
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input=sys.stdin.readline
t=int(input())
def ok(mid,l,n,s):
su=0
cnt=0
ll=[]
for i in range(n):
if(l[i][1]<mid):
su+=l[i][0]
elif(l[i][0]>=mid):
su+=l[i][0]
cnt+=1
else:
ll.append(l[i])
ll.sort()
ne=max(0,(n+1)//2-cnt)
if(ne>len(ll)):
return False
for i in range(len(ll)):
if(i<len(ll)-ne):
su+=ll[i][0]
else:
su+=mid
return su<=s
while t:
l=[]
n,s=map(int,input().split())
for i in range(n):
ll,r=map(int,input().split())
l.append((ll,r))
l.sort()
lf=0
r=10**9+100
while r-lf>1:
mid=lf+(r-lf)//2
if(ok(mid,l,n,s)):
lf=mid
else:
r=mid
#print(lf)
print(lf)
t-=1 | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
const int M = 1e9 + 7;
vector<pair<int, int> > seg;
bool check(long long n, long long s, long long median) {
long long less = 0, more = 0;
long long cur = 0;
vector<int> v;
for (int i = 0; i < n; i++) {
if (seg[i].second < median) {
cur += seg[i].first;
} else if (median <= seg[i].first) {
cur += seg[i].first;
more++;
} else {
v.push_back(seg[i].first);
}
}
sort(v.begin(), v.end(), greater<int>());
int rem = max(0LL, (n + 1) / 2 - more);
if ((int)v.size() < rem) return false;
for (auto val : v) {
if (rem > 0) {
cur += median;
rem--;
} else {
cur += val;
}
}
return cur <= s;
}
void solve() {
long long n, s;
cin >> n >> s;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
seg.push_back({x, y});
}
sort(seg.begin(), seg.end());
long long lo = seg[n / 2].first, hi = s + 1;
while (hi - lo > 1) {
long long mid = lo + hi >> 1;
if (check(n, s, mid))
lo = mid;
else
hi = mid;
}
cout << lo << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
seg.clear();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-6;
const int mod = 1e9 + 7;
const int maxn = 2e6 + 100;
const int maxm = 2e6 + 100;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
int t;
pair<long long, long long> a[maxn];
long long s;
int n;
int vis[maxn];
bool cmp2(pair<long long, long long> a, pair<long long, long long> b) {
return a.second < b.second;
}
vector<long long> mm, rr, lll;
int ck(long long x) {
int L = 0, R = 0, M = 0;
lll.clear();
rr.clear();
mm.clear();
for (int i = 1; i <= n; i++) {
if (a[i].first <= x && a[i].second >= x) {
mm.push_back(a[i].first);
M++;
continue;
}
if (a[i].first > x) {
R++;
rr.push_back(a[i].first);
}
if (a[i].second < x) {
L++;
lll.push_back(a[i].first);
}
}
if (L > n / 2) return false;
long long res = 0;
sort(mm.begin(), mm.end());
if (L < n / 2) {
int to = M;
for (int i = 0; i < to; i++) {
lll.push_back(mm[i]);
L++;
M--;
if (L == n / 2) break;
}
}
if (R < n / 2 + 1) {
if (R + M != n / 2 + 1) return false;
res += 1ll * M * x;
}
for (int i = 0; i < (int)lll.size(); i++) {
res += lll[i];
}
for (int i = 0; i < (int)rr.size(); i++) {
res += max(rr[i], x);
}
return res <= s;
}
int main() {
scanf("%d", &t);
while (t--) {
long long mx = 0;
scanf("%d %lld", &n, &s);
for (int i = 1; i <= n; i++) {
scanf("%lld %lld", &a[i].first, &a[i].second);
mx = max(mx, a[i].second);
}
long long ans = 0;
sort(a + 1, a + 1 + n);
long long l = a[n / 2 + 1].first;
sort(a + 1, a + 1 + n, cmp2);
long long r = a[n / 2 + 1].second;
while (l <= r) {
long long mid = l + r >> 1;
if (ck(mid)) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
printf("%lld\n", ans);
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n;
long long s;
pair<int, int> a[200010];
bool take[200010];
bool good(int x) {
int cnt = n / 2;
long long tot = 0;
for (int i = 1; i <= n; i++) {
if (a[i].second < x) {
tot += a[i].first;
--cnt;
take[i] = true;
} else
take[i] = false;
}
if (cnt < 0) return false;
for (int i = 1; i <= n; i++) {
if (cnt == 0) break;
if (take[i]) continue;
tot += a[i].first;
--cnt;
take[i] = true;
}
for (int i = 1; i <= n; i++) {
if (!take[i]) {
tot += max(x, a[i].first);
}
}
return tot <= s;
}
int search(int b, int e) {
if (b == e) return b;
int m = (b + e + 1) >> 1;
if (good(m))
return search(m, e);
else
return search(b, m - 1);
}
void solve() {
scanf("%d %lld", &n, &s);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &a[i].first, &a[i].second);
}
sort(a + 1, a + n + 1);
printf("%d\n", search(1, 1000000000));
}
int main(int argc, char const *argv[]) {
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input1 = sys.stdin.readline
def solve():
n, s = [int(i) for i in input1().split()]
empl = [[] for i in range(n)]
for i in range(n):
empl[i] = [int(j) for j in input1().split()]
empl.sort(reverse=True)
lg = 0
rg = 10 ** 9 + 1
while rg - lg > 1:
mg = (rg + lg) // 2
need = (n + 1) // 2
money = s
for [li, ri] in empl:
if ri >= mg and need > 0:
money -= max(mg, li)
need -= 1
else:
money -= li
if need == 0 and money >= 0:
check = True
else:
check = False
if check:
lg = mg
else:
rg = mg
print(lg)
t = int(input1())
while t > 0:
empl = []
solve()
t -= 1 | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct node {
long long l, r;
};
bool cmp(node a, node b) {
if (a.l != b.l) return a.l < b.l;
return a.r < b.r;
}
long long T, N, S;
node a[200005];
bool can(long long x) {
long long cnt = 0;
long long money = 0;
for (long long i = N; i >= 1; i--) {
if (a[i].r < x)
money += a[i].l;
else if (cnt * 2 > N)
money += a[i].l;
else {
long long pay = max(a[i].l, x);
money += pay;
cnt++;
}
}
if (money <= S && cnt * 2 > N) return 1;
return 0;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> T;
while (T--) {
cin >> N >> S;
for (long long i = 1; i <= N; i++) cin >> a[i].l >> a[i].r;
sort(a + 1, a + N + 1, cmp);
long long ini = 0;
long long fin = 1e9;
while (ini < fin) {
long long mid = (ini + fin + 1) / 2;
if (can(mid))
ini = mid;
else
fin = mid - 1;
}
cout << ini << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.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 = k + 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 | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const double PI = acos(-1);
long long mod = 1e9 + 7;
struct segment {
long long l, r;
bool operator<(const segment& s) const { return l < s.l; }
};
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
long long n, s;
cin >> n >> s;
vector<segment> vs(n);
for (long long i = 0; i < n; i++) cin >> vs[i].l >> vs[i].r;
long long low = 1, high = s + 1;
while (low < high) {
long long mid = (low + high + 1) / 2;
vector<segment> tmp;
long long cost = 0, left = 0, right = 0;
for (long long i = 0; i < n; i++) {
if (vs[i].r < mid) {
left++;
cost += vs[i].l;
} else if (vs[i].l > mid) {
right++;
cost += vs[i].l;
} else
tmp.push_back(vs[i]);
}
sort(tmp.begin(), tmp.end());
long long rem = n / 2 - left;
for (long long i = 0; i < tmp.size(); i++) {
if (rem > 0) {
rem--;
cost += tmp[i].l;
left++;
} else {
cost += mid;
right++;
}
}
if (cost > s || left >= right)
high = mid - 1;
else
low = mid;
}
cout << low << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long n, s, t, cnt, sum;
const int maxn = 2e5 + 7;
pair<long long, long long> a[maxn];
int main() {
cin >> t;
while (t--) {
cin >> n >> s;
for (int i = 1; i <= n; i++) {
cin >> a[i].first >> a[i].second;
}
sort(a + 1, a + n + 1);
long long l = 1;
long long r = 1000000000;
while (l <= r) {
long long mid = (l + r) / 2;
cnt = (n + 1) / 2;
sum = 0;
for (int i = n; i >= 1; i--) {
if (a[i].second >= mid && cnt) {
sum += max(a[i].first, mid);
cnt--;
} else
sum += a[i].first;
}
if (sum <= s && cnt == 0) {
l = mid + 1;
} else
r = mid - 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 | import sys
input = sys.stdin.readline
import heapq as hq
t = int(input())
for _ in range(t):
n,s = map(int,input().split())
sr = [list(map(int,input().split())) for i in range(n)]
summn = sum(list(zip(*sr))[0])
med = n//2+1
l = 0
r = s+1
while l+1<r:
flg = 0
x = (l+r)//2
cost = summn
q = []
hq.heapify(q)
for i in range(n):
if sr[i][1] >= x:
hq.heappush(q,-sr[i][0])
if len(q) < med:
pass
else:
for _ in range(med):
cost += max(0,x+hq.heappop(q))
if cost <= s:
flg = 1
if flg:
l = x
else:
r = x
print(l) | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
static long s;
static int n;
static int[][] emp;
static final int inf = (int)1e9+100;
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = fs.nextInt();
while(tt-->0) {
n = fs.nextInt();
s = fs.nextLong();
emp = new int[n][2];
for(int i=0;i<n;i++) {
emp[i][0] = fs.nextInt();
emp[i][1] = fs.nextInt();
}
Arrays.sort(emp, (x, y)-> x[0]-y[0]);
//binary search on the minimum possible median value
int l = 1;
int r = inf;
while(l<r) {
int mid = (int)((long)l+r+1)/2;
if(fun(mid)) {
l = mid;
}
else {
r = mid-1;
}
}
out.println(l);
}
out.close();
}
static boolean fun(int med) {
//total salary needed
long sum = 0;
//number of salaries greater than med
int cnt = 0;
ArrayList<Integer> l = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if(emp[i][1]<med) {
sum += emp[i][0];
}
else if(emp[i][0]>=med) {
sum += emp[i][0];
cnt++;
}
else {
l.add(emp[i][0]);
}
}
int need = Math.max(0, (n+1)/2-cnt);
if(need>l.size()) return false;
for(int i=0;i<l.size();i++) {
if(i<l.size()-need) {
sum += l.get(i);
}
else {
sum += med;
}
}
return sum<=s;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
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();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[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 os
def binary_search(f, low, high):
mid = (high + low) // 2
if low == high:
return low
if f(mid):
return binary_search(f, mid + 1, high)
else:
return binary_search(f, low, mid)
# for i in range(10):
# f = lambda x: x <= i
# assert binary_search(f, 0, 100) == i + 1
def f(lr, k, s):
d1s = 0
d1c = 0
d3s = 0
d3c = 0
n = len(lr)
d2cs = [0]
for l, r in lr:
if r < k:
d1s += l
d1c += 1
elif k < l:
d3s += l
d3c += 1
else:
d2cs.append(d2cs[-1] + l)
if n // 2 < d1c:
return False
spend = d1s + d2cs[n // 2 - d1c] + max((n + 1) // 2 - d3c, 0) * k + d3s
return spend <= s
def m(lr, s):
if len(lr) == 1:
return min(s, lr[0][1])
lr = sorted(lr)
k_low = lr[len(lr) // 2][0]
return binary_search(lambda k: f(lr, k, s), k_low, max(r for l, r in lr) + 1) - 1
def pp(input):
n_test = int(input())
for i in range(n_test):
n, s = map(int, input().split())
lr = [tuple(map(int, input().split())) for _ in range(n)]
print(m(lr, s))
if "paalto" in os.getcwd():
from string_source import string_source
s0 = string_source("""3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7""")
pp(s0)
s1 = string_source(
"""1
19 1175
44 87
68 100
93 98
76 79
10 58
74 99
87 97
23 75
62 73
100 100
71 76
73 87
76 82
44 84
54 90
2 82
67 99
85 97
66 88"""
)
pp(s1)
else:
pp(input)
| 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 const N = 200000, inf = 1e9;
pair<int, int> x[N];
int n;
vector<int> y;
bool ok(int m, long long s) {
y.clear();
for (int i = 0; i < (int)(n); ++i) {
s -= x[i].first;
if (m <= x[i].second) {
if (m >= x[i].first)
y.push_back(m - x[i].first);
else
y.push_back(0);
}
}
if (y.size() < n + 1 >> 1) return false;
sort(y.begin(), y.end());
for (int i = 0; i < (int)(n + 1 >> 1); ++i) s -= y[i];
return s >= 0;
}
void solve() {
long long s;
scanf("%d%lld", &n, &s);
for (int i = 0; i < (int)(n); ++i) scanf("%d%d", &x[i].first, &x[i].second);
int l = 1, r = inf;
while (r > l) {
int m = l + r + 1 >> 1;
if (ok(m, s))
l = m;
else
r = m - 1;
}
printf("%d\n", l);
}
int main() {
int t;
scanf("%d", &t);
while (t--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> f;
long long n, s;
bool can(long long mid) {
long long sum = 0, cnt = 0;
vector<long long> v;
for (long long i = 0; i < n; i++) {
if (f[i].second < mid)
sum += f[i].first;
else if (f[i].first >= mid) {
sum += f[i].first;
cnt++;
} else {
v.push_back(f[i].first);
}
}
long long rem = max(0LL, (n + 1) / 2 - cnt);
if (v.size() < rem) return false;
sort(v.rbegin(), v.rend());
for (long long i = 0; i < v.size(); ++i) {
if (rem > 0) {
sum += mid;
rem--;
} else {
sum += v[i];
}
}
return sum <= s;
}
signed main() {
long long t;
cin >> t;
while (t--) {
cin >> n >> s;
f.resize(n);
for (long long i = 0; i < n; i++) {
cin >> f[i].first >> f[i].second;
}
long long left = 0, right = 1e9 + 7;
while (right - left > 1) {
long long mid = right + left >> 1;
if (can(mid))
left = mid;
else
right = mid;
}
cout << left << '\n';
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct range {
int l, r, id;
} rng[200010];
int vis[200010];
int n;
long long s;
bool find(int m) {
for (int i = 1; i <= n; i++) vis[i] = 0;
int lcnt(0), rcnt(0);
long long sum(0);
for (int i = 1; i <= n; i++) {
if (rng[i].r < m) {
lcnt++;
sum += rng[i].l;
vis[i] = 1;
} else if (rng[i].l > m) {
rcnt++;
sum += rng[i].l;
vis[i] = 1;
}
if (sum > s || lcnt > n / 2 || rcnt > n / 2) return false;
}
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;
if (lcnt < n / 2) {
if (rng[i].l > m) {
return false;
}
sum += rng[i].l;
lcnt++;
vis[i] = 1;
} else if (rcnt <= n / 2) {
sum += m;
vis[i] = 1;
rcnt++;
}
if (sum > s) return false;
}
return true;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d %I64d", &n, &s);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &rng[i].l, &rng[i].r);
rng[i].id = i;
}
sort(rng + 1, rng + 1 + n,
[](const range& lhs, const range& rhs) { return lhs.r < rhs.r; });
int r = rng[n / 2 + 1].r + 1;
sort(rng + 1, rng + 1 + n,
[](const range& lhs, const range& rhs) { return lhs.l < rhs.l; });
int l = rng[n / 2 + 1].l;
while (r - l > 1) {
int m = (l + r) >> 1;
if (find(m)) {
l = m;
} else {
r = m;
}
}
printf("%d\n", l);
}
}
| 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 = 0
left_cnt, right_cnt = 0, 0
arr = []
for li, ri in lr:
if ri<x:
salary += li
left_cnt += 1
elif x<li:
salary += li
right_cnt += 1
else:
arr.append(li)
arr.sort()
salary += sum(arr[:(n-1)//2-left_cnt])+(1+(n-1)//2-right_cnt)*x
return salary<=s
def binary_search(l, r):
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)]
l = [li for li, _ in lr]
r = [ri for _, ri in lr]
l.sort()
r.sort()
print(binary_search(l[n//2], r[n//2])) | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
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 | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 1_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "BaZ", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n;
static Pair arr[];
static long s;
static void solve() throws IOException
{
//initIo(true);
initIo(false);
StringBuilder sb = new StringBuilder();
int t = ni();
while(t-->0) {
n = ni();
s = nl();
arr = new Pair[n];
for(int i=0;i<n;++i) {
arr[i] = new Pair(ni(), ni());
}
Arrays.sort(arr);
int low = 0, high = 1000000000,mid,ans = low;
while(low<=high) {
mid = (low+high)>>1;
if(check(mid)) {
ans = mid;
low = ++mid;
}
else {
high = --mid;
}
}
pl(ans);
}
pw.flush();
pw.close();
}
static boolean check(int x) {
int cnt = 0;
long taken = 0;
int i;
for(i=n-1;i>=0;--i) {
if(arr[i].x>=x) {
cnt++;
taken+=arr[i].x;
}
else {
break;
}
}
if(cnt>=(n+1)/2) {
return true;
}
for(;i>=0;--i) {
if(arr[i].y>=x) {
if(cnt<(n+1)/2) {
cnt++;
taken+=x;
}
else {
taken+=arr[i].x;
}
}
else {
taken+=arr[i].x;
}
}
return cnt>=(n+1)/2 && taken<=s;
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair other)
{
if(this.x!=other.x)
return this.x-other.x;
return this.y-other.y;
}
public String toString()
{
return "("+x+","+y+")";
}
}
static void initIo(boolean isFileIO) throws IOException {
scan = new MyScanner(isFileIO);
if(isFileIO) {
pw = new PrintWriter("/Users/amandeep/Desktop/output.txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class D {
static int N;
static long S;
static long[] l,r;
public static void main(String[] args) {
FS in = new FS();
PrintWriter out = new PrintWriter(System.out);
int T = in.nextInt();
for(int runs = 1; runs <= T; runs++) {
N = in.nextInt();
S = in.nextLong();
l = new long[N];
r = new long[N];
for(int i = 0; i < N; i++) {
l[i] = in.nextLong();
r[i] = in.nextLong();
}
//binary search value
long lo = 0;
long hi = S;
long best = 0;
while(lo <= hi) {
long mid = (lo+hi)/2;
if(works(mid)) {
best = Math.max(best, mid);
lo = mid+1;
}
else hi = mid-1;
}
out.println(best);
}
out.close();
}
static boolean works(long med) {
//give everyone the lowest.
//Then give to the people who can go lowest above S
long money = S;
person ar[] = new person[N];
for(int i = 0; i < N; i++) {
ar[i] = new person(l[i], l[i], r[i]);
money -= l[i];
}
PriorityQueue<Long> pq = new PriorityQueue<Long>();
int peopleAboveMed = 0;
for(person p : ar) {
if(p.curMoney >= med) peopleAboveMed++;
else {
if(p.r < med) continue;
long moneyToMed = med-p.l;
pq.add(moneyToMed);
}
}
int need = N/2 + 1 - peopleAboveMed;
while(!pq.isEmpty() && need > 0) {
long m = pq.poll();
if(m > money) return false;
money -= m;
need--;
}
if(need <= 0) return true;
return false;
}
static class person{
long curMoney;
long l,r;
public person(long cc, long ll, long rr) {
curMoney = cc;
l=ll;
r=rr;
}
}
static class FS{
BufferedReader br;
StringTokenizer st;
public FS() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine());}
catch(Exception e) { throw null;}
}
return st.nextToken();
}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
}
static void sort(int a[]) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int ii : a) list.add(ii);
Collections.sort(list);
for(int i = 0; i < a.length; i++) a[i] = list.get(i);
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int amount;
long long total;
pair<int, int> salary[1000005];
bool is_good(int median_sal) {
int need = (amount + 1) / 2;
long long total_need = 0;
for (int i = amount; i >= 1; i--)
if (salary[i].first >= median_sal) {
need--;
total_need += salary[i].first;
} else
break;
for (int i = amount; i >= 1; i--)
if (salary[i].first < median_sal) {
if (need > 0 && salary[i].second >= median_sal)
need--, total_need += median_sal;
else
total_need += salary[i].first;
}
return (total_need <= total && need <= 0);
}
void solve() {
scanf("%d %lld", &amount, &total);
for (int i = 1; i <= amount; i++)
scanf("%d %d", &salary[i].first, &salary[i].second);
sort(salary + 1, salary + amount + 1);
int head = (int)1e9 + 5, tail = 0;
while (head - tail > 1) {
int mid = (head + tail) >> 1;
if (is_good(mid))
tail = mid;
else
head = mid;
}
printf("%d\n", tail);
}
int main() {
int tester;
scanf("%d", &tester);
while (tester--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CodingLegacy {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Palindrome solver = new Palindrome();
int t = in.nextInt();
for(int i=0;i<t;i++) {
solver.solve(i+1, in, out);
}
out.close();
}
static class Palindrome {
static long mod = 1000000007;
static long max = (long) 1e18;
Pair[] a;
int n;
long s;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
s = in.nextLong();
a = new Pair[n];
for(int i = 0;i<n;i++){
Pair pair = new Pair(in.nextInt(),in.nextInt());
a[i] = pair;
}
Arrays.sort(a, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.first == o2.first){
return (o1.second) - (o2.second);
}
return o1.first - o2.first;
}
});
int l = 1,r=(int)1e9 + 100;
while(l+1<r){
int m = (l+r)/2;
// out.println(m);
if(foo(m)){
l = m;
} else {
r = m;
}
}
out.println(l);
// out.println();
}
private boolean foo(int m) {
long sum = 0;
int count = 0;
ArrayList<Integer> aa = new ArrayList<>();
for(int i = 0;i<n;i++){
if(a[i].second < m){
sum += a[i].first;
} else if (a[i].first >= m){
sum += a[i].first;
count++;
} else {
aa.add(a[i].first);
}
}
int needs = Math.max(0,((n+1)/2) - count);
if(aa.size() < needs){
return false;
}
for (int i = 0; i < aa.size(); i++) {
if(i < aa.size() - needs){
sum += aa.get(i);
} else {
sum += m;
}
}
return sum<=s;
}
static class Pair {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
}
static class Maths{
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long factorial(int n){
long fact = 1;
for(int i=1;i<=n;i++){
fact *= i;
}
return fact;
}
}
static class Characters{
public static boolean isVovel(char a){
if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u'){
return true;
}
return false;
}
}
static class Binary {
public static long numberOfBits(long n){
long count=0;
while(n>0){
count++;
n >>=1;
}
return count;
}
public static long numberOfSetBits(long n){
long count = 0;
int p = 1;
while (n>0){
if((n&p) == 1){
count++;
}
n >>= 1;
}
return count;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public Long nextLong(){
return Long.parseLong(next());
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long l[500005], r[500005], n, s;
bool check(long long x) {
long long k = n + 1 >> 1;
vector<long long> vec;
for (long long i = 1, v; i <= n; i++) {
v = max(l[i], x);
if (r[i] < v) continue;
vec.push_back(v - l[i]);
}
if (vec.size() < k) return 0;
long long sum = 0;
sort(vec.begin(), vec.end());
for (long long i = 0; i < k; i++) sum += vec[i];
return sum <= s;
}
signed main() {
long long t;
scanf("%lld", &t);
while (t--) {
scanf("%lld%lld", &n, &s);
for (long long i = 1; i <= n; i++) {
scanf("%lld%lld", &l[i], &r[i]);
s -= l[i];
}
long long ll = 0, rr = 1e9, mid, ans = 0;
while (ll <= rr) {
long long mid = ll + rr >> 1;
if (check(mid))
ans = mid, ll = mid + 1;
else
rr = 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 | #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;
while (l <= r) {
int mid = (l + r) / 2;
if (possible(mid))
l = mid + 1;
else
r = mid - 1;
}
cout << r << '\n';
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
public class CF1251D extends PrintWriter {
CF1251D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1251D o = new CF1251D(); o.main(); o.flush();
}
static class V {
int l, r;
V(int l, int r) {
this.l = l; this.r = r;
}
}
boolean check(V[] vv, int n, int m, long s) {
int h = n / 2;
for (int i = 0; i < n; i++) {
V v = vv[i];
if (v.r < m) {
if (--h < 0)
return false;
if ((s -= v.l) < 0)
return false;
} else if (v.l > m) {
if ((s -= v.l) < 0)
return false;
}
}
for (int i = 0; i < n; i++) {
V v = vv[i];
if (v.l <= m && m <= v.r) {
if (h == 0)
s -= m;
else {
h--;
s -= v.l;
}
if (s < 0)
return false;
}
}
return true;
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
long s = sc.nextLong();
V[] vv = new V[n];
for (int i = 0; i < n; i++) {
int l = sc.nextInt();
int r = sc.nextInt();
vv[i] = new V(l, r);
}
Arrays.sort(vv, (u, v) -> u.l - v.l);
int lower = 0, upper = 1000000001;
while (upper - lower > 1) {
int m = (lower + upper) / 2;
if (check(vv, n, m, s))
lower = m;
else
upper = m;
}
println(lower);
}
}
}
| 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 t, n, i;
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> t;
while (t--) {
long long s;
cin >> n >> s;
vector<int> l(n), r(n);
for (i = 0; i < n; i++) {
cin >> l[i] >> r[i];
}
vector<int> ord(n);
iota(ord.begin(), ord.end(), 0);
sort(ord.begin(), ord.end(),
[&](const int &x, const int &y) { return l[x] > l[y]; });
auto check = [&](long long lim) -> bool {
long long sum = 0;
int cnt = 0;
for (auto it : ord) {
sum += l[it];
long long cur = max(0LL, lim - l[it]);
if (r[it] >= lim && cnt < (n + 1) / 2) {
sum += cur;
cnt++;
}
if (sum > s) return 0;
}
return ((cnt == (n + 1) / 2) && sum <= s);
};
long long res = 0;
for (long long step = 1LL << 50; step; step >>= 1) {
if (check(res + step)) {
res += step;
}
}
cout << res << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long mx = 200005;
bool comparator(pair<long long, long long> A, pair<long long, long long> B) {
return A.first < B.first;
}
int main() {
ios::sync_with_stdio(0);
long long q;
cin >> q;
while (q--) {
long long n, s;
long long l;
long long r;
long long ans = 0;
vector<pair<long long, long long>> intv, Min, Max;
cin >> n >> s;
for (int i = 1; i <= n; ++i) {
int l, r;
cin >> l >> r;
intv.push_back(make_pair(l, r));
Min.push_back(make_pair(l, i - 1));
Max.push_back(make_pair(r, i - 1));
}
sort(Min.begin(), Min.end(), comparator);
sort(Max.begin(), Max.end(), comparator);
l = Min[n / 2].first;
r = Max[n / 2].first;
while (l <= r) {
long long m = (l + r) / 2;
long long cost = m;
long long cntLeft = 0;
long long cntRight = 0;
vector<pair<int, int>> both;
for (int i = 0; i < n; ++i) {
if (intv[i].second < m)
cost += intv[i].first, ++cntLeft;
else if (intv[i].first > m)
cost += intv[i].first, ++cntRight;
else if (intv[i].first <= m && intv[i].second >= m)
both.push_back(intv[i]);
}
sort(both.begin(), both.end(), comparator);
for (int i = 0; i < both.size() && cntLeft < n / 2; ++i)
cost += both[i].first, ++cntLeft;
for (int i = both.size() - 1; i >= 0 && cntRight < n / 2; --i)
cost += m, ++cntRight;
if (cost <= s) {
ans = max(ans, m);
l = m + 1;
} else {
r = m - 1;
}
}
cout << ans << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | if __name__ == '__main__':
import sys
input = sys.stdin.readline
test = int(input())
for i in range(test):
numbers = list(map(int, input().split()))
people = numbers[0]
# the nr of people is odd
salary = numbers[1]
interv= []
nr = 0
for j in range(people):
v = list(map(int, input().split()))
left = v[0]
right = v[1]
nr = nr + left
interv.append([left, right])
left = 0
# 10^9 the highest number on the right
right = 1000000001
while right > left + 1:
m = (left + right) // 2
fin = []
for j in range(people):
if m <= interv[j][1]:
if -interv[j][0] < -m:
fin.append(-m)
else:
fin.append(-interv[j][0])
x = len(fin)
if x < people//2 + 1:
right = m
continue
fin.sort()
suma = nr + (people//2 + 1) * m + sum(fin[:people//2 + 1])
if suma > salary:
right = m
else:
left = m
print(left)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const long long N = 2e5 + 10;
long long T, n, s, mx, ts;
struct node {
long long l, r;
} t[N];
long long cmp(node a, node b) { return a.l < b.l; }
inline long long check(long long mid) {
long long cnt = 0;
s = ts;
for (long long i = n; i >= 1; i--) {
if (t[i].l >= mid) {
cnt++;
continue;
}
if (t[i].r >= mid) {
if (s >= (mid - t[i].l))
cnt++, s -= (mid - t[i].l);
else
return cnt > (n / 2);
}
}
return cnt > (n / 2);
}
long long bsearch() {
long long l = 1, r = mx;
while (l < r) {
long long mid = l + r + 1 >> 1;
if (check(mid))
l = mid;
else
r = mid - 1;
}
return l;
}
signed main() {
cin >> T;
while (T--) {
scanf("%lld %lld", &n, &s);
mx = s;
for (long long i = 1; i <= n; i++)
scanf("%lld %lld", &t[i].l, &t[i].r), s -= t[i].l;
sort(t + 1, t + 1 + n, cmp);
ts = s;
printf("%lld\n", bsearch());
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
// static ArrayList a[] = new ArrayList[500006];
static int n;
static long a[][];
static long tot;
static boolean f(long mid) {
int cnt = 0;
Vector<Long>v = new Vector<>();
for(int i = 0 ; i<n;i++) {
if(a[i][1]<mid)
cnt ++;
else
v.add(a[i][0]);
}
if(cnt >= (n+1)/2)
return false;
Collections.sort(v);
long ans = 0;
for(int i =0 ;i<=n/2;i++)
ans += Math.max(0, mid - v.get(v.size()-i-1));
if(ans<=tot) return true;
return false;
}
public void solve () {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = in.nextInt();
while(t-- > 0) {
n = in.nextInt();
tot = in.nextLong();
long got = tot;
a = new long [n][2];
for(int i = 0; i <n;i++) {
a[i][0] = in.nextLong();
a[i][1] = in.nextLong();
tot -= a[i][0];
}
long start = 0;
long end = got ;
long ans = -1;
while(start <= end)
{
long mid = (start + end)/2L;
if(f(mid)) {
ans = mid;
start = mid+1;
}
else
end = mid - 1;
}
pw.println(ans);
}
pw.flush();
pw.close();
}
public static void main(String[] args) throws Exception {
new Thread(null,new Runnable() {
public void run() {
new Main().solve();
}
},"1",1<<26).start();
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
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 = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} 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 = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public void extended(int a,int b) {
if(b==0) {
d=a;
p=1;
q=0;
}
else
{
extended(b,a%b);
int temp=p;
p=q;
q=temp-(a/b)*q;
}
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static long[] shuffle(long[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
long temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static long GCD(long gcd,long x)
{
if(x==0)
return gcd;
else
return GCD(x,gcd%x);
}
static class pair implements Comparable<pair>
{
Long x,y;
pair(long x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Double(x).hashCode()*31 + new Long(y).hashCode();
}
}
}
class dsu{
int parent[];
dsu(int n){
parent=new int[n+1];
for(int i=0;i<=n;i++)
{
parent[i]=i;
}
}
int root(int n) {
while(parent[n]!=n)
{
parent[n]=parent[parent[n]];
n=parent[n];
}
return n;
}
void union(int _a,int _b) {
int p_a=root(_a);
int p_b=root(_b);
parent[p_a]=p_b;
}
boolean find(int a,int b) {
if(root(a)==root(b))
return true;
else
return false;
}
} | 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.*;
public class Main {
static long binarySearch(long a, long b, long s, long[] low, long[] high) {
if (a == b) return a;
long mid = (a + b + 1) / 2;
if (works(mid, s, low, high)) return binarySearch(mid, b, s, low, high);
else return binarySearch(a, mid - 1, s, low, high);
}
static boolean works(long median, long s, long[] low, long[] high) {
int n = low.length;
long[] cost = new long[n];
for (int i = 0; i < n; i++) {
if (median > high[i])
cost[i] = Long.MAX_VALUE;
else cost[i] = Math.max(median - low[i], 0);
}
Arrays.sort(cost);
for (int i = 0; i < (n+1)/2; i++) {
s -= cost[i];
if (s < 0) { return false; }
}
// System.out.println(median + " works!");
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int y = 0; y < t; y++) {
int n = sc.nextInt();
long s = sc.nextLong();
long[] low = new long[n];
long[] high = new long[n];
long maxSalary = 0;
for (int i = 0; i < n; i++) {
low[i] = sc.nextInt();
s -= low[i];
high[i] = sc.nextInt();
if (high[i] > maxSalary) maxSalary = high[i];
}
long minSalary = 0;
System.out.println(binarySearch(minSalary, maxSalary, s, low, high));
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int t;
int n;
long long s;
struct salary {
long long l, r;
};
salary a[200001];
bool cmp(salary a, salary b) { return a.l > b.l; }
void nhap() {
scanf("%d%lld", &n, &s);
for (int i = 1; i <= n; i++) {
scanf("%lld%lld", &a[i].l, &a[i].r);
}
sort(a + 1, a + n + 1, cmp);
}
bool check(long long k) {
int dem = n / 2 + 1;
long long sum = 0;
for (int i = 1; i <= n; i++) {
if (a[i].l <= k && a[i].r >= k && dem > 0) {
dem--;
sum += k;
} else {
sum += a[i].l;
dem -= (a[i].l > k);
}
}
if (dem > 0) {
return false;
}
return sum <= s;
}
void binary() {
long long l = a[n / 2 + 1].l;
long long r = s;
long long kq = 0;
while (l <= r) {
long long mid = (l + r) / 2;
if (check(mid)) {
kq = mid;
l = mid + 1;
} else
r = mid - 1;
}
cout << kq;
}
int main() {
int t;
cin >> t;
while (t--) {
nhap();
binary();
cout << "\n";
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long read() {
char x = getchar();
long long ans = 0, flag = 1;
while (!isdigit(x))
if (x == '-')
flag = -1, x = getchar();
else
x = getchar();
while (isdigit(x)) ans = ans * 10 + x - '0', x = getchar();
return ans * flag;
}
long long n, s;
struct node {
long long l, r;
bool operator<(node x) const { return l < x.l; }
} a[200005];
signed main() {
long long T;
cin >> T;
while (T--) {
cin >> n >> s;
for (long long i = 1; i <= n; i++) cin >> a[i].l >> a[i].r;
sort(a + 1, a + n + 1);
for (long long i = 1; i <= n; i++) s -= a[i].l;
long long l = a[(n + 1) / 2].l, r = 1e9, mid, ans = a[(n + 1) / 2].l;
while (l <= r) {
long long tmp = s, cnt = 0;
bool flag = 0;
mid = (l + r) >> 1;
for (long long i = n; i >= 1; i--) {
if (a[i].l <= mid && a[i].r >= mid && tmp >= mid - a[i].l) {
tmp -= mid - a[i].l;
cnt++;
continue;
}
if (a[i].l >= mid) cnt++;
}
if (cnt >= (n + 1) / 2)
l = mid + 1, ans = mid;
else
r = mid - 1;
}
cout << ans << endl;
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > d;
long long s;
int f(int cost) {
int cnt = 0;
long long sum = 0;
vector<int> vec;
for (int i = 0; i < (int)d.size(); i++)
if (cost <= d[i].first) {
cnt++;
sum += d[i].first;
} else if (d[i].second < cost)
sum += d[i].first;
else if (d[i].first < cost && cost <= d[i].second)
vec.push_back(d[i].first);
int rem = max(0, ((int)d.size() + 1) / 2 - cnt);
if (rem > (int)vec.size()) return false;
for (int i = 0; i < (int)vec.size(); i++)
if (i < (int)vec.size() - rem)
sum += vec[i];
else
sum += cost;
return sum <= s;
}
void solve() {
int n;
cin >> n >> s;
d.clear();
d.resize(n);
for (int i = 0; i < n; i++) cin >> d[i].first >> d[i].second;
sort(d.begin(), d.end());
int l = 1, r = int(1e9) + 100;
while (r - l > 1) {
int mid = l + (r - l) / 2;
if (f(mid))
l = mid;
else
r = mid;
}
cout << l << endl;
}
int main() {
int t;
cin >> t;
while (t--) solve();
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.*;
import java.util.*;
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;
if(l2.size()>(n/2))
{
System.out.println(i+" "+l1.size()+" "+l2.size()+" "+set.size()+" "+list.size()+"gdgd ");
System.exit(1);
}
while(l1.size()<(n/2))
{
try{Pair p=set.get(i++);
l1.add(p);}
catch(Exception e)
{
System.out.println(i+" "+l1.size()+" "+l2.size()+" "+set.size()+" "+list.size());
System.exit(1);
}
}
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
import math
from collections import defaultdict
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : map(int, input().split())
def write(*args, sep="\n"):
for i in args:
sys.stdout.write("{}".format(i) + sep)
INF = float('inf')
MOD = int(1e9 + 7)
for t in range(int(input())):
n, x= read()
lr = sorted([list(read()) for i in range(n)], reverse = True)
s = 0
e = int(1e9 + 10)
while s <= e:
m = (s + e) // 2
money = 0
a, b, c = 0, [], 0
for l, r in lr:
if l > m:
c += 1
money += l
elif r < m:
a += 1
money += l
else:
b.append(l)
if money > x or a >= n//2 + 1:
e = m - 1
continue
need = n//2 + 1 - c
cnt = 0
money += m * need
money += sum(b[need:])
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.readline
import heapq
sys.setrecursionlimit(100000)
def getN():
return int(input())
def getList():
return list(map(int, input().split()))
def solve():
ls, rs = [], []
n, money = getList()
sals = []
for _ in range(n):
a, b = getList()
sals.append((a, b))
# ls.sort()
# rs.sort()
ans_mx = 10**10
ans_mn = 0
while(ans_mx - ans_mn > 1):
# print(ans_mx, ans_mn)
tmp = 0
heap = []
mid = (ans_mn + ans_mx) // 2
for sal in sals:
if sal[1] < mid:
tmp += sal[0]
else:
heapq.heappush(heap, (-sal[0], -sal[1]))
# print(len(heap))
if len(heap) < (n + 1) // 2:
ans_mx = mid
continue
high = 0
tgt = n // 2
# print(heap)
while(heap):
sal_cur = heapq.heappop(heap)
if high <= tgt:
tmp += max(mid, -sal_cur[0])
high += 1
else:
tmp += -sal_cur[0]
if tmp <= money:
ans_mn = mid
else:
ans_mx = mid
# print(tmp)
# ================================
# print(ans_mx, ans_mn)
tmp = 0
heap = []
mid = ans_mx
# print("mid", mid)
for sal in sals:
if sal[1] < mid:
tmp += sal[0]
else:
heapq.heappush(heap, (-sal[0], -sal[1]))
if len(heap) < (n + 1) // 2:
print(ans_mn)
return
high = 0
tgt = n // 2
# print(heap)
while (heap):
sal_cur = heapq.heappop(heap)
# print(sal_cur)
if high <= tgt:
tmp += max(mid, -sal_cur[0])
high += 1
else:
tmp += -sal_cur[0]
# print(tmp)
if tmp <= money:
print(mid)
return
else:
print(ans_mn)
return
# print(tmp)
def main():
t = getN()
for times in range(t):
solve()
if __name__ == "__main__":
main()
"""
1
3 26
10 12
1 4
10 11
1
1 100
1 1
1
3 6
1 1000
2 1000
3 1000
1
9 100
2 4
3 5
8 100
25 100
2 39
1 2
23 40
1 20
2 10
""" | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
Interval[] interval;
int n;
boolean can(long budget, long median) {
int firstHalf = n >> 1;
int idx = 0;
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
if (interval[i].r < median) {
used[i] = true;
idx++;
if (idx > firstHalf) return false;
}
}
if (idx < firstHalf) {
for (int i = 0; i < n; i++) {
if (used[i] == true) continue;
used[i] = true;
idx++;
if (idx == firstHalf) break;
}
}
long usedMoney = 0;
for (int i = 0; i < n; i++) {
if (used[i] == true) usedMoney += interval[i].l;
else usedMoney += Math.max(interval[i].l, median);
}
return usedMoney <= budget;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int test = in.nextInt();
for (int t = 0; t < test; t++) {
n = in.nextInt();
long s = in.nextLong();
interval = new Interval[n];
for (int i = 0; i < n; i++) {
interval[i] = new Interval(in.nextInt(), in.nextInt());
}
Arrays.sort(interval);
long lo = 0, hi = s;
while (lo < hi) {
long mid = (lo + hi + 1) / 2;
if (can(s, mid) == false) {
hi = mid - 1;
} else
lo = mid;
}
out.println(lo);
}
}
class Interval implements Comparable<Interval> {
int l;
int r;
Interval(int _l, int _r) {
this.l = _l;
this.r = _r;
}
public int compareTo(Interval o) {
if (this.l != o.l) return this.l < o.l ? -1 : 1;
if (this.r != o.r) return this.r < o.r ? -1 : 1;
return 0;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long int, long long int> > v;
vector<long long int> v1;
long long n, s, lef;
bool check(long long x) {
long long t = lower_bound((v1).begin(), (v1).end(), x) - v1.begin();
if (t <= n / 2) return 1;
long long needed = t;
long long left = lef;
for (long long i = t - 1; i >= 0; i--) {
if (needed == n / 2) {
break;
}
if (v[i].second >= x) {
if ((x - v[i].first) <= left) {
left -= (x - v[i].first);
needed--;
}
}
}
if (needed == n / 2) return 1;
return 0;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int TESTS = 1;
cin >> TESTS;
while (TESTS--) {
cin >> n >> s;
long long l = 1000000007, r = -1;
lef = s;
v.clear();
v1.clear();
for (long long int i = 0; i < n; i++) {
long long x, y;
cin >> x >> y;
lef -= x;
l = min(l, x);
r = max(r, y);
v.push_back({x, y});
v1.push_back(x);
}
sort((v).begin(), (v).end());
sort((v1).begin(), (v1).end());
long long ans = v[n / 2].first;
long long m;
while (l <= r) {
m = (l + r) / 2;
if (check(m)) {
ans = max(ans, m);
l = m + 1;
} else {
r = m - 1;
}
}
cout << ans << '\n';
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range (int(input())):
n,s = [int(i) for i in input().split()]
l = []
r = []
v = []
for i in range (n):
li,ri = [int(i) for i in input().split()]
l.append(li)
r.append(ri)
v.append([li,ri])
l.sort()
r.sort()
v.sort()
low = l[n//2]
high = r[n//2]
while(low<high):
# print(low,high)
mid = (low+high+1)//2
curr = []
cost = 0
rem = []
for i in range (n):
if v[i][1]<mid:
curr.append(v[i])
else:
rem.append(v[i])
curr.extend(rem)
for i in range (n):
if i<n//2:
cost+=curr[i][0]
else:
cost+=max(mid, curr[i][0])
if cost<=s:
low = mid
else:
high = mid-1
print(low) | PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
using PII = pair<int, int>;
void solve() {
int n;
LL s;
scanf("%d%lld", &n, &s);
vector<int> lb(n), ub(n);
for (int i = 0; i < n; ++i) scanf("%d%d", &lb[i], &ub[i]);
auto check = [&](int mid) -> int {
multiset<LL> se;
LL tot = 0;
int need = (n - 1) / 2;
for (int i = 0; i < n; ++i) {
if (ub[i] < mid)
--need, tot += lb[i];
else if (lb[i] > mid)
tot += lb[i];
else
se.insert(lb[i]);
}
if (need < 0) return 2;
while (!se.empty() && need) {
tot += *se.begin();
se.erase(se.begin());
--need;
}
if (need) return -1;
tot += 1LL * mid * se.size();
if (tot <= s)
return 0;
else
return 1;
};
LL l = 1, r = 1e9;
while (l + 1 < r) {
LL m = (l + r) >> 1;
int ret = check(m);
if (ret < 0)
l = m + 1;
else if (ret > 0)
r = m - 1;
else
l = m;
}
if (check(r) == 0)
printf("%lld\n", r);
else
printf("%lld\n", l);
}
int main() {
int t;
scanf("%d", &t);
while (t--) solve();
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | 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 = 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 sys
import operator
input = sys.stdin.buffer.readline
def f(med):
total = 0
cnt = 0
cnt2 = 0
other = []
for x in salaries:
if x[0] > med:
total += x[0] # too big pay min salary
cnt += 1
elif x[1] < med:
total += x[0] # useless so pay min salaray
cnt2 += 1
else:
other.append(x)
if cnt2 > n/2:
return False
other.sort(reverse=True)
for x in other:
if cnt< n/2:
total += med
cnt +=1
else:
total += x[0]
if total > s:
return False
return True
q = int(input())
for _ in range(q):
salaries = []
minl = 999999999999999
maxl = -1
n, s = map(int, input().split())
for __ in range(n):
l, r = map(int, input().split())
if l<minl:
minl = l
if r > maxl:
maxl = r
salaries.append((l, r))
# for i in range(10):
# print(f"i:{i} f:f{f(i)}")
# binary search
a= minl
b = maxl
while b>=a:
m=(a+b)//2
##
##
if f(m):
a=m+1
else:
b=m-1
# print("ANS")
print(b)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 |
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class Main {
public static int maxn=200010,n;
public static long s;
public static node p[]=new node[maxn];
public static Comparator<Long> cmp=new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
// TODO θͺε¨ηζηζΉζ³εζ Ή
return (int) (o1-o2);
}
};
/* 1
15 8300491723
526326566 749490258
593725844 975583387
592457280 779975895
62319931 531228245
566155304 955481513
105903835 343449476
433324604 771659156
544623985 560404804
811800379 831435965
963144608 974793773
819869642 958244595
940843567 953509489
135976689 281360071
888573574 965239390
315445915 724421161*/
public static boolean chk(int mid) {
long sum=0;
long cnt1=0;
long cnt2=0;
ArrayList<Long> v=new ArrayList<Long>();
for(int i=0;i<n;i++) {
if(p[i].b<mid) {
sum+=p[i].a;
cnt1++;
}else if(p[i].a>mid) {
sum+=p[i].a;
cnt2++;
}else {
v.add(p[i].a);
}
}
if(cnt1>n/2) {
return false;
}
if(cnt2>n/2) {
return true;
}
v.sort(cmp);
//System.out.println(v.get(0)+" "+v.get(v.size()-1)+"?");
long need=n/2-cnt2+1;
for(int i=0;i<v.size()-need;i++) {
sum+=v.get(i);
}
sum+=need*mid;
return (sum<=s);
}
public static void main(String args[]) {
InputReader sc=new InputReader(System.in);
int t=sc.nextInt();
while(t-->0) {
n=sc.nextInt();
s=sc.nextLong();
for(int i=0;i<n;i++) {
p[i]=new node();
p[i].a=sc.nextInt();
p[i].b=sc.nextInt();
}
Arrays.sort(p,0,n);
int l=0;
int r=1000000010;
int mid=0;
while(r-l>1) {
mid=(l+r)>>1;
//System.out.println(l+" "+r+" "+mid);
if(chk(mid)) {
l=mid;
}else {
r=mid;
}
}
System.out.println(l);
}
}
}
class node implements Comparable<node>{
long a,b;
public int compareTo(node o) {
if(this.a==o.a) {
return (int) (this.b-o.b);
}else {
return (int) (this.a-o.a);
}
}
}
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 sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,s=map(int,input().split())
lr=[list(map(int,input().split())) for i in range(n)]
ng=10**9+1
ok=0
while ng-ok>1:
mid=(ok+ng)//2
cnt_more=0
ss=0
v=[]
for l,r in lr:
if mid<=l:
cnt_more+=1
ss+=l
elif l<mid<=r:
v.append(l)
else:
ss+=l
v.sort()
need=max(0,n//2+1-cnt_more)
if len(v)<need:
ng=mid
continue
for i in range(len(v)):
if i<len(v)-need:
ss+=v[i]
else:
ss+=mid
if ss<=s:
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.util.*;
import java.io.*;
public class EdD {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(bf.readLine());
for(int i = 0;i<t;i++){
// String input1 = bf.readLine().trim();
// String input2 = bf.readLine().trim();
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
long s = Long.parseLong(st.nextToken());
int[][] bounds = new int[n][2];
for(int j = 0;j<n;j++){
StringTokenizer st1 = new StringTokenizer(bf.readLine());
bounds[j][0] = Integer.parseInt(st1.nextToken());
bounds[j][1] = Integer.parseInt(st1.nextToken());
}
long l = 0;
long r = 1000000000;
while (l < r){
long mid = (l+r+1)/2;
int countleft = 0;
int countright = 0;
long sumright = 0;
long sumleft = 0;
ArrayList<Int> array = new ArrayList<Int>();
for(int j = 0;j<n;j++){
if (bounds[j][1] < mid){
countleft++;
sumleft+=bounds[j][0];
}
else if (bounds[j][0] > mid){
countright++;
sumright+=bounds[j][0];
}
else{
array.add(new Int(bounds[j][0], bounds[j][1]));
}
}
Collections.sort(array);
long minsum = 0;
for(int k = 0;k< array.size();k++){
if (k <= (n-3-2*countleft)/2)
minsum+=array.get(k).getL();
else
minsum+= mid;
}
minsum+=sumright;
minsum+=sumleft;
if (countright > n/2){
l = mid;
}
else if (countleft > n/2){
r = mid-1;
}
else if (minsum <= s){
l = mid;
}
else{
r = mid-1;
}
}
out.println(l);
}
out.println();
out.close();
}
static class Int implements Comparable<Int>{
private int l;
private int r;
public Int(int l, int r){
this.r = r;
this.l = l;
}
public int getL() {
return l;
}
public void setL(int l) {
this.l = l;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public int compareTo(Int other){
if (other.l != l)
return l - other.l;
else
return r - other.r;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
| 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
readline = sys.stdin.readline
inf = 10**16
def calc(m, L, R):
N = len(L)
cl = 0
cr = 0
ss = 0
candi = []
for i in range(N):
if L[i] > m:
cr += 1
ss += L[i]
elif R[i] < m:
cl += 1
ss += L[i]
else:
candi.append(L[i])
cm = len(candi)
if cl > N//2:
return inf
k = min(cm, N//2 - cl)
candi.sort()
ss += sum(candi[:k])
ss += (cm - k)*m
return ss
T = int(readline())
Ans = [None]*T
for qu in range(T):
M, LS = map(int, readline().split())
L = [None]*M
R = [None]*M
for i in range(M):
L[i], R[i] = map(int, readline().split())
ok = 0
ng = 10**9+1
while abs(ok - ng) > 1:
med = (ok + ng)//2
if calc(med, L, R) <= LS:
ok = med
else:
ng = med
Ans[qu] = 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 | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
Problems problems = new Problems();
problems.solve();
}
}
class Problems {
Parser parser = new Parser();
void solve() {
int t = parser.parseInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
Problem problem = new Problem();
sb.append(problem.solve()).append("\n");
}
System.out.print(sb.toString());
}
class Problem {
String solve() {
int n = parser.parseInt();
long s = parser.parseLong();
List<Range> ranges = new ArrayList<>();
for (int i = 0; i < n; i++) {
int l = parser.parseInt();
int r = parser.parseInt();
ranges.add(new Range(l, r));
}
ranges.sort((o1, o2) -> {
if(o1.l != o2.l) {
return Integer.compare(o1.l, o2.l);
}
return Integer.compare(o1.r, o2.r);
});
long l = -1;
long r = 1_000_000_009;
while (l + 1 < r) {
long m = (l + r) / 2;
if (ok(ranges, m, s)) l = m;
else r = m;
}
return String.valueOf(l);
}
boolean ok(List<Range> ranges, long v, long s) {
int size = ranges.size();
long now = 0;
int count = 0;
for (Range range : ranges) {
if (range.r < v) {
now += range.l;
} else if (range.l > v) {
now += range.l;
count += 1;
}
}
for (int i = size - 1; i >= 0; i--) {
Range range = ranges.get(i);
if (range.l > v || range.r < v) continue;
if (count < (size + 1) / 2) {
count += 1;
now += v;
} else {
now += range.l;
}
}
return count >= (size + 1) / 2 && s >= now;
}
class Range {
int l, r;
public Range(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range range = (Range) o;
return l == range.l &&
r == range.r;
}
@Override
public int hashCode() {
return Objects.hash(l, r);
}
@Override
public String toString() {
return "Range{" +
"l=" + l +
", r=" + r +
'}';
}
}
}
}
class Parser {
private final Iterator<String> stringIterator;
private final Deque<String> inputs;
Parser() {
this(System.in);
}
Parser(InputStream in) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
stringIterator = br.lines().iterator();
inputs = new ArrayDeque<>();
}
void fill() {
while (inputs.isEmpty()) {
if (!stringIterator.hasNext()) throw new NoSuchElementException();
inputs.addAll(Arrays.asList(stringIterator.next().split(" ")));
while (!inputs.isEmpty() && inputs.getFirst().isEmpty()) {
inputs.removeFirst();
}
}
}
Integer parseInt() {
fill();
if (!inputs.isEmpty()) {
return Integer.parseInt(inputs.pollFirst());
}
throw new NoSuchElementException();
}
Long parseLong() {
fill();
if (!inputs.isEmpty()) {
return Long.parseLong(inputs.pollFirst());
}
throw new NoSuchElementException();
}
Double parseDouble() {
fill();
if (!inputs.isEmpty()) {
return Double.parseDouble(inputs.pollFirst());
}
throw new NoSuchElementException();
}
String parseString() {
fill();
return inputs.removeFirst();
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DSalaryChanging solver = new DSalaryChanging();
int testCount = in.scanInt();
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DSalaryChanging {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
long salary = in.scanLong();
int[][] ar = new int[n][2];
long base = 0;
for (int i = 0; i < n; i++) {
ar[i][0] = in.scanInt();
ar[i][1] = in.scanInt();
base += ar[i][0];
}
long low = 0;
long high = salary;
long index = -1;
while (low <= high) {
long mid = (low + high) >> 1;
int vadhare = 0;
ArrayList<Long> temp = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (ar[i][0] >= mid) vadhare++;
else if (ar[i][1] >= mid) {
temp.add(mid - ar[i][0]);
}
}
if (vadhare < n / 2 + 1) {
Collections.sort(temp);
long tempp = salary - base;
for (long l : temp) {
if (vadhare >= n / 2 + 1) break;
if (tempp >= l) {
tempp -= l;
vadhare++;
} else break;
}
}
if (vadhare >= n / 2 + 1) {
index = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
out.println(index);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
}
}
| 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 bisect
input=sys.stdin.readline
def checker(rem_,lower_):
sum_=0
a=[]
b=[]
for i in range(n):
if lower[i][1]>=rem_:
a.append(lower[i][0])
else:
b.append(lower[i][0])
a.sort(reverse=True)
if len(a) > n//2 and sum([max(j, rem_) for j in a[:n//2+1]]) + sum(a[n//2+1:]) + sum(b) <= s:
return(True)
return(False)
t=int(input())
for i in range(t):
lower=[]
higher=[]
n,s=map(int,input().split())
for i in range(n):
l,r=map(int,input().split())
lower.append([l,r])
higher.append(l)
higher.sort()
if sum(higher)==s:
print(higher[n//2])
else:
beg=1
end=1000000001
while end-beg>1:
mid=(beg+end)//2
#print(beg,end)
if checker(mid,lower):
beg=mid
else:
end=mid
print(beg)
| PYTHON3 |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Random;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
SalaryChanging solver = new SalaryChanging();
solver.solve(1, in, out);
out.close();
}
static class SalaryChanging {
int n;
long s;
int[][] a;
long lsum;
boolean ok(long x) {
int numLess = 0, numGreater = 0, numEqual = 0;
for (int i = 0; i < n; i++) {
if (a[i][0] < x) {
numLess++;
} else if (a[i][0] > x) {
numGreater++;
} else {
numEqual++;
}
}
if (numLess + numEqual < n / 2) {
return false;
}
EzLongArrayList diffs;
diffs = new EzLongArrayList();
for (int i = 0; i < n; i++) {
if (a[i][0] < x && x <= a[i][1]) {
diffs.add(x - a[i][0]);
}
}
int need = (n + 1) / 2 - (numEqual + numGreater);
if (diffs.size() < need) {
return false;
}
diffs.sort();
long total = 0;
for (int i = 0; i < need; i++) {
total += diffs.get(i);
}
return lsum + total <= s;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int tt = in.nextInt();
while (tt-- > 0) {
n = in.nextInt();
s = in.nextLong();
a = new int[n][2];
lsum = 0;
for (int i = 0; i < n; i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
lsum += a[i][0];
}
Arrays.sort(a, Comparator.comparingInt(o -> o[0]));
long ans = a[n / 2][0];
for (long jump = 2 * s; jump >= 1; jump /= 2) {
while (ok(ans + jump)) {
ans += jump;
}
}
out.println(ans);
}
}
}
static interface EzLongIterator {
boolean hasNext();
long next();
}
static final class EzLongSort {
private static final Random rnd = new Random();
private EzLongSort() {
}
private static void randomShuffle(long[] a, int left, int right) {
for (int i = left; i < right; i++) {
int j = i + rnd.nextInt(right - i);
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
public static void safeArraysSort(long[] a, int left, int right) {
if (left > right || left < 0 || right > a.length) {
throw new IllegalArgumentException(
"Incorrect range [" + left + ", " + right + ") was specified for sorting, length = " + a.length);
}
randomShuffle(a, left, right);
Arrays.sort(a, left, right);
}
}
static interface EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static class EzLongArrayList implements EzLongList, EzLongStack {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
private long[] array;
private int size;
public EzLongArrayList() {
this(DEFAULT_CAPACITY);
}
public EzLongArrayList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
array = new long[capacity];
size = 0;
}
public EzLongArrayList(EzLongCollection collection) {
size = collection.size();
array = new long[size];
int i = 0;
for (EzLongIterator iterator = collection.iterator(); iterator.hasNext(); ) {
array[i++] = iterator.next();
}
}
public EzLongArrayList(long[] srcArray) {
size = srcArray.length;
array = new long[size];
System.arraycopy(srcArray, 0, array, 0, size);
}
public EzLongArrayList(Collection<Long> javaCollection) {
size = javaCollection.size();
array = new long[size];
int i = 0;
for (long element : javaCollection) {
array[i++] = element;
}
}
public int size() {
return size;
}
public EzLongIterator iterator() {
return new EzLongArrayListIterator();
}
public boolean add(long element) {
if (size == array.length) {
enlarge();
}
array[size++] = element;
return true;
}
public long get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index " + index + " is out of range, size = " + size);
}
return array[index];
}
private void enlarge() {
int newSize = Math.max(size + 1, (int) (size * ENLARGE_SCALE));
long[] newArray = new long[newSize];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EzLongArrayList that = (EzLongArrayList) o;
if (size != that.size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[i] != that.array[i]) {
return false;
}
}
return true;
}
public int hashCode() {
int hash = HASHCODE_INITIAL_VALUE;
for (int i = 0; i < size; i++) {
hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER;
}
return hash;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < size; i++) {
sb.append(array[i]);
if (i < size - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString();
}
public void sort() {
EzLongSort.safeArraysSort(array, 0, size);
}
private class EzLongArrayListIterator implements EzLongIterator {
private int curIndex = 0;
public boolean hasNext() {
return curIndex < size;
}
public long next() {
if (curIndex == size) {
throw new NoSuchElementException("Iterator doesn't have more elements");
}
return array[curIndex++];
}
}
}
static interface EzLongList extends EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static class InputReader {
private final InputStream is;
private final byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
public InputReader(InputStream stream) {
is = stream;
}
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
static interface EzLongStack extends EzLongCollection {
int size();
EzLongIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static final class PrimitiveHashCalculator {
private PrimitiveHashCalculator() {
}
public static int getHash(long x) {
return (int) x ^ (int) (x >>> 32);
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | import sys
input = sys.stdin.readline
def solve(mid):
ans = 0
cnt = 0
tmp = []
for i in range(n):
if info[i][1] < mid:
ans += info[i][0]
elif mid < info[i][0]:
ans += info[i][0]
cnt += 1
else:
tmp.append(info[i][0])
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 | import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
//static final long MOD = 998244353;
static final long MOD = 1000000007;
static final int INF = 1000000007;
static int[][] perms;
static int index;
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner();
int Q = sc.nextInt();
String letters = "abcdefghijklmnopqrstuvwxyz";
StringBuilder print = new StringBuilder();
for (int q = 0; q < Q; q++) {
int N = sc.nextInt();
long S = sc.nextLong();
int[][] nums = new int[N][2];
ArrayList<Integer> low = new ArrayList<Integer>();
ArrayList<Integer> high = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
nums[i] = new int[]{sc.nextInt(),sc.nextInt()};
low.add(nums[i][0]);
high.add(nums[i][1]);
}
Collections.sort(low);
Collections.sort(high);
int minMed = low.get(N/2);
int maxMed = high.get(N/2);
while (minMed < maxMed) {
int med = (minMed+maxMed+1)/2;
int below = 0;
int above = 0;
long cost = 0;
PriorityQueue<Integer> border = new PriorityQueue<Integer>();
for (int i = 0; i < N; i++) {
if (nums[i][0] > med) {
above++;
cost += nums[i][0];
} else if (nums[i][1] < med) {
below++;
cost += nums[i][0];
} else {
//Could be med if necessary
border.add(nums[i][0]);
}
}
if (above > N/2) {
minMed = med+1;
} else if (below > N/2) {
maxMed = med-1;
} else {
while (below < N/2) {
cost += border.poll();
below++;
}
cost += ((N+1)/2 - above)*((long)med);
if (cost > S) {
maxMed = med-1;
} else {
minMed = med;
}
}
}
print.append(minMed + "\n");
}
System.out.print(print);
}
public static void permute(int[] nums, int l, int r) {
if (l == r) {
for (int i = 0; i < 4; i++) {
perms[index][i] = nums[i]*nums[i+1];
}
for (int i = 4; i < 10; i++) {
perms[index][i] = nums[i-4];
}
index++;
} else {
for (int i = l; i <= r; i++) {
nums = swap(nums,l,i);
permute(nums, l+1, r);
nums = swap(nums,l,i);
}
}
}
public static int[] swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
return a;
}
static class DisjointSetUnion {
public int[] parent;
public int[] weight;
public int count;
public DisjointSetUnion(int nodes) {
count = nodes;
parent = new int[nodes];
weight = new int[nodes];
for (int i = 0; i < nodes; i++) {
parent[i] = i;
weight[i] = 1;
}
}
//"find"
public int root(int p) {
while (p != parent[p]) {
p = parent[p];
}
return p;
}
//"union"
public void connect(int p, int q) {
int rootP = root(p);
int rootQ = root(q);
if (rootP == rootQ) return;
if (weight[rootP] < weight[rootQ]) {
parent[rootP] = rootQ;
weight[rootQ] += weight[rootP];
} else {
parent[rootQ] = rootP;
weight[rootP] += weight[rootQ];
}
count--;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
}
public static long power(long x, long y, long p) {
// Initialize result
long res = 1;
// Update x if it is more
// than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if((y & 1)==1)
res = (res * x) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long dist(int[] point, int[] point2) {
return (long)(Math.pow((point2[1]-point[1]),2)+Math.pow((point2[0]-point[0]),2));
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b,a%b);
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] arr1, int[] arr2) {
return arr2[1]-arr1[1];
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
long long int paixu(long long int shuzu[][2], long long int daxiao) {
long long int i, j, k, l;
l = daxiao;
if (l >= 1000) {
l = 1000;
}
for (l = l; l >= 1; l /= 2) {
for (i = l; i <= daxiao; i++) {
for (j = i; ((shuzu[j][1] < shuzu[j - l][1]) & (j > l)); j -= l) {
k = shuzu[j][1];
shuzu[j][1] = shuzu[j - l][1];
shuzu[j - l][1] = k;
k = shuzu[j][0];
shuzu[j][0] = shuzu[j - l][0];
shuzu[j - l][0] = k;
}
}
}
return 0;
}
long long int paixu2(long long int shuzu[][2], long long int daxiao) {
long long int i, j, k, l;
l = daxiao;
if (l >= 1000) {
l = 1000;
}
for (l = l; l >= 1; l /= 2) {
for (i = l; i <= daxiao; i++) {
for (j = i; ((shuzu[j][0] < shuzu[j - l][0]) & (j > l)); j -= l) {
k = shuzu[j][1];
shuzu[j][1] = shuzu[j - l][1];
shuzu[j - l][1] = k;
k = shuzu[j][0];
shuzu[j][0] = shuzu[j - l][0];
shuzu[j - l][0] = k;
}
}
}
for (i = 2; i <= daxiao; i++) {
if ((shuzu[i - 1][0] == shuzu[i][0]) & (shuzu[i - 1][1] > shuzu[i][1])) {
k = shuzu[i][0];
shuzu[i][0] = shuzu[i - 1][0];
shuzu[i - 1][0] = k;
}
}
return 0;
}
long long int min(long long int x, long long int y) {
if (x >= y) {
return y;
} else {
return x;
}
}
long long int max(long long int x, long long int y) {
if (x >= y) {
return x;
} else {
return y;
}
}
long long int sb[200001][2], jb[200001][2], m, n, i, j, k, maxhp, hp, p, tmp,
zuixiao, mid, mid1, mid2;
int main() {
scanf("%lld", &n);
for (i = 1; i <= n; i++) {
scanf("%lld%lld", &m, &hp);
maxhp = 0;
p = m;
tmp = 0;
for (j = 1; j <= m; j++) {
scanf("%lld%lld", &sb[j][0], &sb[j][1]);
jb[j][0] = sb[j][0];
jb[j][1] = sb[j][1];
}
if (m == 1) {
printf("%lld\n", min(hp, sb[1][1]));
continue;
}
paixu(sb, m);
mid = mid1 = sb[m / 2 + 1][1];
paixu2(jb, m);
zuixiao = jb[m / 2 + 1][0];
mid2 = zuixiao;
while (1) {
aaa:
if (mid == zuixiao) {
goto bbb;
}
k = 0;
maxhp = 0;
for (j = m; j >= 1; j--) {
if (maxhp > hp) {
if ((mid1 == mid2 + 1) & (mid == mid1)) {
mid = mid2;
goto bbb;
} else {
mid1 = mid;
mid = (mid1 + mid2) / 2;
goto aaa;
}
}
if (k == m / 2 + 1) {
maxhp += jb[j][0];
goto ccc;
}
if (jb[j][0] >= mid) {
maxhp += jb[j][0];
k++;
goto ccc;
}
if (k == m / 2 + 1) {
maxhp += jb[j][0];
goto ccc;
}
if (jb[j][1] >= mid) {
maxhp += mid;
k++;
goto ccc;
} else {
maxhp += jb[j][0];
}
ccc:
if ((maxhp > hp) | ((j == 1) & (k < m / 2 + 1))) {
if ((mid1 == mid2 + 1) & (mid == mid1)) {
mid = mid2;
goto bbb;
} else {
mid1 = mid;
mid = (mid1 + mid2) / 2;
goto aaa;
}
}
}
if ((mid1 == mid2 + 1) & (mid == mid1) | (mid1 == mid2)) {
mid = mid1;
goto bbb;
}
mid2 = mid;
if (mid1 == mid2 + 1) {
mid++;
} else {
mid = (mid1 + mid2) / 2;
}
}
bbb:
printf("%lld\n", mid);
}
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.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws Exception {
// StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next());
StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
StringBuilder sb = new StringBuilder();
Integer t = Integer.parseInt(stok.nextToken());
while(t-->0) {
Integer n = Integer.parseInt(stok.nextToken());
Long s = Long.parseLong(stok.nextToken());
long[][] a = new long[n][3];
long[][] b = new long[n][2];
for(int i=0;i<n;i++) {
a[i][0] = Long.parseLong(stok.nextToken());
a[i][1] = Long.parseLong(stok.nextToken());
b[i][0] = a[i][0];
b[i][1] = a[i][1];
}
Arrays.sort(a,(x,y)->(int)(x[1]-y[1]));
Arrays.sort(b,(x,y)->(int)(x[0]-y[0]));
a[0][2]=a[0][0];
for(int i=1;i<n;i++) a[i][2]=a[i-1][2]+a[i][0];
sb.append(maximum(b[n/2][0],a[n/2][1]+1,s,a,n));
sb.append("\n");
}
System.out.println(sb);
}
private static long maximum(long l,long r,long s,long[][] a,int n) {
if(r==l+1) return l;
long m = (l+r)/2;
int pos = getFirst(-1,n,m,a);
if(pos>n/2) return maximum(l,m,s,a,n);
while(pos>0 && a[pos][1]==a[pos-1][1] && a[pos][1]==m) pos--;
long tot = 0;
if(pos>0) tot = a[pos-1][2];
PriorityQueue<Long> q = new PriorityQueue<Long>();
// System.out.println(pos);
for(int i=pos;i<n;i++) {
q.add(a[i][0]);
}
for(int i=pos;i<n/2;i++) {
long v = q.poll();
if(v>m) return maximum(l,m,s,a,n);
tot += v;
}
for(int i=n/2;i<n;i++) tot += Math.max(m, q.poll());
if(tot<=s) return maximum(m,r,s,a,n);
return maximum(l,m,s,a,n);
}
private static int getFirst(int l,int r,long m, long[][] a) {
if(r==l+1) return r;
int p = (l+r)/2;
if(a[p][1]<m) return getFirst(p,r,m,a);
return getFirst(l,p,m,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;
long long mo(const long long input, const long long ceil) {
return input >= ceil ? input % ceil : input;
}
long long n, s, ans, l, r, i, mid, cnt, sum;
pair<long long, long long> a[400000];
void solve(long long tt) {
cin >> n >> s;
for (i = 1; i <= n; i++) {
cin >> a[i].first >> a[i].second;
}
sort(a + 1, a + n + 1);
ans = 1, l = 1, r = 1000000000000000;
while (l <= r) {
mid = (l + r) / 2;
cnt = (n + 1) / 2;
sum = 0;
for (i = n; i >= 1; i--) {
if (a[i].second >= mid && cnt) {
sum = sum + max(a[i].first, mid);
cnt--;
} else
sum = sum + a[i].first;
}
if (sum <= s && cnt == 0) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
cout << ans << "\n";
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
long long tt = 1;
cin >> tt;
for (long long i = 0; i < tt; i++) solve(tt);
cerr << "\n\n\nTime : "
<< 1000 * (long double)clock() / (long double)CLOCKS_PER_SEC << "ms\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;
long long s;
long long l[200010], r[200010], b[200010];
long long res;
bool ok(long long x) {
long long tmp = 0;
int dem;
dem = 0;
vector<int> mi;
mi.clear();
for (int i = 1; i <= n; i++) {
if (r[i] < x) {
tmp += l[i];
continue;
}
if (l[i] > x) {
tmp += l[i];
dem++;
continue;
}
tmp += x;
dem++;
mi.push_back(l[i]);
}
if (dem < n / 2 + 1) return false;
sort(mi.begin(), mi.end());
int now = 0;
while (dem > n / 2 + 1) {
if (now >= mi.size()) return false;
tmp += (mi[now] - x);
now++;
dem--;
}
return (tmp <= s);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int ntest;
cin >> ntest;
for (int test = 1; test <= ntest; test++) {
cin >> n >> s;
for (int i = 1; i <= n; i++) cin >> l[i] >> r[i];
for (int i = 1; i <= n; i++) b[i] = l[i];
sort(b + 1, b + n + 1);
long long lo, hi, mid;
lo = b[n / 2 + 1];
hi = 1000000100;
while (lo <= hi) {
mid = (lo + hi) >> 1;
if (ok(mid)) {
res = mid;
lo = mid + 1;
} else
hi = mid - 1;
}
cout << res << 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>
#pragma GCC optimize(2)
using namespace std;
const int man = 2e5 + 10;
template <typename T>
T gcd(T a, T b) {
return b == 0 ? a : gcd(b, a % b);
}
template <typename T>
T exgcd(T a, T b, T &g, T &x, T &y) {
if (!b) {
g = a, x = 1, y = 0;
} else {
exgcd(b, a % b, g, y, x);
y -= x * (a / b);
}
}
const long long mod = 1e9 + 7;
struct node {
int l, r;
bool operator<(const node &a) const { return l == a.l ? r > a.r : l > a.l; }
} a[man];
int n;
long long s;
bool check(long long mid) {
int cnt = n / 2 + 1;
long long sum = 0;
for (int i = 1; i <= n; i++) {
int l = a[i].l, r = a[i].r;
if (l <= mid && r >= mid && cnt) {
sum += mid;
cnt--;
} else {
sum += l;
if (l > mid) cnt--;
}
}
return (sum <= s && !cnt);
}
void slove() {
long long l = a[n / 2 + 1].l, r = s;
long long ans = a[n / 2 + 1].l + 1;
while (l <= r) {
long long mid = l + r >> 1;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
cin >> n;
cin >> s;
for (int i = 1; i <= n; i++) {
cin >> a[i].l >> a[i].r;
}
sort(a + 1, a + 1 + n);
slove();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
bool check(pair<long long int, long long int> arr[], long long int mid,
long long int n, long long int s) {
vector<pair<long long int, long long int>> both;
long long int l = 0, r = 0;
for (long long int i = 0; i < n; i++) {
if (arr[i].second < mid) {
s -= arr[i].first;
l++;
} else if (arr[i].first > mid) {
s -= arr[i].first;
r++;
} else {
both.push_back(arr[i]);
}
}
if (l > (n / 2) || r > (n / 2)) return false;
for (long long int i = 0; i < both.size(); i++) {
if (l < (n / 2)) {
s -= both[i].first;
l++;
} else {
s -= mid;
r++;
}
}
if (s < 0) return false;
return true;
}
void solve() {
long long int n, s, l, r = 0, a, b;
cin >> n >> s;
pair<long long int, long long int> arr[n];
for (long long int i = 0; i < n; i++) {
cin >> a >> b;
arr[i] = {a, b};
r = max(r, b);
}
sort(arr, arr + n);
l = arr[n / 2].first;
r = arr[n].second;
while (l < r) {
long long int mid = (l + r + 1) / 2;
if (check(arr, mid, n, s)) {
l = mid;
} else {
r = mid - 1;
}
}
cout << l << "\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int t;
cin >> t;
while (t--) {
solve();
}
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | 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
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: 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: break
else:
low = mid + 1
if high < low: break
print(high) | 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 SalaryChanging {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out,false);
int t = scanner.nextInt();
while(t-->0) {
int n = scanner.nextInt();
long s = scanner.nextLong();
long hi = Integer.MAX_VALUE;
long lo = 0;
long[][] vals = new long[2][n];
for(int i = 0; i < n; i++) {
vals[0][i] = scanner.nextInt();
vals[1][i] = scanner.nextInt();
s -= vals[0][i];
}
while(hi >= lo) {
long mid = (hi + lo)/2;
ArrayList<Long> temp = new ArrayList<>();
for(int i = 0; i < n; i++) {
if (mid > vals[1][i]) continue;
else if (mid <= vals[0][i]) temp.add(0L);
else temp.add(mid - vals[0][i]);
}
boolean bad = false;
if (temp.size() < (n + 1) /2) bad = true;
if (!bad) {
Collections.sort(temp);
long sum = 0;
for(int i = 0; i < (n + 1)/2; i++) {
sum += temp.get(i);
}
if (sum > s) bad = true;
}
if (bad) hi = mid - 1;
else lo = mid + 1;
}
out.println(lo - 1);
}
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(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 readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| JAVA |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long M = 3 * (1e5) + 7, mod = 1e9 + 7;
long long n, s;
vector<pair<long long, long long>> v;
bool ok(long long mid) {
vector<pair<long long, long long>> d;
for (auto u : v) {
if (u.second >= mid) {
d.push_back({u.first, u.second});
}
}
sort(d.begin(), d.end());
if (d.size() < v.size() / 2) return 0;
long long cnt = v.size() / 2, sum = mid;
while (cnt--) {
sum += max(d.back().first, mid);
d.pop_back();
}
if (d.size() == 0 || d.back().first > mid)
return 0;
else
d.pop_back();
for (auto u : v) {
if (u.first < mid && !(u.second >= mid)) {
d.push_back({u.first, u.second});
}
}
if (d.size() != v.size() / 2) return 0;
for (auto u : d) sum += u.first;
if (sum > s)
return 0;
else
return 1;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
long long tt;
cin >> tt;
while (tt--) {
cin >> n >> s;
for (long long i = 0; i < n; i++) {
long long l, r;
cin >> l >> r;
v.push_back({l, r});
}
sort(v.begin(), v.end());
long long lo = v[(long long)v.size() / 2].first, hi = 1e10, ans = 0;
while (lo <= hi) {
long long mid = (lo + hi) / 2;
if (ok(mid)) {
lo = mid + 1;
ans = mid;
} else
hi = mid - 1;
}
cout << ans << "\n";
v.clear();
}
return 0;
}
| CPP |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int o = 1 << 17;
const int maxn = 200005;
const int mod = 1000000007;
const int inf = 0x3f3f3f3f;
const long long huge = 100000000000000000LL;
long long s;
int n, t;
int l[maxn], r[maxn];
int tmp[maxn];
long long price(int med) {
long long ret = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (r[i] < med) continue;
tmp[cnt++] = max(0, med - l[i]);
}
sort(tmp, tmp + cnt);
if (cnt < n / 2 + 1) return huge;
for (int i = 0; i <= n / 2; i++) ret += tmp[i];
return ret;
}
void solve() {
cin >> n >> s;
for (int i = 0; i < n; i++) {
cin >> l[i] >> r[i];
s -= l[i];
}
int lo = 0;
int hi = 1e9;
while (lo < hi) {
int mid = (lo + hi + 1) / 2;
if (price(mid) <= s)
lo = mid;
else
hi = mid - 1;
}
cout << lo << endl;
}
int main() {
ios::sync_with_stdio(false);
cin >> t;
for (int i = 0; i < t; i++) solve();
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n=int(input())
s=list(input())
s.append("B")
b=s.count("B")
w=len(s)-b
if b==1 or w==0:
print(0)
exit(0)
s.pop(n)
b-=1
if b%2 and w%2:
print("-1")
exit(0)
if b%2==0:
p=[]
for i in range(s.index('B'),n-1):
if s[i]=="W":
continue
if s[i+1:].count('B')==0:
break
p.append(i+1)
if s[i+1]=='W':
s[i+1]="B"
else:
s[i+1]="W"
print(len(p))
print(*p)
else:
p=[]
for i in range(s.index('W'),n-1):
if s[i]=="B":
continue
if s[i+1:].count('W')==0:
break
p.append(i+1)
if s[i+1]=='W':
s[i+1]="B"
else:
s[i+1]="W"
print(len(p))
print(*p) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
bool besarDulu(const int &a, const int &b) { return a > b; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
string s, sOri;
cin >> sOri;
s = sOri;
int B_count = 0, W_count = 0;
bool W_ada = false, B_ada = false;
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'W') {
W_ada = true;
W_count++;
} else {
B_ada = true;
B_count++;
}
}
if ((B_ada && !W_ada) || (!B_ada && W_ada)) {
cout << "0" << '\n';
return 0;
}
if (W_count % 2 == 1 && B_count % 2 == 1) {
cout << "-1" << '\n';
return 0;
}
int W_cara = 0, B_cara = 0;
vector<int> caraPola_B, caraPola_W;
int minim;
if (B_count % 2 == 0) {
for (int i = 0; i < s.length() - 1; i++) {
if (s[i] == 'B') {
B_cara++;
caraPola_B.push_back(i + 1);
s[i] = 'W';
if (s[i + 1] == 'W')
s[i + 1] = 'B';
else
s[i + 1] = 'W';
}
}
} else {
B_cara = INT_MAX;
}
if (W_count % 2 == 0) {
s = sOri;
for (int i = 0; i < s.length() - 1; i++) {
if (s[i] == 'W') {
W_cara++;
caraPola_W.push_back(i + 1);
s[i] = 'B';
if (s[i + 1] == 'B')
s[i + 1] = 'W';
else
s[i + 1] = 'B';
}
}
} else {
W_cara = INT_MAX;
}
minim = min(W_cara, B_cara);
if (minim <= n) {
cout << minim << '\n';
for (int i = 0; i < minim - 1; i++) {
if (minim == B_cara)
cout << caraPola_B[i] << " ";
else
cout << caraPola_W[i] << " ";
}
if (minim == B_cara)
cout << caraPola_B[minim - 1] << '\n';
else
cout << caraPola_W[minim - 1] << '\n';
return 0;
} else {
cout << "-1" << '\n';
return 0;
}
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
char s[200005];
vector<int> ans;
int main() {
int T = 1;
while (T--) {
int n;
cin >> n;
scanf("%s", s + 1);
int cnt1 = 0, cnt2 = 0;
for (int i = 1; i <= n; i++) s[i] == 'B' ? cnt1++ : cnt2++;
if (cnt1 % 2 && cnt2 % 2) {
puts("-1");
continue;
}
if (cnt1 % 2) {
for (int i = 1; i < n; i++) {
if (s[i] == 'W') {
ans.push_back(i);
if (s[i + 1] == 'B')
s[i + 1] = 'W';
else
s[i + 1] = 'B';
}
}
} else {
for (int i = 1; i < n; i++) {
if (s[i] == 'B') {
ans.push_back(i);
if (s[i + 1] == 'B')
s[i + 1] = 'W';
else
s[i + 1] = 'B';
}
}
}
printf("%d ", ans.size());
for (int i = 0; i < ans.size(); i++) printf("%d ", ans[i]);
}
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | """
Satwik_Tiwari ;) .
5th AUGUST , 2020 - WEDNESDAY
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve():
n = int(inp())
s = list(inp())
new = deepcopy(s)
ans = []
for i in range(n-1):
if(s[i] == 'B'):
continue
else:
s[i] = 'B'
if(s[i+1] == 'B'):
s[i+1] = 'W'
else:
s[i+1] = 'B'
ans.append(i)
if(s[n-1] == 'B'):
print(len(ans))
print(' '.join(str(ans[i]+1) for i in range(len(ans))))
return
ans = []
for i in range(n-1):
if(new[i] == 'W'):
continue
else:
new[i] = 'W'
if(new[i+1] == 'B'):
new[i+1] = 'W'
else:
new[i+1] = 'B'
ans.append(i)
if(new[n-1] == 'W'):
print(len(ans))
print(' '.join(str(ans[i]+1) for i in range(len(ans))))
return
print(-1)
testcase(1)
# testcase(int(inp()))
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | import sys
def flip(c, i):
if c[i] == 'W':
c[i] = 'B'
else:
c[i] = 'W'
n = int(input())
c = list(input())
ops = []
for i in range(1, n - 1):
if c[i - 1] != c[i]:
flip(c, i)
flip(c, i + 1)
ops.append(i + 1)
if c[n - 1] != c[n - 2]:
if n % 2 == 0:
print(-1)
sys.exit(0)
for i in range(n // 2):
ops.append(2 * i + 1)
print(len(ops))
print(' '.join([str(o) for o in ops]))
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
int c1 = 0, c2 = 0;
vector<bool> a(n);
for (int i = 0; i < n; i++) {
char tmp;
cin >> tmp;
if (tmp == 'B') {
c1++;
a[i] = 0;
} else {
c2++;
a[i] = 1;
}
}
if (c1 % 2 == 1 && c2 % 2 == 1) {
cout << -1 << '\n';
return;
}
vector<int> ans;
for (int i = 0; i < n - 1; i++) {
if (a[i] == 1) {
ans.push_back(i + 1);
a[i] = !a[i];
a[i + 1] = !a[i + 1];
}
}
if (n % 2 == 1 && a[n - 1] == 1) {
for (int i = 0; i < n - 1; i++) {
if (i % 2 == 0) {
ans.push_back(i + 1);
}
}
}
cout << ans.size() << '\n';
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << '\n';
;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) {
solve();
}
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | '''input
1
B
'''
from sys import stdin
import math
def input():
return stdin.readline()[:-1]
n = int(input())
l = list(input())
l2 = l[:]
if n == 1:
print(-1)
else:
# all white to black
i = 0
pos = []
while i < n - 1:
if l[i] == 'W' and l[i + 1] == 'W':
pos.append(i+1)
l[i] = 'B'
l[i+1] = 'B'
i += 2
elif l[i] == 'B' and l[i + 1] == 'B':
i += 2
elif l[i] == 'W' and l[i + 1] == 'B':
pos.append(i+1)
l[i] = 'B'
l[i+1] = 'W'
i += 1
elif l[i] == 'B' and l[i + 1] == 'W':
i += 1
if l[-1] == 'B':
print(len(pos))
if len(pos) > 0:
print(' '.join(map(str,pos)))
else:
# all black to white
i = 0
pos2 = []
while i < n - 1:
if l2[i] == 'B' and l2[i + 1] == 'B':
pos2.append(i+1)
l2[i] = 'W'
l2[i+1] = 'W'
i += 2
elif l2[i] == 'W' and l2[i + 1] == 'W':
i += 2
elif l2[i] == 'B' and l2[i + 1] == 'W':
pos2.append(i+1)
l2[i] = 'W'
l2[i+1] = 'B'
i += 1
elif l2[i] == 'W' and l2[i + 1] == 'B':
i += 1
if l2[-1] == 'W':
print(len(pos2))
if len(pos2) > 0:
print(' '.join(map(str,pos2)))
else:
print(-1)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | # map(int, input().split())
# list(map(int, input().split()))
def pairup(col,i):
if i >= n:
return 0
if blocks[i] != col:
pairup(col,i+1)
elif blocks[i] != blocks[i+1]: # should not give index error
blocks[i], blocks[i+1] = blocks[i+1], blocks[i]
seq.append(i+1)
pairup(col,i+1)
else:
pairup(col,i+2)
def invert(col):
i = 0
while (i<n):
if blocks[i] == col and blocks[i] == blocks[i+1]:
seq.append(i+1)
i+=2
else:
i+=1
n = int(input())
blocks = input()
bc = blocks.count('B')
wc = blocks.count('W')
blocks = list(blocks)
seq = []
if bc % 2 == 1 and wc % 2 == 1:
print(-1)
elif bc == 0 or wc == 0:
print(0)
else:
if bc % 2 == 0:
pairup('B',0)
#print(blocks)
invert('B')
else:
pairup('W',0)
#print(blocks)
invert('W')
print(len(seq))
print(' '.join([str(x) for x in seq]))
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n = int(input())
s = list(input())
ans = []
f = "W" if s.count("B")%2 == 0 else "B"
for i in range(0,len(s) - 1):
if(s[i] != f):
ans.append(i+1)
s[i] = f
if(s[i + 1] == "W"):
s[i + 1] = "B"
else:
s[i + 1] = "W"
if(s[len(s) - 1] == f):
if(len(ans)>0):
print(len(ans))
print(*ans)
else:
print(0)
else:
print(-1)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | # from debug import debug
import sys
from math import ceil
input = sys.stdin.readline
n = int(input())
s = [True if x == 'W' else False for x in input().strip()]
r = s[:]
store = []
for i in range(n-1):
if s[i]: continue
else: store.append(i+1); s[i] = not s[i]; s[i+1] = not s[i+1]
if s[-1]:
print(len(store))
print(*store)
else:
store = []
for i in range(n-1):
if not r[i]: continue
else: store.append(i+1); r[i] = not r[i]; r[i+1] = not r[i+1]
if not r[-1]: print(len(store)); print(*store)
else: print(-1) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class codeforces
{
static int M = 1_000_000_007;
static int INF = 2_000_000_000;
static final FastScanner fs = new FastScanner();
//variable
public static void main(String[] args) throws IOException {
int n = fs.nextInt();
char[] s = fs.next().toCharArray();
ArrayList<Integer> ans = new ArrayList<>();
int nw = 0, nb = 0;
for(int i=0;i<n;i++){
if(s[i] == 'W') nw++;
else nb++;
}
if(nb % 2 == 1 && nw % 2 == 1) {
System.out.println("-1");
return;
}
for(int i=0;i<n-1;i++) {
if(s[i] == 'B') {
s[i] = 'W';
s[i+1] = (s[i+1]=='W')?'B':'W';
ans.add(i+1);
}
}
if(s[n-1] == 'B') {
for(int i=0;i<n-1;i+=2) ans.add(i+1);
}
System.out.println(ans.size());
for(int i:ans)
System.out.print(i+" ");
}
//class
//function
// Template
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static int gcd(int a, int b) {
if(a==0) return b;
return gcd(b%a,a);
}
static void premutation(int n, ArrayList<Integer> arr,boolean[] chosen) {
if(arr.size() == n) {
}else {
for(int i=1; i<=n; i++) {
if(chosen[i]) continue;
arr.add(i);
chosen[i] = true;
premutation(n,arr,chosen);
arr.remove(i);
chosen[i] = false;
}
}
}
static boolean isPalindrome(char[] c) {
int n = c.length;
for(int i=0; i<n/2; i++) {
if(c[i] != c[n-i-1]) return false;
}
return true;
}
static long nCk(int n, int k) {
return (modMult(fact(n),fastexp(modMult(fact(n-k),fact(k)),M-2)));
}
static long fact (long n) {
long fact =1;
for(int i=1; i<=n; i++) {
fact = modMult(fact,i);
}
return fact%M;
}
static int modMult(long a,long b) {
return (int) (a*b%M);
}
static int negMult(long a,long b) {
return (int)((a*b)%M + M)%M;
}
static long fastexp(long x, int y){
if(y==1) return x;
long ans = fastexp(x,y/2);
if(y%2 == 0) return modMult(ans,ans);
else return modMult(ans,modMult(ans,x));
}
static final Random random = new Random();
static void ruffleSort(int[] arr)
{
int n = arr.length;
for(int i=0; i<n; i++)
{
int j = random.nextInt(n),temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
public static class Pairs implements Comparable<Pairs>
{
int value,index;
Pairs(int value, int index)
{
this.value = value;
this.index = index;
}
public int compareTo(Pairs p)
{
return Integer.compare(this.value,p.value);
}
}
}
class FastScanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer str = new StringTokenizer("");
String next() throws IOException
{
while(!str.hasMoreTokens())
str = new StringTokenizer(br.readLine());
return str.nextToken();
}
char nextChar() throws IOException {
return next().charAt(0);
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
float nextfloat() throws IOException
{
return Float.parseFloat(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
byte nextByte() throws IOException
{
return Byte.parseByte(next());
}
int [] arrayIn(int n) throws IOException
{
int[] arr = new int[n];
for(int i=0; i<n; i++)
{
arr[i] = nextInt();
}
return arr;
}
}
| JAVA |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int b = 0, c = 0;
int k = 0;
int n;
void solve(void) {
cin >> n;
string x;
cin >> x;
vector<int> indexB;
vector<int> indexW;
for (int i = 0; i < n; i++) {
if (x[i] == 'B') {
b++;
indexB.push_back(i + 1);
} else {
c++;
indexW.push_back((i + 1));
}
}
if (b & 1 && c & 1) {
cout << -1 << endl;
} else if (b == 0 || c == 0)
cout << 0 << '\n';
else {
if (!(b & 1) && (c & 1 || (b <= c))) {
int i = 0;
int m = 0;
for (int k = 0; k < indexB.size(); k += 2)
m = m + (indexB[k + 1] - indexB[k]);
if (m > 3 * n) {
cout << -1 << endl;
return;
}
cout << m << '\n';
while (i < indexB.size()) {
for (int j = indexB[i]; j < indexB[i + 1]; j++) cout << j << ' ';
i += 2;
}
} else {
int i = 0;
int m = 0;
for (int k = 0; k < indexW.size(); k += 2)
m = m + (indexW[k + 1] - indexW[k]);
if (m > 3 * n) {
cout << -1 << endl;
return;
}
cout << m << '\n';
while (i < indexW.size()) {
for (int j = indexW[i]; j < indexW[i + 1]; j++) cout << j << ' ';
i += 2;
}
}
}
}
int main(void) {
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
solve();
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s;
cin >> s;
int count_b = 0, count_w = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W')
count_w++;
else
count_b++;
}
if (count_b % 2 != 0 && count_w % 2 != 0) {
cout << -1 << endl;
return 0;
} else if (count_b == 0 || count_w == 0) {
cout << 0 << endl;
return 0;
}
char chng;
if (count_b % 2 != 0)
chng = 'B';
else
chng = 'W';
vector<int> v;
for (int i = 0; i < n - 1; i++) {
if (chng == s[i])
continue;
else {
s[i] = chng;
if (s[i + 1] == 'B')
s[i + 1] = 'W';
else
s[i + 1] = 'B';
v.push_back(i + 1);
}
}
cout << v.size() << endl;
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << endl;
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n = int(input())
block = list(input())
W=0
B=0
moves = []
for x in block:
if x == 'W':
W += 1
else:
B += 1
status = 0
if W%2 == 1 and B%2 ==1:
print(-1)
status = -1
else:
if W%2 == 0:
for i in range(len(block)-1):
if block[i] == 'W':
if block[i] == block[i+1]:
moves.append(i+1)
block[i] = 'B'
block[i+1] = 'B'
else:
moves.append(i+1)
block[i], block[i+1] = block[i+1], block[i]
else:
for i in range(len(block)-1):
if block[i] == 'B':
if block[i] == block[i+1]:
moves.append(i+1)
block[i] = 'W'
block[i+1] = 'W'
else:
moves.append(i+1)
block[i], block[i+1] = block[i+1], block[i]
if status != -1:
moves = list(map(str, moves))
print(len(moves))
print(" ".join(moves)) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | /* Rajkin Hossain */
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class B {
FastInput k = new FastInput(System.in);
//FastInput k = new FastInput("/home/rajkin/Desktop/input.txt");
FastOutput z = new FastOutput();
char [] y;
int n;
void startAlgo(){
int b = 0, w = 0;
ArrayList<Integer> ans = new ArrayList<Integer>();
for(int i = 0; i<n; i++) {
if(y[i] == 'B') {
b++;
}
else {
w++;
}
}
if(b % 2 == 0) {
for(int i = 0; i<n-1; i++) {
if(y[i] == 'B' && y[i+1] == 'B') {
y[i] = 'W';
y[i+1] = 'W';
ans.add(i);
}
else if(y[i] == 'B' && y[i+1] == 'W'){
y[i+1] = 'B';
y[i] = 'W';
ans.add(i);
}
}
z.println(ans.size());
for(int i = 0; i<ans.size(); i++) {
z.print((ans.get(i)+1)+" ");
}
if(ans.size() != 0) {
z.println();
}
}
else if(w % 2 == 0) {
for(int i = 0; i<n-1; i++) {
if(y[i] == 'W' && y[i+1] == 'W') {
y[i] = 'B';
y[i+1] = 'B';
ans.add(i);
}
else if(y[i] == 'W' && y[i+1] == 'B'){
y[i+1] = 'W';
y[i] = 'B';
ans.add(i);
}
}
z.println(ans.size());
for(int i = 0; i<ans.size(); i++) {
z.print((ans.get(i)+1)+" ");
}
if(ans.size() != 0) {
z.println();
}
}
else {
z.println(-1);
}
}
void startProgram() {
while(k.hasNext()) {
n = k.nextInt();
y = k.next().toCharArray();
startAlgo();
}
z.flush();
System.exit(0);
}
public static void main(String [] args) throws IOException {
new Thread(null, new Runnable(){
public void run(){
try{
new B().startProgram();
}
catch(Exception e){
e.printStackTrace();
}
}
},"Main",1<<28).start();
}
/* MARK: FastInput and FastOutput */
class FastInput {
BufferedReader reader;
StringTokenizer tokenizer;
FastInput(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
FastInput(String path){
try {
reader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
String next() {
return nextToken();
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
boolean hasNext(){
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.valueOf(nextToken());
}
int [] getInputIntegerArray(int n) {
int [] input = new int[n];
for(int i = 0; i<n; i++) {
input[i] = nextInt();
}
return input;
}
long [] getInputLongArray(int n) {
long [] input = new long[n];
for(int i = 0; i<n; i++) {
input[i] = nextLong();
}
return input;
}
int [] getInputIntegerArrayOneBasedIndex(int n) {
int [] input = new int[n+1];
for(int i = 1; i<=n; i++) {
input[i] = nextInt();
}
return input;
}
long [] getInputLongArrayOneBasedIndex(int n) {
long [] input = new long[n+1];
for(int i = 1; i<=n; i++) {
input[i] = nextLong();
}
return input;
}
}
class FastOutput extends PrintWriter {
FastOutput() {
super(new BufferedOutputStream(System.out));
}
public void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
}
}
| JAVA |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | def convert(arr):
return ['1' if i=='0' else '0' for i in arr]
def solve2(arr):
#since we are changing `0`s, to `1`s
answer = []
#first change `0`s in pair
i = 0
while i<len(arr)-1:
if arr[i]=='0' and arr[i+1]=='0':
arr[i] = '1'
arr[i+1] = '1'
answer.append(i)
i += 2
else:
i += 1
## print(answer)
## print(arr)
#now we have to change the one's that are left that are individual
# since number of zeroes left will even only, then again we will
# have to pair these together
indices = []
for i in range(len(arr)):
if arr[i]=='0':
indices.append(i)
#agar 2 pair ban gaye hai to answer to jod do
if len(indices)==2:
answer.extend(list(range(indices[0], indices[1])))
indices = []
return answer
n = int(input())
arr = []
cnt0, cnt1= 0, 0
for i in input().strip():
arr.append('1') if i=='B' else arr.append('0')
if arr[-1]=='1':
cnt1 += 1
else:
cnt0 += 1
##print(arr)
##print(cnt0, cnt1)
if cnt1%2!=0 and cnt0%2!=0:
print(-1)
else:
answer = []
if cnt1%2==0 and cnt0%2==0:
#both are even in number
#`0` ko he convert karna hai to usse chota bana denge
if cnt0>=cnt1:
arr = convert(arr)
cnt0, cnt1 = cnt1, cnt0
else:
#any one of them has odd frequency and one has even
# we will have to change the one which has even frequencey
# we will always change `0` to `1`s for the sake of simplicity
if cnt0%2!=0:
arr = convert(arr)
#we will also have to swap, since we are converting `0`s so cnt0 should be even
cnt0, cnt1 = cnt1, cnt0
answer = solve2(arr)
answer = [i+1 for i in answer]
print(len(answer))
if len(answer)!=0:
print(*answer)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
n=int(input())
string1=[k for k in input()]
#something about the parity and the length of the parity of the array
white=0
black=0
for s in range(len(string1)):
if string1[s]=="W":
white+=1
else:
black+=1
if white==0 or black==0:
print(0)
else:
moves=0
outy=[]
for s in range(n-1,0,-1):
val1=string1[s]
if val1=="B":
if string1[s-1]=="B":
string1[s],string1[s-1]="W","W"
elif string1[s-1]=="W":
string1[s],string1[s-1]="W","B"
moves+=1
outy.append(str(s))
#then we check if they have same parity
w1=0
b1=0
for s in range(n):
if string1[s]=="W":
w1+=1
else:
b1+=1
if w1%2==0 or b1%2==0:
if w1>0 and b1>0:
for s in range(n-1,0,-1):
leftbord=string1[s-1]
if string1[s]=="W":
if leftbord=="W":
string1[s],string1[s-1]="B","B"
moves+=1
outy.append(str(s))
print(moves)
print(" ".join(outy))
else:
print(moves)
print(" ".join(outy))
else:
print(-1) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n = int(input())
s = input()
def function(s):
if len(s)%2 == 0:
count =0
for elements in s:
if elements == "B":
count+=1
else:
continue
if count%2 == 0:
array_steps = []
selection = False
selected = " "
previous = 0
change = 0
i = 2
for letters in s :
if not selection :
selection = True
selected = letters
continue
if previous == 0:
if letters != selected:
array_steps.append(i)
change = 1
previous = letters
i+=1
continue
if change ==1 :
if letters == selected:
array_steps.append(i)
else:
change = 0
i+=1
else:
if letters != selected:
array_steps.append(i)
change = 1
i+=1
return array_steps
else:
return -1
else:
array_steps = []
count = 0
for elements in s:
if elements == "B":
count += 1
else:
continue
if count%2 == 0:
selected = "W"
change = 0
i = 1
for letters in s:
if change == 0:
if letters == selected:
i +=1
else:
array_steps.append(i)
i+=1
change = 1
else:
if letters == selected:
array_steps.append(i)
i+=1
else:
i+=1
change =0
else:
selected = "B"
change = 0
i = 1
for letters in s:
if change == 0:
if letters == selected:
i += 1
else:
array_steps.append(i)
i += 1
change = 1
else:
if letters == selected:
array_steps.append(i)
i += 1
else:
i += 1
change = 0
return array_steps
if function(s) == -1:
print(-1)
else:
print(len(function(s)))
answer = ""
for elements in function(s):
answer += str(elements) + " "
print(answer)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | import sys
n = int(input())
s = list(input())
s2 = s.copy()
ans = []
for i in range(n-1):
if s[i] == 'B':
ans.append(i+1)
if s[i+1] == 'B':
s[i+1] = 'W'
else:
s[i+1] = 'B'
if s[n-1] == 'W':
print(len(ans))
print(" ".join(map(str, ans)))
sys.exit()
ans = []
for i in range(n-1):
if s2[i] == 'W':
ans.append(i+1)
if s2[i+1] == 'B':
s2[i+1] = 'W'
else:
s2[i+1] = 'B'
if s2[n-1] == 'B':
print(len(ans))
print(" ".join(map(str, ans)))
sys.exit()
print("-1")
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> ans;
char s[100001];
int main() {
int n;
scanf("%d %s", &n, s);
for (int i = 0; i < n - 1; ++i) {
if (s[i] == 'W') {
s[i] = 'B';
s[i + 1] = (s[i + 1] == 'W') ? 'B' : 'W';
ans.push_back(i + 1);
}
}
if (s[n - 1] == 'B') {
printf("%d\n", ans.size());
for (int i = 0; i < ans.size(); ++i)
printf("%d%s", ans[i], (i == ans.size() - 1) ? "\n" : " ");
return 0;
}
for (int i = 0; i < n - 1; ++i) {
if (s[i] == 'B') {
s[i] = 'W';
s[i + 1] = (s[i + 1] == 'W') ? 'B' : 'W';
ans.push_back(i + 1);
}
}
if (s[n - 1] == 'W') {
printf("%d\n", ans.size());
for (int i = 0; i < ans.size(); ++i)
printf("%d%s", ans[i], (i == ans.size() - 1) ? "\n" : " ");
return 0;
}
printf("-1\n");
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n = int(input())
s = list(input())
arr = []
for i in s:
if i == 'B':
arr.append(1)
else:
arr.append(0)
toMake = arr[0]
count = 0
affected = []
for i in range(1, len(arr)-1):
if arr[i] != toMake:
arr[i] = 1 - arr[i]
arr[i+1] = 1 - arr[i+1]
affected.append(i+1)
count += 1
if arr.count(toMake) == len(arr):
print(count)
print(*affected)
else:
toMake = 1 - toMake
for i in range(len(arr)-1):
if arr[i] != toMake:
arr[i] = 1 - arr[i]
arr[i+1] = 1 - arr[i+1]
affected.append(i+1)
count += 1
if arr.count(toMake) == len(arr):
print(count)
print(*affected)
else:
print(-1) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | from collections import Counter
_ =int(input())
s = list(input())
counter = Counter(s)
bs, ws = counter['B'], counter['W']
if bs%2!=0 and ws%2!=0:
print(-1)
else:
c = 'W' if ws%2==0 else 'B'
ops= []
i = 0
while i <len(s)-1:
if s[i] == c:
if s[i+1] != c:
s[i], s[i+1] = s[i+1], s[i]
ops.append(i+1)
else:
ops.append(i+1)
i+=1
i+=1
print(len(ops))
if len(ops):
print(*ops) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | import java.util.*;
import java.io.*;
public class B {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
PrintWriter pw = new PrintWriter(System.out);
int[] q = new int[2];
char[] s = sc.next().toCharArray();
int[] in = new int[n];
for(int i = 0; i < n; i++) {
in[i] = s[i] == 'B' ? 0: 1;
}
for(int k: in) q[k]++;
if((q[0] + n) % 2 == 0) {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> res = new ArrayList<>();
for(int i = 0; i < n-1; i++) {
if(in[i] != 0) {
in[i] = 0;
in[i+1] = 1-in[i+1];
res.add(i+1);
}
}
for(int k: res) sb.append(k+" ");
pw.write(res.size()+"\n");
pw.write(sb.toString().trim()+"\n");
}
else if((q[1] + n) % 2 == 0) {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> res = new ArrayList<>();
for(int i = 0; i < n-1; i++) {
if(in[i] != 1) {
in[i] = 1;
in[i+1] = 1-in[i+1];
res.add(i+1);
}
}
for(int k: res) sb.append(k+" ");
pw.write(res.size()+"\n");
pw.write(sb.toString().trim()+"\n");
}
else {
pw.write("-1\n");
}
pw.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| JAVA |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char[] s = in.next().toCharArray();
char[] c = s.clone();
ArrayList<Integer>id1 = new ArrayList<>();
ArrayList<Integer>id2 = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
if(s[i] == 'W'){
s[i] = 'B';
s[i+1] = s[i+1] == 'W' ? 'B' : 'W';
id1.add(i);
}
}
boolean cn = true;
for (int i = 0; i < n; i++) {
if(s[i] != 'B')cn = false;
}
if(cn){
out.println(id1.size());
for(int id : id1)out.print(id+1+ " ");
out.close();
return;
}
for (int i = 0; i < n - 1; i++) {
if(c[i] == 'B'){
c[i] = 'W';
c[i+1] = c[i+1] == 'B' ? 'W' : 'B';
id2.add(i);
}
}
cn = true;
for (int i = 0; i < n; i++) {
if(c[i] != 'W')cn = false;
}
if(cn){
out.println(id2.size());
for(int id : id2)out.print(id+1+ " ");
out.close();
return;
}
out.println(-1);
out.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
}
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
} | JAVA |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int len,len1,flag=0,sum[]=new int[606],k;
int b=0,w=0;
k=0;
len=sc.nextInt();
char str[]=sc.next().toCharArray();
for(int i=0;i<str.length;i++)
{
if(str[i]=='W')
w++;
if(str[i]=='B')
b++;
}
if(w==0||b==0)
{
System.out.println(0);
return ;
}
if(w%2==1&&b%2==1)
{
System.out.println(-1);
return ;
}
if(w%2==0)
{
while(flag==0)
{
for(int i=0;i<str.length;i++)
{
if(str[i]=='W')
{
flag=0;
str[i]='B';
if(str[i+1]=='W')
str[i+1]='B';
else
str[i+1]='W';
sum[k++]=i+1;
break;
}
flag=1;
}
}
System.out.println(k);
for(int i=0;i<k;i++)
{
System.out.print(sum[i]+" ");
}
System.out.println();
}else if(b%2==0)
{
while(flag==0)
{
for(int i=0;i<str.length;i++)
{
if(str[i]=='B')
{
flag=0;
str[i]='W';
if(str[i+1]=='W')
str[i+1]='B';
else
str[i+1]='W';
sum[k++]=i+1;
break;
}else
flag=1;
}
}
System.out.println(k);
for(int i=0;i<k;i++)
{
System.out.print(sum[i]+" ");
}
System.out.println();
}
}
}
| JAVA |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> v;
int numOfBlocks, j;
string block;
void invert(char s) {
for (int i = 0; i < numOfBlocks; i++) {
if (block[i] == s) {
j = i + 1;
while (block[j] != s) {
v.push_back(j);
block[j - 1] = block[j - 1] == 'B' ? 'W' : 'B';
block[j] = block[j] == 'B' ? 'W' : 'B';
j++;
}
v.push_back(j);
block[j - 1] = block[j - 1] == 'B' ? 'W' : 'B';
block[j] = block[j] == 'B' ? 'W' : 'B';
}
}
}
int main() {
int white = 0, black = 0;
cin >> numOfBlocks >> block;
for (int i = 0; i < numOfBlocks; i++) {
if (block[i] == 'W')
white++;
else
black++;
}
if (white == 0 || black == 0) {
cout << 0;
return 0;
}
if (white % 2 == 0 || black % 2 == 0) {
if (black % 2 != 0)
invert('W');
else
invert('B');
cout << v.size() << "\n";
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
} else {
cout << -1;
}
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
int va = 10e8 + 7;
long long val[200007] = {0};
using namespace std;
long long getmul(long long n) {
long long int k{0};
while (n > 0) {
k += n % 10;
n = n / 10;
}
return k;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t{1};
while (t--) {
int n;
cin >> n;
string s, k;
cin >> s;
k = s;
vector<int> ans;
for (int i = 0; i + 1 < n; i++) {
if (s[i] == 'B') {
ans.push_back(i + 1);
s[i] = 'W';
s[i + 1] = (s[i + 1] == 'W' ? 'B' : 'W');
}
}
if (s[n - 1] == 'W') {
cout << ((int)(ans).size()) << " ";
for (auto i : ans) cout << i << " ";
cout << "\n";
} else {
ans.clear();
for (int i = 0; i + 1 < n; i++) {
if (k[i] == 'W') {
ans.push_back(i + 1);
k[i] = 'B';
k[i + 1] = (k[i + 1] == 'W' ? 'B' : 'W');
}
}
if (k[n - 1] == 'B') {
cout << ((int)(ans).size()) << " ";
for (auto i : ans) cout << i << " ";
cout << "\n";
} else
cout << "-1"
<< "\n";
}
}
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | # ":"
n = int(input())
s = input()
lis = [i for i in s]
# all black
che_black = ["B"]*n
ans = []
for i in range(n-1):
if lis[i] == "W":
ans.append(i+1)
lis[i] = "B"
if lis[i+1] == "W":
lis[i+1] = "B"
else:
lis[i+1] = "W"
if lis == che_black:
print(len(ans))
print(*ans)
else:
# all white
lis = [i for i in s]
che_white = ["W"] * n
ans = []
for i in range(n - 1):
if lis[i] == "B":
ans.append(i+1)
lis[i] = "W"
if lis[i + 1] == "W":
lis[i + 1] = "B"
else:
lis[i + 1] = "W"
if lis == che_white:
print(len(ans))
print(*ans)
else:
print(-1)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 |
n = int(input())
s = input()
from collections import Counter
c = Counter(s)
if ((c["B"]%2==1 and c["W"] > 0) or (c["B"] > 0 and c["W"]%2==1)) and len(s)%2==0:
print(-1)
else:
s = list(s)
scopy = s[:]
targ = s[0]
d = {"W":"B", "B":"W"}
c = 0
ans = []
while len(set(s))!=1:
#print(s)
for i in range(len(s)-1):
if s[i]!=targ:
ans.append(i+1)
s[i], s[i+1] = targ, d[s[i+1]]
break
c += 1
if c > 3*len(s):
c = 0
targ = d[targ]
s = scopy[:]
ans = []
continue
print(c)
print(" ".join(list(map(str,ans)))) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | def solve1(str,c,d):
nw=str[0]
ans=[]
pos=0
for i in (str[1:]):
pos+=1
if(nw==d):
ans.append(pos)
nw=i
if(i==d):
nw=c
else:
nw=d
else:
nw=i
if(nw==c):
print(len(ans))
for i in ans:
print(i,end=' ')
print("")
return 1
n=input()
s=input()
if(solve1(s,'B','W')==1):
1
elif (solve1(s,'W','B')==1):
1
else:
print(-1) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | n=int(input())
b=input()
a=[]
for i in b:
a.append(i)
wn=a.count('W')
bn=a.count('B')
if wn==0 or bn==0:
print(0)
elif wn%2!=0 and bn%2!=0:
print(-1)
else:
c='-'
count=0
ans=[]
if wn%2==0:
c='W'
else:
c='B'
for i in range(n-1):
if a[i]==c:
if a[i]=='B':
a[i]='W'
else:
a[i]='B'
if a[i+1]=='B':
a[i+1]='W'
else:
a[i+1]='B'
count+=1
ans.append(i+1)
print(count)
print(*ans)
| PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, a, b, c, d, e, t, max_cost, ans = 0;
string s;
string original;
cin >> n;
if (n == 0) {
cout << "0";
return 0;
}
cin >> s;
original = s;
int arr[n];
int j = 0, f = 0;
for (long long int i = 0; i < n; i++) {
arr[i] = -1;
if (s[i] != 'B') {
f = 1;
}
}
if (f == 0) {
cout << "0";
return 0;
}
for (long long int i = 0; i < n - 1; i++) {
if (s[i] == 'B') {
s[i] = 'W';
arr[j] = i + 1;
j++;
if (s[i + 1] == 'B')
s[i + 1] = 'W';
else
s[i + 1] = 'B';
ans++;
}
}
if (s[n - 1] != 'B') {
cout << ans << endl;
int k = 0;
while (arr[k] != -1) {
cout << arr[k] << " ";
k++;
}
return 0;
}
if (s[n - 1] == 'B') {
ans = 0;
for (long long int i = 0; i < n; i++) {
arr[i] = -1;
}
j = 0;
for (long long int i = 0; i < n - 1; i++) {
if (original[i] == 'W') {
original[i] = 'B';
arr[j] = i + 1;
j++;
if (original[i + 1] == 'W')
original[i + 1] = 'B';
else
original[i + 1] = 'W';
ans++;
}
}
}
if (original[n - 1] == 'W')
cout << "-1";
else {
cout << ans << endl;
int k = 0;
while (arr[k] != -1) {
cout << arr[k] << " ";
k++;
}
}
return 0;
}
| CPP |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | N = int(input())
S = input()
black = []
white = []
for i, s in enumerate(S, 1):
if s == "B":
black.append(i)
elif s == "W":
white.append(i)
black_num = len(black)
white_num = len(white)
if black_num == 0 or white_num == 0:
print(0)
exit()
if black_num % 2 == 1 and white_num % 2 == 1:
print(-1)
exit()
if white_num % 2 == 0:
adopt = white
elif black_num % 2 == 0:
adopt = black
process = []
for i in range(0, len(adopt)-1, 2):
process += list(range(adopt[i], adopt[i+1])[::-1])
print(len(process))
print(*process) | PYTHON3 |
1271_B. Blocks | There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
void speed() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
const long long N = 1e5 + 5;
const long long NN = 105;
const long long MAX = 2e5 + 123;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
vector<pair<long long, long long> > vb, vw;
void hajime() {
string s;
long long n, cnt = 0;
cin >> n >> s;
string b = s;
string w = s;
for (long long i = 0; i < b.size(); i++) {
if (b[i] == 'W' && i != b.size() - 1) {
b[i] = 'B';
if (b[i + 1] == 'W')
b[i + 1] = 'B';
else
b[i + 1] = 'W';
cnt++;
vb.push_back(make_pair(i + 1, i + 2));
}
}
if (b[b.size() - 1] == b[b.size() - 2]) {
cout << cnt << '\n';
for (long long i = 0; i < vb.size(); i++) cout << vb[i].first << ' ';
return;
}
cnt = 0;
for (long long i = 0; i < w.size(); i++) {
if (w[i] == 'B' && i != w.size() - 1) {
w[i] = 'W';
if (w[i + 1] == 'B')
w[i + 1] = 'W';
else
w[i + 1] = 'B';
cnt++;
vw.push_back(make_pair(i + 1, i + 2));
}
}
if (w[w.size() - 1] == w[w.size() - 2]) {
cout << cnt << '\n';
for (long long i = 0; i < vw.size(); i++) cout << vw[i].first << ' ';
return;
} else
cout << -1;
}
int main() {
long long miyagi = 1;
speed();
while (miyagi--) hajime();
}
| CPP |
Subsets and Splits