0% found this document useful (0 votes)
66 views18 pages

Binary Search

The document describes a problem where the user wants to spam emotes in the form of an emote triangle of size k on a chat channel. The auto moderator will ban the user if they send more than x emotes in succession. The task is to determine how many messages the user can send before getting banned for different values of k and x. Sample test cases are provided to demonstrate the approach of calculating the cumulative emotes sent at each step and checking if it exceeds the ban limit x.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views18 pages

Binary Search

The document describes a problem where the user wants to spam emotes in the form of an emote triangle of size k on a chat channel. The auto moderator will ban the user if they send more than x emotes in succession. The task is to determine how many messages the user can send before getting banned for different values of k and x. Sample test cases are provided to demonstrate the approach of calculating the cumulative emotes sent at each step and checking if it exceeds the ban limit x.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

EDU-114  

  Apr 02, 2023

Problem C. Slay the Dragon


Time limit 2000 ms
Mem limit 262144 kB

Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player
will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To
do this, the player has a squad of n heroes, the strength of the i-th hero is equal to ai . ​

According to the rules of the game, exactly one hero should go kill the dragon, all the others will
defend the castle. If the dragon's defense is equal to x, then you have to send a hero with a
strength of at least x to kill it. If the dragon's attack power is y , then the total strength of the
heroes defending the castle should be at least y .

The player can increase the strength of any hero by 1 for one gold coin. This operation can be
done any number of times.

There are m dragons in the game, the i-th of them has defense equal to xi and attack power equal

to yi . Petya was wondering what is the minimum number of coins he needs to spend to defeat the

i-th dragon.

Note that the task is solved independently for each dragon (improvements are not saved).

Input

The first line contains a single integer n (2 ≤ n ≤ 2 ⋅ 105 ) — number of heroes.

The second line contains n integers a1 , a2 , … , an (1


​ ​ ​ ≤ ai ≤ 1012 ), where ai is the strength of
​ ​

the i-th hero.

The third line contains a single integer m (1 ≤ m ≤ 2 ⋅ 105 ) — the number of dragons.

The next m lines contain two integers each, xi and yi (1


​ ​ ≤ xi ≤ 1012 ; 1 ≤ yi ≤ 1018 ) — defense
​ ​

and attack power of the i-th dragon.

Output

Print m lines, i-th of which contains a single integer — the minimum number of coins that
should be spent to defeat the i-th dragon.

Sample 1

-
EDU-114    Apr 02, 2023

Input Output

4 1
3 6 2 3 2
5 4
3 12 0
7 9 2
4 14
1 10
8 7

Note

To defeat the first dragon, you can increase the strength of the third hero by 1, then the strength
of the heroes will be equal to [3, 6, 3, 3]. To kill the dragon, you can choose the first hero.

To defeat the second dragon, you can increase the forces of the second and third heroes by 1,
then the strength of the heroes will be equal to [3, 7, 3, 3]. To kill the dragon, you can choose a
second hero.

To defeat the third dragon, you can increase the strength of all the heroes by 1, then the strength
of the heroes will be equal to [4, 7, 3, 4]. To kill the dragon, you can choose a fourth hero.

To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill
the dragon.

To defeat the fifth dragon, you can increase the strength of the second hero by 2, then the
strength of the heroes will be equal to [3, 8, 2, 3]. To kill the dragon, you can choose a second
hero.

-
#include <bits/stdc++.h>
using namespace std;
/*Vocabulary
slay-> matar
defeat-> vencer
squad-> equipo
*/
#define debug(x) cout << #x << " = " << x << endl
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
#define pb push_back
#define mp make_pair
#define all(v) sort(v.begin(),v.end())
#define sz(v) int(v.size())
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int MAXN=1e5+5;
const int inf=1e9;
const long long mod=1e9+7;
vector<int> g[MAXN] ;
bool used[MAXN];
vector<int> comp ;
#define yes cout<<"YES\n";
#define no cout<<"NO\n";
const double PI = acos(-1);
/*Ideas que solucionan el Problema

*/

int main() {
fastio;
int n;
cin >> n;
vector<ll> a(n);
for (auto &x : a) cin >> x;
sort(a.begin(), a.end());
ll sum = accumulate(a.begin(), a.end(), 0LL);
int m;
cin >> m;
while (m--) {
ll x, y;
cin >> x >> y;//x defensa del dragon, y es el attack
int i = lower_bound(a.begin(), a.end(), x) - a.begin();
//i es el índice del primer elemento no menor a X
ll ans = 2e18;
if (i > 0) ans = min(ans, (x - a[i - 1]) + max(0LL, y - sum + a[i - 1]));
//la parte del max es la fuerza que voy a comprar para que resista el
//ataque y del dragón
//(x - a[i - 1]) esta parte son los coins que necesitar para matar al dragón
if (i < n) ans = min(ans, max(0LL, y - sum + a[i]));//son los coins que necesitas
//para resistir el ataque y del dragón, como usas el a[i] para atacar entonces
//ya sabes que si lo vas a vencer.
cout << ans << '\n';
}
}
/*Errores que Cometí

*/
EDU-117    Apr 02, 2023

Problem C. Chat Ban


Time limit 2000 ms
Mem limit 524288 kB

You are a usual chat user on the most famous streaming platform. Of course, there are some
moments when you just want to chill and spam something.

More precisely, you want to spam the emote triangle of size k. It consists of 2k − 1 messages.
The first message consists of one emote, the second one — of two emotes, ..., the k-th one — of
k emotes, the k + 1-th one — of k − 1 emotes, ..., and the last one — of one emote.

For example, the emote triangle for k = 3 consists of 5 messages:

Of course, most of the channels have auto moderation. Auto moderator of the current chat will
ban you right after you spam at least x emotes in succession (you can assume you are the only
user in the chat). Now you are interested — how many messages will you write before getting
banned? Or maybe you will not get banned at all (i.e. will write all 2k − 1 messages and complete
your emote triangle successfully)? Note that if you get banned as a result of writing a message,
this message is also counted.

You have to answer t independent test cases.

Input

The first line of the input contains one integer t (1 ≤ t ≤ 104 ) — the number of test cases. The
next t lines describe test cases.

The only line of the test case contains integers k and x (1 ≤ k ≤ 109 ; 1 ≤ x ≤ 1018 ).

Output

For each test case, print the number of messages you will write before getting banned for the
corresponding values k and x.

-
EDU-117    Apr 02, 2023
Sample 1
Input Output

7 3
4 6 4
4 7 1
1 2 4
3 7 3
2 5 1
100 1 1608737403
1000000000 923456789987654321

Note

Let's analyze the test cases of the example.

1. In the first test case, you write three messages containing 1, 2 and 3 emotes respectively,
and since 1 + 2 + 3 ≥ 6, you get banned after that.
2. In the second test case, you write four messages containing 1, 2, 3 and 4 emotes
respectively, and since 1 + 2 + 3 + 4 ≥ 7, you get banned after that.
3. In the third test case, you write one message containing exactly 1 emote. It doesn't get you
banned, since 1 < 2, but you have already finished posting your emote triangle. So you
wrote one message successfully.
4. In the fourth test case, you write four messages containing 1, 2, 3 and 2 emotes
respectively, and since 1 + 2 + 3 + 2 ≥ 7, you get banned after that.
5. In the fifth test case, you write three messages containing 1, 2 and 1 emote respectively. It
doesn't get you banned, since 1 + 2 + 1 < 5, but you have already finished posting your
emote triangle. So you wrote three messages successfully.
6. In the sixth test case, since x = 1, you get banned as soon as you send your first message.
7. The seventh test case is too large to analyze, so we'll skip it.

-
/*Vocabulary
to chill-> relajarse
most of the channels-> mayoria de los canales
*/
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int mod=1e9+7;
const int inf=1e9;
const int N=2e5+10;
ll a[N];
ll get(int x) {
return x * 1ll * (x + 1) / 2;
}
int main() {
int t;
cin >> t;
while (t--) {
int k;
ll x;
cin >> k >> x;
/*Un triángulo de emotes de tamaño k tiene 2k-1 mensajes(filas de emotes)
x es la cantidad de emotes máximo que debería tener para que baneen*/
ll l = 1, r = 2 * k - 1;
ll res = 2 * k - 1;
bool over = false;
while (l <= r) {//búsqueda binaria
int mid = (l + r) >> 1;
if (mid > k) {
/*get(k) + get(k - 1) sumo todo los emotes y le resto un cachito de
abajo get(2 * k - 1 - mid)*/
ll val=get(k) + get(k - 1) - get(2 * k - 1 - mid);
over = (val>= x);
//cout<<l<<" "<<r<<" "<<mid<<" "<<val<<" "<<get(k)<<" "<<get(k-1)<<" "<<get(2
* k - 1 - mid)<<"\n";
//en ves de poner el if
}else{
ll val=get(mid);
over = (val>= x);
//cout<<l<<" "<<r<<" "<<mid<<" "<<val<<"\n";
}
//Busca el primero que cumpla la condición
if (over){
res = mid;//el mid más a la izquierda es el que nos sirve
//para solucionar el problema
r = mid - 1;//si over es verdadero quiere decir que
//el x que buscamos no esta a la derecha de mid(incluido este)
} else {
l = mid + 1;
}
}
cout << res << endl;
}
return 0;
}
EDU-118    Apr 02, 2023

Problem C. Poisoned Dagger


Time limit 2000 ms
Mem limit 262144 kB

Monocarp is playing yet another computer game. In this game, his character has to kill a dragon.
The battle with the dragon lasts 100500 seconds, during which Monocarp attacks the dragon with
a poisoned dagger. The i-th attack is performed at the beginning of the ai -th second from the

battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon,
which deals 1 damage during each of the next k seconds (starting with the same second when
the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then
the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).

For example, suppose k = 4, and Monocarp stabs the dragon during the seconds 2, 4 and 10.
Then the poison effect is applied at the start of the 2-nd second and deals 1 damage during the 2-
nd and 3-rd seconds; then, at the beginning of the 4-th second, the poison effect is reapplied, so
it deals exactly 1 damage during the seconds 4, 5, 6 and 7; then, during the 10-th second, the
poison effect is applied again, and it deals 1 damage during the seconds 10, 11, 12 and 13. In
total, the dragon receives 10 damage.

Monocarp knows that the dragon has h hit points, and if he deals at least h damage to the dragon
during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison
he will use during the battle, so he wants to find the minimum possible value of k (the number of
seconds the poison effect lasts) that is enough to deal at least h damage to the dragon.

Input

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.

The first line of the test case contains two integers n and h (1 ≤ n ≤ 100; 1 ≤ h ≤ 1018 ) — the
number of Monocarp's attacks and the amount of damage that needs to be dealt.

The second line contains n integers a1 , a2 , ..., an (1


​ ​ ​ ≤ ai ≤ 109 ; ai < ai+1 ), where ai is the
​ ​ ​ ​

second when the i-th attack is performed.

Output

For each test case, print a single integer — the minimum value of the parameter k, such that
Monocarp will cause at least h damage to the dragon.

Sample 1

-
EDU-118    Apr 02, 2023

Input Output

4 3
2 5 4
1 5 1
3 10 470
2 4 10
5 3
1 2 4 5 7
4 1000
3 25 64 1337

Note

In the first example, for k = 3, damage is dealt in seconds [1, 2, 3, 5, 6, 7].

In the second example, for k = 4, damage is dealt in seconds [2, 3, 4, 5, 6, 7, 10, 11, 12, 13].

In the third example, for k = 1, damage is dealt in seconds [1, 2, 4, 5, 7].

-
/*Vocabulary
deal damage-> inflingir daño
slay-> matar
stabbed-> apuñalado
be dealt->debe hacerse
*/
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using ii=pair<int, int>;
#define vi vector<int>
#define pb push_back
#define fast ios_base::sync_with_stdio(0);cin.tie(0);
#define f first
#define s second
const int mod=1e9+7;
const int inf=1e9;
const int N=2e5+10;
ll a[N];
/*Ideas que solucionan el Problema

*/
int main(){
fast
int t;
cin>>t;
while(t--){
ll n,h;
cin>>n>>h;
for(int i=0;i<n;i++){
cin>>a[i];
}

ll l = 1, r = 1e18;
while (l <= r) {//búsqueda binaria
ll m = (l + r) / 2;
//cout<<r-2<<"\n";
ll sum = m;//es el m del final
for (int i = 0; i < n - 1; ++i)
sum += min(m, a[i + 1] - a[i]);//va viendo cuanto
//de daño le hace al dragón para cada m

// cout<<l<<" "<<r<<" "<<sum<<" "<<h<<" "<<r+1<<"\n";


if (sum < h) l = m + 1;
else r = m - 1;

}
cout << r + 1 << '\n';

}
}
/*Errores que Cometí

*/
EDU-126    Apr 02, 2023

Problem C. Water the Trees


Time limit 3000 ms
Mem limit 262144 kB

There are n trees in a park, numbered from 1 to n. The initial height of the i-th tree is hi . ​

You want to water these trees, so they all grow to the same height.

The watering process goes as follows. You start watering trees at day 1. During the j -th day you
can:

Choose a tree and water it. If the day is odd (e.g. 1, 3, 5, 7, …), then the height of the tree
increases by 1. If the day is even (e.g. 2, 4, 6, 8, …), then the height of the tree increases by
2.
Or skip a day without watering any tree.

Note that you can't water more than one tree in a day.

Your task is to determine the minimum number of days required to water the trees so they grow
to the same height.

You have to answer t independent test cases.

Input

The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 104 ) — the number of test cases.

The first line of the test case contains one integer n (1 ≤ n ≤ 3 ⋅ 105 ) — the number of trees.

The second line of the test case contains n integers h1 , h2 , … , hn (1


​ ​ ​ ≤ hi ≤ 109 ), where hi is the
​ ​

height of the i-th tree.

It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 105 (∑ n ≤ 3 ⋅ 105 ).

Output

For each test case, print one integer — the minimum number of days required to water the trees,
so they grow to the same height.

Sample 1

-
EDU-126    Apr 02, 2023

Input Output

3 4
3 3
1 2 4 16
5
4 4 3 5 5
7
2 5 4 8 3 7 4

Note

Consider the first test case of the example. The initial state of the trees is [1, 2, 4].

1. During the first day, let's water the first tree, so the sequence of heights becomes [2, 2, 4];
2. during the second day, let's water the second tree, so the sequence of heights becomes
[2, 4, 4];
3. let's skip the third day;
4. during the fourth day, let's water the first tree, so the sequence of heights becomes [4, 4, 4].

Thus, the answer is 4.

-
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using ii=pair<int, int>;
#define all(c) (c).begin(), (c).end()
#define vi vector<int>
const int mod=1e9+7;
const int inf=1e9;
const int N=2e5+10;
ll h[N];
/*Ideas que solucionan el Problema
Buscamos los mínimos valores de días impares y pares(uno más que los días impares)
para que cumplan la condición de tener todas las plantas del mismo máximo tamaño
*/
int n; vi a;
ll solve(ll add) {
ll cnt1 = 0, cnt2 = 0;
for(int i = 0; i < n; i++) {
int x = a[n-1]+add-a[i];
cnt1 += (x&1);//saca el resto de dividir entre 2, con esta cantidad puede convertir
//a todos los valores impares en pares
cnt2 += x >> 1;//divide entre 2, con esta cantidad lleva a todas las cantidades
//pares a la cantidad máxima deseada
}
ll l = 0, r = (ll) 1e16;
while(l < r) {
ll m = (l+r) >> 1;
bool cmp = 0;
ll even = m >> 1;//la cantidad de veces que se incrementa en 2 es
ll odd = m-even;//igual o inferior en 1 a la cantidad de veces que se
//incrementa 1
if(even >= cnt2 and odd >= cnt1)//quiere decir que hay suficiente tiempo
cmp = 1;//razón por el cuál se seguirá iterando viendo la parte izquierda
//en la búsqueda binaria
if(even < cnt2) {//
ll need = cnt2-even;//esta es la cantidad que se va usar de los días impares
if(cnt1 + 2 * need <= odd)//como hay suficientes días impares, se seguirá iterando
cmp = 1;//viendo la parte izquierda en caso se cumpla la condición
}
if(cmp) r = m;
else l = m+1;
}
return l;
}
int main() {
#define fast ios_base::sync_with_stdio(0);cin.tie(0);
int t; cin >> t;
while(t--) {
cin >> n;
a.clear(); a.resize(n);
for(int i = 0; i < n; i++) cin >> a[i];
sort(all(a));
cout << min(solve(0), solve(1)) << "\n";
}
return 0;
}
 
EDU-131    Apr 02, 2023

Problem C. Schedule Management


Time limit 2000 ms
Mem limit 262144 kB

There are n workers and m tasks. The workers are numbered from 1 to n. Each task i has a value
ai — the index of worker who is proficient in this task.

Every task should have a worker assigned to it. If a worker is proficient in the task, they
complete it in 1 hour. Otherwise, it takes them 2 hours.

The workers work in parallel, independently of each other. Each worker can only work on one
task at once.

Assign the workers to all tasks in such a way that the tasks are completed as early as possible.
The work starts at time 0. What's the minimum time all tasks can be completed by?

Input

The first line contains a single integer t (1 ≤ t ≤ 104 ) — the number of testcases.

The first line of each testcase contains two integers n and m (1 ≤ n ≤ m ≤ 2 ⋅ 105 ) — the
number of workers and the number of tasks.

The second line contains m integers a1 , a2 , … , am (1


​ ​ ​ ≤ ai ≤ n) — the index of the worker

proficient in the i-th task.

The sum of m over all testcases doesn't exceed 2 ⋅ 105 .

Output

For each testcase, print a single integer — the minimum time all tasks can be completed by.

Sample 1
Input Output

4 2
2 4 3
1 2 1 2 1
2 4 1
1 1 1 1
5 5
5 1 3 2 4
1 1
1

Note

-
EDU-131    Apr 02, 2023
In the first testcase, the first worker works on tasks 1 and 3, and the second worker works on
tasks 2 and 4. Since they both are proficient in the corresponding tasks, they take 1 hour on each.
Both of them complete 2 tasks in 2 hours. Thus, all tasks are completed by 2 hours.

In the second testcase, it's optimal to assign the first worker to tasks 1, 2 and 3 and the second
worker to task 4. The first worker spends 3 hours, the second worker spends 2 hours (since they
are not proficient in the taken task).

In the third example, each worker can be assigned to the task they are proficient at. Thus, each of
them complete their task in 1 hour.

-
/*Vocabulary
took-> tomó
Worst case-> en el peor de los casos
proficient-> competente
*/
#include<bits/stdc++.h>
using namespace std;
/*Ideas que ayudan
Definir variables que nos ayuden a resolver el problema, si esta
variable esta ordenado(podría usarse búsqueda binaria)

Ver los extremos de las variables


*/
#define ll long long
int n,m,a,b[200005],t;
int main(){
cin>>t;
while(t--){
memset(b,0,sizeof(b));
cin>>n>>m;
for(int i=1;i<=m;i++) cin>>a,b[a]++;
//b[i] nos dice en cuantas tareas es competentbe un worker i
int mid,l=1,r=2*m;//2*m es la cantidad máxima de tiempo que va a demorar

while(l<=r){
mid=(l+r)>>1;
ll q=0;
for(int i=1;i<=n;i++){//mira la contribucion de cada worker
if(b[i]<mid) q+=b[i]+(mid-b[i])/2;//es /2 ya que
//en estas tareas no es competente

//q es la cantidad de tareas realizada por el worker i en el tiempo mid


else q+=mid;
//si la cantidad de tiempo a usar(mid) es menor o igual a b[i],
//entonces se usa todo este(1 hora realizar cada tarea)
}
if(q<m) l=mid+1;
else r=mid-1;
}
cout<<l<<endl;
}
}
/*Errores que Cometí
f
*/
EDU-134    Apr 02, 2023

Problem C. Min-Max Array Transformation


Time limit 2000 ms
Mem limit 262144 kB

You are given an array a1 , a2 , … , an , which is sorted in non-descending order. You decided to
​ ​ ​

perform the following steps to create array b1 , b2 , … , bn : ​ ​ ​

1. Create an array d consisting of n arbitrary non-negative integers.


2. Set bi= ai + di for each bi.
​ ​ ​ ​

3. Sort the array b in non-descending order.

You are given the resulting array b. For each index i, calculate what is the minimum and
maximum possible value of di you can choose in order to get the given array b.

Note that the minimum (maximum) di -s are independent of each other, i. e. they can be obtained

from different possible arrays d.

Input

The first line contains the single integer t (1 ≤ t ≤ 104 ) — the number of test cases.

The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 105 ) — the length of
arrays a, b and d.

The second line contains n integers a1 , a2 , … , an (1 ​ ​ ​ ≤ ai ≤ 109 ; ai ≤ ai+1 ) — the array a in
​ ​ ​

non-descending order.

The third line contains n integers b1 , b2 , … , bn (1


​ ​ ​ ≤ bi ≤ 109 ; bi ≤ bi+1 ) — the array b in non-
​ ​ ​

descending order.

Additional constraints on the input:

there is at least one way to obtain the array b from the a by choosing an array d consisting
of non-negative integers;
the sum of n doesn't exceed 2 ⋅ 105 .

Output

1 , d2 , … , dn , where
For each test case, print two lines. In the first line, print n integers dmin min min
​ ​ ​

dmin
i ​is the minimum possible value you can add to ai .

-
EDU-134    Apr 02, 2023
Secondly, print n integers dmax
1 , dmax
2 , … , dmax
​ ​
max
n , where di ​is the maximum possible value you

can add to ai . ​

All dmin
i ​and dmax
i values are independent of each other. In other words, for each i, dmin

i is just the

minimum value among all possible values of di . ​

Sample 1
Input Output

4 5 4 2
3 11 10 8
2 3 5 4000
7 11 13 4000
1 0 0 0 0
1000 0 0 0 0
5000 12 2 3 15
4 23 13 3 15
1 2 3 4
1 2 3 4
4
10 20 30 40
22 33 33 55

Note

1 = 5, we can choose, for example, d = [5, 10, 6]. Then b


In the first test case, in order to get dmin ​

= [2 + 5, 3 + 10, 5 + 6] = [7, 13, 11] = [7, 11, 13].

For dmin
2 ​ = 4, we can choose d = [9, 4, 8]. Then b = [2 + 9, 3 + 4, 5 + 8] = [11, 7, 13] = [7, 11, 13].

-
/*Resumen del Problema

*/
#include<bits/stdc++.h>
using namespace std;
int a[1000005],b[1000005],n;
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)cin>>b[i];
for(int i=0;i<n;i++)cout<<*lower_bound(b,b+n,a[i])-a[i]<<' ';
cout<<endl;
int ind=0;
for(int i=0;i<n;i++){
ind=max(ind,i);
while(ind<n-1&&a[ind+1]<=b[ind])ind++;
cout<<b[ind]-a[i]<<' ';
}
cout<<endl;
}
}
/*Errores que cometí

*/

You might also like