contest_id stringlengths 1 4 | index stringclasses 43
values | title stringlengths 2 63 | statement stringlengths 51 4.24k | tutorial stringlengths 19 20.4k | tags listlengths 0 11 | rating int64 800 3.5k ⌀ | code stringlengths 46 29.6k ⌀ |
|---|---|---|---|---|---|---|---|
468 | A | 24 Game | Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of $n$ integers: $1, 2, ..., n$. In a single step, you can pick two of them, let's denote them $a$ and $b$, erase them from the sequence, and append to the sequence either... | Solution 1: If $n \le 3$, it's easy to find that it's impossible to make $24$, because the maximal number they can form is $9$. If $n > 5$, we can simply add $n - (n - 1) = 1, 24 * 1 = 24$ at the end of the solution to the number $n - 2$. So we can find the solution of $4, 5$ by hand. $1 * 2 * 3 * 4 = 24, (5 - 3) * 4... | [
"constructive algorithms",
"greedy",
"math"
] | 1,500 | // Author: Ruchiose
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#define i64 long long
#define d64 long double
#define fortodo(i, f, t) for (i = f; i <= t; i++)
using namespace std;
bool posi[100010];
int main()
{
int N;
scanf("%d", &... |
468 | B | Two Sets | Little X has $n$ distinct integers: $p_{1}, p_{2}, ..., p_{n}$. He wants to divide all of them into two sets $A$ and $B$. The following two conditions must be satisfied:
- If number $x$ belongs to set $A$, then number $a - x$ must also belong to set $A$.
- If number $x$ belongs to set $B$, then number $b - x$ must als... | Solution 1: If we have number $x$ and $a - x$, they should be in the same set. If $x\in A$, it's obvious that $a-x\in A$. The contraposition of it is $a-x\not\in A\Rightarrow x\not\in A$, that means if $x\in B$, $a - x$ should in the set $B$. Same as the number $x, b - x$. So we can use Disjoint Set Union to merge the ... | [
"2-sat",
"dfs and similar",
"dsu",
"graph matchings",
"greedy"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
const int N=101000;
map<int,int> hs;
int vis[N],way[N],A[N],B[N],p[N];
int n,a,b;
bool check0() {
rep(i,0,n) if (!hs.count(a-p[i])) return 0;
return 1;
}
void dfs(int u,int p,int s) {
vis[u]=1;
way[u]=s;
if (p==0) {
if (A[... |
468 | C | Hack it! | Little X has met the following problem recently.
Let's define $f(x)$ as the sum of digits in decimal representation of number $x$ (for example, $f(1234) = 1 + 2 + 3 + 4$). You are to calculate $\sum_{i=1}^{r}f(i)\,\bmod\,a.$
Of course Little X has solved this problem quickly, has locked it, and then has tried to hack... | Define $g(x)=\sum_{i=0}^{x-1}f(i)$. $\sum_{i=l}^{r}f(i)=g(r+1)-g(l)$, so we should find a pair of number $a, b$ that $g(a)\equiv g(b)(\mathrm{mod}\ a)$ Solution 1: First we choose $x$ randomly. Then we can use binary search to find the minimal $d$ that $g(x+d)-g(x)\geq a-g(x)\;\mathrm{mod}\;a$ . So $g(x+d){\mathrm{~mod... | [
"binary search",
"constructive algorithms",
"math"
] | 2,500 | m = int(input())
x,t=10**100-1,m-100*45*10**99%m
print(t,t+x)
|
468 | D | Tree | Little X has a tree consisting of $n$ nodes (they are numbered from $1$ to $n$). Each edge of the tree has a positive length. Let's define the distance between two nodes $v$ and $u$ (we'll denote it $d(v, u)$) as the sum of the lengths of edges in the shortest path between $v$ and $u$.
A permutation $p$ is a sequence ... | $d(u, v) = dep_{u} + dep_{v} - 2 * dep_{LCA(u, v)}$, so the answer is: $\textstyle{\sum_{i=1}^{n}d e p_{i}+d e p_{p_{i}}-2*d e p_{L C A(i,p_{i})}=2*\sum_{i=1}^{n}d e p_{i}-2*\sum_{i=1}^{n}d e p_{L C A(i,p_{i})}}$ $dep_{i}$ there means the distance between node $i$ and root. We choose centroid of tree as root (let's den... | [
"graph matchings"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define fi first
#define se second
typedef vector<int> VI;
typedef long long l... |
468 | E | Permanent | Little X has solved the #P-complete problem in polynomial time recently. So he gives this task to you.
There is a special $n × n$ matrix $A$, you should calculate its permanent modulo $1000000007 (10^{9} + 7)$. The special property of matrix $A$ is almost all its elements equal to $1$. Only $k$ elements have specified... | The permanent can be obtained as follows: for each $(e_{1}, e_{2}, ..., e_{t})$ such that $x_{1}, x_{e2}..., x_{et}$ are distinct and $y_{e1}, y_{e2}, ..., y_{et}$ are distinct, add $(n-t)!\prod_{i=1}^{t}(w_{e_{i}}-1)$ to the answer. It can be proved by the formula : ${\mathrm{perm}}(A+B)=\sum_{s,t}{\mathrm{perm}}(a_{i... | [
"dp",
"graph matchings",
"math",
"meet-in-the-middle"
] | 3,100 | null |
469 | A | I Wanna Be the Guy | There is a game called "I Wanna Be the Guy", consisting of $n$ levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only $p$ levels of the game. And Little Y can pass only $q$ levels of the game. You are given the indices of levels Little X can... | The problem itself is easy. Just check if all the levels could be passed by Little X or Little Y. | [
"greedy",
"implementation"
] | 800 | R=lambda:map(int,raw_input().split())[1:]
print ["Oh, my keyboard!","I become the guy."][input()==len(set(R()).union(set(R())))] |
469 | B | Chat Online | Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between $a_{1}$ and $b_{1}$, between $a_{2}$ and $b_{2}$, ..., between $a_{p}$ and $b_{p}$ (all borders inclusive). But the schedule of Little X is quite... | This problem is not hard. Just iterator over all possible $t$, and check if the schedule of Little X and Little Z will overlap. | [
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
const int N=110;
int p,q,l,r,ans,tl,tr;
int pool[10000],pa[10000],pb[10000],*vis=pool+5000,*a=pa+5000,*b=pb+5000;
int main() {
scanf("%d%d%d%d",&p,&q,&l,&r);
rep(i,0,p) {
scanf("%d%d",&tl,&tr);
rep(j,tl,tr) a[j]=1;
}
rep(i,0,... |
471 | A | MUH and Sticks | Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- ... | Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer "Alien" should be given only if we can't find four sticks for the legs. Otherwise we... | [
"implementation"
] | 1,100 | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> l(6);
for (int i = 0 ; i < 6 ; i++) cin >> l[i];
sort(l.begin(), l.end());
if (l[0] == l[3]) cout << (l[4] == l[5] ? "Elephant" : "Bear");
else if (l[1] == l[4]) cout << "Bear";
else if (l[2] == l[5... |
471 | B | MUH and Important Things | It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are $n$ tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in ord... | You need to check whether exist three pairwise different permutations of the indices of the input which result in array being sorted. Generally you can count the number of total permutation which give non-decreasing array. This number might be very large and it might easily overflow even long integer type. And what is ... | [
"implementation",
"sortings"
] | 1,300 | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void print(vector<pair<int, int> > &v) {
for (int i = 0 ; i < v.size() ; i++) cout << v[i].second << ' ';
cout << endl;
}
int main() {
int n;
cin >> n;
vector<pair<int, int> > input;
for (int i = 0 ; i < n ; i++) {
int x;
... |
471 | C | MUH and House of Cards | Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of $n$ playing cards. Let's describe the house they want to make:
- The house consists of some non-zero number of floors.
- Each floor ... | Card house. This problem required some maths, but just a little bit. So in order to start here let's first observe that the number of cards you need to use for a complete floor with $R$ rooms equals to: $C = C_{rooms} + C_{ceiling} = 2 \cdot R + (R - 1) = 3 \cdot R - 1$ Then if you have $F$ floors with $R_{i}$ rooms on... | [
"binary search",
"brute force",
"greedy",
"math"
] | 1,700 | #include "assert.h"
#include <iostream>
typedef long long int LL;
using namespace std;
LL getNumberOfCardsInFullHouse(LL floors) {
return 3 * floors * (floors + 1) / 2 - floors;
}
LL solve(LL n) {
LL res = 0;
for (LL floors = 1 ; getNumberOfCardsInFullHouse(floors) <= n ; floors++)
if ((n + floors) % ... |
471 | D | MUH and Cube Walls | Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of di... | In this problem we are given two arrays of integers and we need to find how many times we can see second array as a subarray in the first array if we can add some arbitrary constant value to every element of the second array. Let's call these arrays $a$ and $b$. As many people noticed or knew in advance this problem ca... | [
"string suffix structures",
"strings"
] | 1,800 | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int IntMinVal = (int) -1e20;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
/// compacts the array of arbitrary numbers into an array o... |
471 | E | MUH and Lots and Lots of Segments | Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of $n$ segments. Each segment was either horizontal or vertical. Now the ... | Given a set of horizontal/vertical lines you need to erase some parts of the lines or some lines completely in order to receive single connected drawing with no cycles. First of all let's go through naive $N^{2}$ solution which won't even remove cycles. In order to solve this problem you will need a DSU data structure,... | [
"data structures",
"dsu"
] | 2,700 | #include <algorithm>
#include "assert.h"
#include <deque>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <vector>
typedef long long LL;
#define all(v) v.begin(),v.end()
int IntMaxVal = (int) 1e20;
int IntMinVal = (int) -1e20;
#define FOR(i, a, b) for(int i = a; i < b ; ++i)
#define... |
472 | A | Design Tutorial: Learn from Math | One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | One way to solve this is by bruteforce: there are O(n) different ways to decomose n as sum of two number. If we can check if a number is a prime in O(1) then the whole algorithm can run in O(n). You can use Sieve of Eratosthenes to do the pre-calculation. And another way is try to prove this theorem. The prove is simpl... | [
"math",
"number theory"
] | 800 | null |
472 | B | Design Tutorial: Learn from Life | One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.
Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following... | This task can be solve by greedy: the k people with highest floor goes together, and next k people with highest floor goes together and so on. So the answer is 2 * ((f[n]-1) + (f[n-k]-1) + (f[n-2k]-1) + ...) . It is a bit tricky to prove the correctness of greedy, since people can get off the elevator and take it again... | [] | 1,300 | null |
472 | C | Design Tutorial: Make It Nondeterministic | A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.
Let's try to make a new task. Firstly we will use the following task. There are $n$ people, sort them by their name. It is just an ordi... | This one laso can be solved by greedy, let's think in this way: let pick one with smallest handle, then we let him/her use min(firstName, secondName) as handle. And go for the next one (2nd mallest handle), now he/she must choose a handle greater than handle of previous person, and if both meet this requirement, he/she... | [
"greedy"
] | 1,400 | null |
472 | D | Design Tutorial: Inverse the Problem | There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.
Now ... | Let's think it in the following way: for the minimal length edge, it must belong the the tree, ..., for the k-th minimal length edge(a, b), if there is already an path between a-b, then it can not be an edge of tree anymore, otherwise it must be edge of tree, why? Because otherwise there must be a path from a to b in t... | [
"dfs and similar",
"dsu",
"shortest paths",
"trees"
] | 1,900 | null |
472 | E | Design Tutorial: Learn from a Game | One way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task.
Let's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle.
\begin{center}
(Picture from Wikip... | First let's solve some special cases: If the initial board and the target board contains different orbs, then there can't be a solution. If n = 1 (or m = 1), then we can try all O(m^2) (or O(n^2)) possible moves. And for the other cases, there always have solution. We first hold the orb with number target[1][1] in init... | [
"constructive algorithms",
"implementation"
] | 2,800 | null |
472 | F | Design Tutorial: Change the Goal | There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.
Let's have a try. I have created the following task for Top... | You need to know some knowledge about linear algebra and notice the operation of xor on 32 bit integers equals to + operation in a 32 dimension linear space. If you don't know, you should learn it from the editorial of similar tasks, for example, Topcoder SRM 557 Div1-Hard. We need to know some basic properties of our ... | [
"constructive algorithms",
"math",
"matrices"
] | 2,700 | null |
472 | G | Design Tutorial: Increase the Constraints | There is a simple way to create hard tasks: take one simple problem as the query, and try to find an algorithm that can solve it faster than bruteforce. This kind of tasks usually appears in OI contest, and usually involves data structures.
Let's try to create a task, for example, we take the "Hamming distance problem... | Let's start with a simpler task: we have string A and B (|A|, |B| <= n), we have q queries and each query we ask the Hamming distance between A and a substring of B with length equals to |A|. How to solve this? We need to notice compute A with different offset of B is similar to the computation of convolution, so it ca... | [
"bitmasks",
"data structures",
"fft"
] | 2,800 | null |
474 | A | Keyboard | Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
\begin{verbatim}
qwertyuiop
asdfghjkl;
zxcvbnm,./
\end{verbatim}
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both ... | This is an implementation problem, therefore most of the solution fit in the time limit. We can even save the keyboard in $3$ strings and make a brute force search for each character to find its position and then print the left/right neighbour. | [
"implementation"
] | 900 | null |
474 | B | Worms | It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole $n$ ordered piles of worms such that $i$-th pile contains $a_{i}$ worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers $1$ to $a_{1}$, worms in second pile are lab... | There are two solutions: We can make partial sums ($sum_{i} = a_{1} + a_{2} + ... + a_{i}$) and then make a binary search for each query $q_{i}$ to find the result $j$ with the properties $sum_{j - 1} < q_{i}$ and $sum_{j} \ge q_{i}$. This solution has the complexity $O(n + m \cdot log(n))$ We can precalculate the in... | [
"binary search",
"implementation"
] | 1,200 | null |
474 | C | Captain Marmot | Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has $n$ regiments, each consisting of $4$ moles.
Initially, each mole $i$ ($1 ≤ i ≤ 4n$) is placed at some position $(x_{i}, y_{i})$ in the Cartesian plane. Captain Marmot wants to move some moles to make t... | For each $4$ points we want to see if we can rotate them with $90$ degrees such that we obtain a square. We can make a backtracking where we rotate each point $0, 1, 2$ or $3$ times and verify the figure obtained. If it's a square we update the minimal solution. Since we can rotate each point $0, 1, 2$ or $3$ times, fo... | [
"brute force",
"geometry"
] | 2,000 | null |
474 | D | Flowers | We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty... | We can notate each string as a binary string, instead of red and white flowers. A string of this type is good only if every maximal contigous subsequence of "$0$" has the length divisible by $k$. We can make dynamic programming this way : $nr_{i}$ = the number of good strings of length $i$. If the $i$-th character is "... | [
"dp"
] | 1,700 | null |
474 | E | Pillars | Marmot found a row with $n$ pillars. The $i$-th pillar has the height of $h_{i}$ meters. Starting from one pillar $i_{1}$, Marmot wants to jump on the pillars $i_{2}$, ..., $i_{k}$. ($1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n$). From a pillar $i$ Marmot can jump on a pillar $j$ only if $i < j$ and $|h_{i} - h_{j}| ≥ d$, wher... | We have to find a substring $i_{1}, i_{2}, ..., i_{k}$ such that $abs(h_{ij} - h_{ij + 1}) \ge D$ for $1 \le j < k$. Let's suppose that the values in $h$ are smaller. We can make dynamic programming this way : $best_{i}$ = the maximal length of such a substring ending in the $i$-th position, $best_{i} = max(best_{j... | [
"binary search",
"data structures",
"dp",
"sortings",
"trees"
] | 2,000 | null |
474 | F | Ant colony | Mole is hungry again. He found one ant colony, consisting of $n$ ants, ordered in a row. Each ant $i$ ($1 ≤ i ≤ n$) has a strength $s_{i}$.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$) and each pair of ants w... | For each subsequence $[L, R]$ we must find how many queens we have. A value is "queen" only if is the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$). Also, we must notice that the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$) can be only the minimum value from ($s_{L}, s_{L + 1}, ..., s_{R}$). So for each query we search in a data ... | [
"data structures",
"math",
"number theory"
] | 2,100 | null |
475 | A | Bayan Bus | The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
The event coordinator has a list of $k$ participants who should be picked up at the airport. When a ... | As usual for A we have an implementation problem and the main question is how to implement it quickly in the easiest (thus less error-prone) way. During the contest I spent almost no time thinking about it and decided to implement quite straightforward approach - start with empty string and concatenate different symbol... | [
"implementation"
] | 1,100 | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> result = {
"+------------------------+",
"|O.O.O.O.O.O.O.#.#.#.#.|D|)",
"|O.O.O.O.O.O.#.#.#.#.#.|.|",
"|O.......................|",
"|O.O.O.O.O.O.#.#.#.#.#.|.|)",
"+------------------------+"
};
int n; cin >> n;
for (int ... |
475 | B | Strongly Connected City | Imagine a city with $n$ horizontal streets crossing $m$ vertical streets, forming an $(n - 1) × (m - 1)$ grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also,... | For B we already might need some kind of algorithm to solve it, though for the constraints given you might use almost any approach. If you just have a directed graph then in order to check whether you can reach all nodes from all other nodes you can do different things - you can dfs/bfs from all nodes, two dfs/bfs from... | [
"brute force",
"dfs and similar",
"graphs",
"implementation"
] | 1,400 | #include <iostream>
#include <string>
using namespace std;
int main() {
int x; cin >> x >> x;
string s1; cin >> s1;
string s2; cin >> s2;
string s3 = { s1.front() , s1.back() , s2.front() , s2.back() };
cout << (s3 == "<>v^" || s3 == "><^v" ? "YES" : "NO");
} |
475 | C | Kamal-ol-molk's Painting | Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.
Consider the painting as a $n × m$ rectangular grid. At the beginning an $x × y$ rectangular brush is placed somewhere in the frame, with edges parallel to the frame, ($1 ≤ x ≤ n, 1 ≤ y... | There are probably several completely different ways to solve this problem, I will describe only the one I implemented during the round. The start point for the solution is that there are three cases we need to cover: either first time we move the brush right or we move it down or we do not move it at all. Let's start ... | [
"brute force",
"constructive algorithms",
"greedy"
] | 2,100 | null |
475 | D | CGCDSSQ | Given a sequence of integers $a_{1}, ..., a_{n}$ and $q$ queries $x_{1}, ..., x_{q}$ on it. For each query $x_{i}$ you have to count the number of pairs $(l, r)$ such that $1 ≤ l ≤ r ≤ n$ and $gcd(a_{l}, a_{l + 1}, ..., a_{r}) = x_{i}$.
$\operatorname{ecd}(v_{1},v_{2},\ldots,v_{n})$ is a greatest common divisor of $v_... | It seems that all the solutions for this problem based on the same observation. Let's introduce two number sequences: $a_{0}, a_{1}, ..., a_{n}$ and $x_{0} = a_{0}, x_{i} = gcd(x_{i - 1}, a_{i})$. Then the observation is that the number of distinct values in $x$ sequence is no more than $1 + log_{2}a_{0}$. It can be pr... | [
"brute force",
"data structures",
"math"
] | 2,000 | #include <iostream>
#include <map>
#include <vector>
using namespace std;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
int gcd(int a, int b) {
if (a % b == 0) return b;
return gcd(b, a % b);
}
int main() {
ios_base::sync_with... |
475 | E | Strongly Connected City 2 | Imagine a city with $n$ junctions and $m$ streets. Junctions are numbered from $1$ to $n$.
In order to increase the traffic flow, mayor of the city has decided to make each street one-way. This means in the street between junctions $u$ and $v$, the traffic moves only from $u$ to $v$ or only from $v$ to $u$.
The probl... | Here we can start with the simple observation - if we have a cycle then we can choose such an orientation for the edges such that it will become a directed cycle. In this case all nodes in the cycle will be accessible from all other nodes of the same cycle. I was using the bridges finding algorithm to find the cycles. ... | [
"dfs and similar"
] | 2,700 | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
typedef long long LL;
template<typename T> inline void maximize(T &a, T b) { a = std::max(a, b); }
#define all(v) v.begin(),v.end()
using namespace std;
template<typename T> struct argument_type;
template<typename T, typename U> struct ... |
475 | F | Meta-universe | Consider infinite grid of unit cells. Some of those cells are planets.
Meta-universe $M = {p_{1}, p_{2}, ..., p_{k}}$ is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet $p_{i}$ of meta-universe $M$ on it; 2) there are planets of $M$ located o... | Let's try to solve this problem naively first, the approach should be obvious then - you have a set of points, you iterate them left to right and you mind the gap between them. If there is such a gap between two neighbours you split this meta-universe with vertical line and do the same thing for each of two subsets. If... | [
"data structures"
] | 2,900 | #include <cstdlib>
#include <iostream>
#include <set>
using namespace std;
pair<int, int> mirror(pair<int, int> &p) {
return { p.second , p.first };
}
void move_from_first_two_sets_to_other_two(set<pair<int, int>> &set1_1, set<pair<int, int>> &set1_2, set<pair<int, int>> &set2_1, set<pair<int, int>> &set2_2,
... |
476 | A | Dreamoon and Stairs | Dreamoon wants to climb up a stair of $n$ steps. He can climb $1$ or $2$ steps at each move. Dreamoon wants the number of moves to be a multiple of an integer $m$.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? | We can show that the maximum number of moves possible is n and minimal moves needed is $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$, so the problem equals to determine the minimal integer that is a multiple of m in the range $\textstyle\left[{\frac{n}{2}}\right],n\right]$. One way to find the minimal number which ... | [
"implementation",
"math"
] | 1,000 | #include <cstdio>
int main(void)
{
int n, m ;
scanf("%d%d", &n, &m) ;
int lower_bound = (n+1)/2 ;
int ans = (lower_bound+m-1)/m*m ;
if(ans>n)
ans = -1 ;
printf("%d\n", ans) ;
return 0 ;
} |
476 | B | Dreamoon and WiFi | Dreamoon is standing at the position $0$ on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
- Go 1 unit towards the positive direction, denoted as '+'
- Go 1 unit towards the negative direction, denot... | The order of moves won't change the final position, so we can move all '?'s to the end of the string. We have the following information: 1. the correct final position 2. the position that Dreamoon will be before all '?'s 3. the number of '?'s We can infer that the distance and direction dreamoon still needs to move in ... | [
"bitmasks",
"brute force",
"combinatorics",
"dp",
"math",
"probabilities"
] | 1,300 | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
int main(void)
{
char s1[15], s2[15] ;
scanf("%s%s", s1, s2) ;
int n = strlen(s1) ;
int answerPosition = 0 ;
for(int i=0;i<n;i++)
answerPosition += (s1[i]=='+'?1:-1) ;
int finalPosition = 0 ;
... |
476 | C | Dreamoon and Sums | Dreamoon loves summing up something for no reason. One day he obtains two integers $a$ and $b$ occasionally. He wants to calculate the sum of all nice integers. Positive integer $x$ is called nice if $\operatorname*{mod}(x,b)\neq0$ and $\frac{\mathrm{div}(x,b)}{\mathrm{mod}\{x.b)}\implies\int$, where $k$ is some \textb... | If we fix the value of $k$, and let $d = div(x, b)$, $m = mod(x, b)$, we have : $d = mk$ $x = db + m$ So we have $x = mkb + m = (kb + 1) * m$. And we know $m$ would be in range $[1, b - 1]$ because it's a remainder and $x$ is positive, so the sum of $x$ of that fixed $k$ would be $\textstyle\sum_{m=1}^{b-1}((k b+1)m)=(... | [
"math"
] | 1,600 | #include <cstdio>
long long mod = 1000000007 ;
int main(void)
{
long long a, b ;
scanf("%I64d%I64d", &a, &b) ;
long long B = (b*(b-1)/2) % mod ;
long long A1 = (a*(a+1)/2) % mod ;
long long A = (A1*b+a) % mod ;
long long answer = (A*B) % mod ;
printf("%I64d\n", answer) ;
retu... |
476 | D | Dreamoon and Sets | Dreamoon likes to play with sets, integers and $\operatorname{gcd}$. $\operatorname*{gcd}(a,b)$ is defined as the largest positive integer that divides both $a$ and $b$.
Let $S$ be a set of exactly four distinct integers greater than $0$. Define $S$ to be of rank $k$ if and only if for all pairs of distinct elements $... | The first observation is that if we divide each number in a set by $k$, than the set would be rank $1$. So we could find $n$ sets of rank $1$ then multiple every number by $k$. For how to find $n$ sets of rank 1, we can use ${6a + 1, 6a + 2, 6a + 3, 6a + 5}$ as a valid rank $1$ set and take $a = 0$ to $n - 1$ to form $... | [
"constructive algorithms",
"greedy",
"math"
] | 1,900 | #include <cstdio>
int main(void)
{
int n, k ;
scanf("%d%d", &n, &k) ;
printf("%d\n", k*(6*n-1)) ;
for(int i=0;i<n;i++)
printf("%d %d %d %d\n", k*(6*i+1), k*(6*i+3), k*(6*i+4), k*(6*i+5)) ;
return 0 ;
} |
476 | E | Dreamoon and Strings | Dreamoon has a string $s$ and a pattern string $p$. He first removes exactly $x$ characters from $s$ obtaining string $s'$ as a result. Then he calculates $\operatorname{occ}(s^{\prime},p)$ that is defined as the maximal number of non-overlapping substrings equal to $p$ that can be found in $s'$. He wants to make this ... | First let $A[i]$ to be the minimal length $L$ needed so that substring $s[i..i + L]$ can become pattern $p$ by removing some characters. We can calculate this greedily by keep selecting next occurrence of characters in $p$ in $O(length(s))$ time for a fixed $i$, so for all $i$ requires $O(length(s)^{2})$. Next we can d... | [
"dp",
"strings"
] | 2,200 | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std ;
char s[2100], p[510] ;
int D[2100][2100] ;
int answer[2100] ;
int INF = 2100 ;
int main(void)
{
gets(s) ;
gets(p) ;
int Len_s = strlen(s) ;
int Len_p = strlen(p) ;
int k = Len_s/Len_p ;
D... |
477 | D | Dreamoon and Binary | Dreamoon saw a large integer $x$ written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning $x$ into its binary format. Now he is going to print it in the following manner.
He has an integer $n = 0$ and can only perform the following two operations in any order for unli... | Let $Xb$ be the binary string of number $X$. An ideal sequence can be expressed as a partition of $Xb$: $P_{1} = Xb[1..p_{1}], P_{2} = Xb[p_{1}..p_{2}], ... P_{K} = Xb[p_{K - 1}..length(Xb)]$ where $P_{i} \le P_{i + 1}$. The length of operations of such sequence is $P_{K} + K$. We can calculate the number of differen... | [
"dp",
"strings"
] | 2,700 | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
char X[5100] ;
int len ;
int arr[5100] ;
int rank[30][5100] ;
int *ref, rL ;
long long mod = 1000000007LL ;
long long sp[5100][5100] ;
long long ws[5100][5100] ;
//compare function for doubling prefix algorithm
//ref is... |
477 | E | Dreamoon and Notepad | Dreamoon has just created a document of hard problems using notepad.exe. The document consists of $n$ lines of text, $a_{i}$ denotes the length of the $i$-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long.
Let $(r, c)$ be a current cursor position, wher... | Although swapping two parts of a query would result in different answer, if we reverse the lines length alltogether then the answer would stay the same. So we only analyze queries where $r2 \ge r1$. The answers would comes in several types, we'll discuss them one by one: 1. HOME key being pressed once: the answer wil... | [
"data structures"
] | 3,100 | #include <bits/stdc++.h>
#define PB push_back
typedef long long LL;
using namespace std;
const int SIZE = 4e5+1;
const int MAX = 1e9;
int n,a[SIZE],an[SIZE],d[SIZE<<2],stk[SIZE],ml[SIZE];
struct data{
int x1,y1,y2,id;
data(int _x1,int _y1,int _y2,int _id){x1=_x1;y1=_y1;y2=_y2;id=_id;}
};
vector<data>in[2][SIZE]... |
478 | A | Initial Bet | There are five people playing a game called "Generosity". Each person gives some non-zero number of coins $b$ as an initial bet. After all players make their bets of $b$ coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program ... | To solve the problem, it is important to note that during the game, the number of coins on the table can not be changed. The total number of coins on the table after a successful bid, remains unchanged. Therefore, by dividing the total number of coins on the table by the number of players, can obtain an initial rate fo... | [
"implementation"
] | 1,100 | null |
478 | B | Random Teams | $n$ participants of the competition were split into $m$ teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that coul... | If you restate the problem in terms of graph theory, it can be formulated as follows: There is a graph consisting of n vertices and m connected components. Inside each connected component, each pair of vertices connected by an edge of the component. In other words, each connected component is a full mesh. What is the s... | [
"combinatorics",
"constructive algorithms",
"greedy",
"math"
] | 1,300 | null |
478 | C | Table Decorations | You have $r$ red, $g$ green and $b$ blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number $t$ of tables can be decorated if we know number of balloons of each color?
Your task is to write a pro... | Consider a situation where the value max (r, g, b) - min (r, g, b) \le 1, then obviously the answer is (r+g+b)/3. We can always decorate so many tables three balloons of different colors. Obviously, the remaining amount will be less than three balls, and hence can not be used to decorate the table anyway. All the rem... | [
"greedy"
] | 1,800 | null |
478 | D | Red-Green Towers | There are $r$ red and $g$ green blocks for construction of the red-green tower. Red-green tower can be built following next rules:
- Red-green tower is consisting of some number of levels;
- Let the red-green tower consist of $n$ levels, then the first level of this tower should consist of $n$ blocks, second level — o... | To begin, you will notice that in order to build a red-green tower height h requires h(h+1)/2 cubes. Therefore, the height of the resulting tower predetermined limits never exceeds 893. This height can be determined in advance, if it is assumed that all blocks of the same color. Try to prove it yourself. Further it is ... | [
"dp"
] | 2,000 | null |
478 | E | Wavy numbers | A wavy number is such positive integer that for any digit of its decimal representation except for the first one and the last one following condition holds: the digit is either strictly larger than both its adjacent digits or strictly less than both its adjacent digits. For example, numbers $35270$, $102$, $747$, $20$ ... | To solve this problem, it was necessary to note that the numbers on the undulating range of from 0 to 107 is much smaller than 107. In this case, the problem can be solved using an approach meet-in-the-middle. That is separate to solve this problem for the first seven digits of the answer, and for the last seven digits... | [
"brute force",
"dfs and similar",
"meet-in-the-middle",
"sortings"
] | 2,900 | null |
479 | A | Expression | Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers $a$, $b$, $c$ on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resul... | In this task you have to consider several cases and choose the best one: int ans = a + b + c; ans = max(ans, (a + b) * c); ans = max(ans, a * (b + c)); ans = max(ans, a * b * c); cout << ans << endl; | [
"brute force",
"math"
] | 1,000 | null |
479 | B | Towers | As you know, all the kids in Berland love playing with cubes. Little Petya has $n$ towers consisting of cubes of the same size. Tower with number $i$ consists of $a_{i}$ cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the ... | The task is solved greedily. In each iteration, move the cube from the tallest tower to the shortest one. To do this, each time find the position of minimum and maximum in the array of heights (in linear time). | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 1,400 | null |
479 | C | Exams | Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly $n$ exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a st... | The solution is again greedy. Sort the exams by increasing $a_{i}$, breaking ties by increasing $b_{i}$. Let's consider exams in this order and try to take the exams as early as possible. Take the first exams in this order on the early day ($b_{1}$). Move to the second exam. If we can take it on the day $b_{2}$ (i.e. $... | [
"greedy",
"sortings"
] | 1,400 | null |
479 | D | Long Jumps | Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!
However, there is no reason for disappointment, as Valery has found another ruler, its length is $l$ centimeters. The ruler already has $n$ marks, with which he can make meas... | It is easy to see that the answer is always 0, 1 or 2. If we can already measure both $x$ and $y$, output 0. Then try to measure both $x$ and $y$ by adding one more mark. If it was not successful, print two marks: one at $x$, other at $y$. So, how to check if the answer is 1? Consider all existing marks. Let some mark ... | [
"binary search",
"greedy",
"implementation"
] | 1,700 | null |
479 | E | Riding in a Lift | Imagine that you are in a building that has exactly $n$ floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from $1$ to $n$. Now you're on the floor number $a$. You are very bored, so you want to take the lift. Floor number $b$ has a secret lab, the entry is forbi... | The task is solved by a dynamic programming. State is a pair $(i, j)$, where $i$ is the number of trips made, and $j$ is the current floor. Initial state is $(0, a)$, final states are $(k, v)$, where $v$ is any floor (except $b$). It is easy to see the transitions: to calculate $dp(i, j)$, let's see what can be the pre... | [
"combinatorics",
"dp"
] | 1,900 | #include <cstdio>
#include <algorithm>
#include <ctime>
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int MOD = 1000000007;
const int N = 5005;
int d[2][N], n, a, b, k;
bool read() {
if (scanf("%d %d %d %d", &n, &a, &b, &k) != 4)
return false;
a--, b--;
return true;
}
int add(int... |
480 | D | Parcels | Jaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules:
- If the platform is empty, then the ... | Let's make two observations. First, consider the parcels as time segments $[in_{i}, out_{i}]$. It is true that if at some moment of time both parcel $i$ and parcel $j$ are on the platform, and $i$ is higher than $j$, then $[i n_{i},o u t_{i}]\subset[i n_{j},o u t_{j}]$. Second, let's imagine that there are some parcels... | [
"dp",
"graphs"
] | 2,600 | null |
480 | E | Parking Lot | Petya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an $n × m$ table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty.
Petya watches cars riding into the parking lot o... | Let's denote the car arrivals as events. Consider the following solution (it will help to understand the author's idea): let's consider all empty square in the table. There a too many of them, but imagine that we can afford to loop through all of them. If we fix a square, we can find out when it is no longer empty: fin... | [
"data structures",
"divide and conquer"
] | 2,800 | null |
482 | A | Diverse Permutation | Permutation $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers not larger than $n$. We'll denote as $n$ the length of permutation $p_{1}, p_{2}, ..., p_{n}$.
Your task is to find such permutation $p$ of length $n$, that the group of numbers $|p_{1} - p_{2}|, |p_{... | Let's see, what's the solution for some $k = n - 1$: 1 10 2 9 3 8 4 7 5 6 At the odd indexes we placed increasing sequence 1, 2, 3 .., at the even - decreasing sequence $n, n - 1, n - 2, ..$. First, we must get the permutation the way described above, then get first $k$ numbers from it, and then we should make all oth... | [
"constructive algorithms",
"greedy"
] | 1,200 | import java.math.BigInteger;
import java.util.Scanner;
import java.io.PrintWriter;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Boolean[... |
482 | B | Interesting Array | We'll call an array of $n$ non-negative integers $a[1], a[2], ..., a[n]$ interesting, if it meets $m$ constraints. The $i$-th of the $m$ constraints consists of three integers $l_{i}$, $r_{i}$, $q_{i}$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$) meaning that value $a[l_{i}]\,\ \ll\,a[l_{i}+1]\,\ \vartheta_{<\,\ \cdot\,\cdot\,\ \cdot\,\ ... | We will solve the task for every distinct bit. Now we must handle new constraint: $l[i], r[i], q[i]$. If number $q[i]$ has 1 in bit with number $pos$, then all numbers in segment $[l[i], r[i]]$ will have 1 in that bit too. To do that, we can use a standard idea of adding on a segment. Let's do two adding operation in ... | [
"constructive algorithms",
"data structures",
"trees"
] | 1,800 | #include <cstdio>
#include <algorithm>
const int N = 1000 * 1000;
const int MAXBIT = 30;
int l[N], r[N], q[N], a[N], t[4 * N];
int sum[N];
inline void build(int v, int l, int r) {
if (l + 1 == r) {
t[v] = a[l];
return;
}
int mid = (l + r) >> 1;
build(v * 2, l, mid);
build(v * 2 + 1, mid, r);
... |
482 | C | Game with Strings | You play the game with your friend. The description of this game is listed below.
Your friend creates $n$ distinct strings of the same length $m$ and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the $n$ strings equals $\texts... | Let's handle all string pairs and calculate the $mask$ mask, which will have 1-bits only in positions in which that strings have the same characters. In other words, we could not distinguish these strings using positions with submask of mask $mask$, then we must add in $d[mask]$ 1-bits in positions $i$ and $j$. This w... | [
"bitmasks",
"dp",
"probabilities"
] | 2,600 | #include <cstdio>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <ctime>
using namespace std;
const int N = 20;
const int M = 150;
int n;
char s[M][N + 10];
typedef long long li;
typedef long double ld;
li d[(1 << N)];
inline bool has(li mask, int pos) {
return (mask... |
482 | D | Random Function and Tree | You have a rooted tree consisting of $n$ vertices. Let's number them with integers from $1$ to $n$ inclusive. The root of the tree is the vertex $1$. For each $i > 1$ direct parent of the vertex $i$ is $p_{i}$. We say that vertex $i$ is child for its direct parent $p_{i}$.
You have initially painted all the vertices w... | Let's calculate $d[v][p]$ dynamics - the answer for vertex $v$ with size of parity $p$. At first step to calculate this dynamic for vertex $v$ we should count all different paintings of a subtree visiting all children in increasing order of their numbers. By multiplying this number by 2 we will get paintings visiting ... | [
"combinatorics",
"dp",
"trees"
] | 2,700 | #define _USE_MATH_DEFINES
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <list>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <stack>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
using ... |
482 | E | ELCA | You have a root tree containing $n$ vertexes. Let's number the tree vertexes with integers from $1$ to $n$. The tree root is in the vertex $1$.
Each vertex (except fot the tree root) $v$ has a direct ancestor $p_{v}$. Also each vertex $v$ has its integer value $s_{v}$.
Your task is to perform following queries:
- \t... | Let's split all $M$ requests in $\sqrt{M}$ blocks containing $\sqrt{M}$ requests each. Every block will be processed following way: First using dfs we need to calculate $p a t h_{v}=\sum\left(s i z e_{p_{u}}-s i z e_{u}\right)\cdot V_{p_{u}}$ for every vertex $v$, where $u$ is every ancestor of $v$, $size_{i}$ - size ... | [
"data structures",
"trees"
] | 3,200 | #include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <iomanip>
using namespace std;
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define sz(a) int(a.size())
#define pb push_back
#define all(a) a.begin(),a.end()
#define mp make_pair
typed... |
483 | A | Counterexample | Your friend has recently learned about coprime numbers. A pair of numbers ${a, b}$ is called coprime if the maximum number that divides both $a$ and $b$ is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair $(a, b)$ is coprime and the pair $(b, c)$ is coprime,... | This problem has two possible solutions: Let's handle all possible triples and check every of them for being a counterexample. This solution works with asymptotics $O(n^{3}logA)$ Handle only a few cases. It could be done like this: | [
"brute force",
"implementation",
"math",
"number theory"
] | 1,100 | #include <iostream>
using namespace std;
int main() {
long long l, r;
cin >> l >> r;
if (r - l + 1 < 3) {
cout << -1 << endl;
return 0;
}
if (l % 2 == 0) {
cout << l << ' ' << l + 1 << ' ' << l + 2 << endl;
return 0;
}
if (r - l + 1 > 3){
cout << l + 1 << ' ' << l + 2 << ' ' << l + 3 <... |
483 | B | Friends and Presents | You have two friends. You want to present each of them several positive integers. You want to present $cnt_{1}$ numbers to the first friend and $cnt_{2}$ numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In additio... | Jury's solution is using binary search. First, you can notice that if you can make presents with numbers $1, 2, ..., v$ then you can make presents with numbers $1, 2, ..., v, v + 1$ too. Let $f(v)$ be the function returning true or false: is it right, that you can make presents with numbers $1, 2, ..., v$. Let $f_{1}$... | [
"binary search",
"math"
] | 1,800 | #include <cstdio>
using namespace std;
typedef long long li;
int cnt[2], v[2];
inline bool f(li val) {
li f[] = {val / v[0], val / v[1]};
li l = v[0] * 1ll * v[1];
li both = val / l;
li other = val - f[0] - f[1] + both;
f[0] -= both;
f[1] -= both;
li tcnt[] = {cnt[0] - f[1], cnt[1] - ... |
484 | A | Bits | Let's denote as ${\mathrm{popcount}}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer $x$.
You are given multiple queries consisting of pairs of integers $l$ and $r$. For each query, find the $x$, such that $l ≤ x ≤ r$, and ${\mathsf{P o P c o u n t}}(x)$ is maximum possib... | Let us define function $f(L, R)$, that gives answer to the query. It looks follows: if $L = R$ then $f(L, R) = L$; else if $2^{b} \le L$, where $b$ - maximum integer such $2^{b} \le R$, then $f(L, R) = f(L - 2^{b}, R - 2^{b}) + 2^{b}$; else if $2^{b + 1} - 1 \le R$ then $f(L, R) = 2^{b + 1} - 1$; else $f(L, R) = ... | [
"bitmasks",
"constructive algorithms"
] | 1,700 | null |
484 | B | Maximum Value | You are given a sequence $a$ consisting of $n$ integers. Find the maximum possible value of $a_{i}{\mathrm{~mod~}}a_{j}$ (integer remainder of $a_{i}$ divided by $a_{j}$), where $1 ≤ i, j ≤ n$ and $a_{i} ≥ a_{j}$. | Let us iterate over all different $a_{j}$. Since we need to maximize $a_{i}{\mathrm{~mod~}}a_{j}$, then iterate all integer $x$ (such $x$ divisible by $a_{j}$) in range from $2a_{j}$ to $M$, where $M$ - doubled maximum value of the sequence. For each such $x$ we need to find maximum $a_{i}$, such $a_{i} < x$. Limits fo... | [
"binary search",
"math",
"sortings",
"two pointers"
] | 2,100 | null |
484 | C | Strange Sorting | How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: \underline{$d$-sorting}. This sorting is applied to the strings of length at least $d$, where $d$ is some positive integer. The characters of... | Note, that $d$-sorting is just a permutation (call it $P$), because it does not depends on characters in string. Look at shuffling operation in different way: instead of going to the next substring and sort it, we will shift string to one character left. It remains to understand that shift of string the permutation too... | [
"implementation",
"math"
] | 2,600 | null |
484 | D | Kindergarten | In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's \underline{sociability} ... | Let us note, that in optimal answer any segment that making a group contains their minimum and maximum values on borders. Otherwise it will be better to split this segment to two other segments. Another note that is every segment in optimal solution is strictly monotonic (increasing or decreasing). Paying attention to ... | [
"data structures",
"dp",
"greedy"
] | 2,400 | null |
484 | E | Sign on Fence | Bizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of $n$ panels of $1$ meter width and of arbitrary height. The $i$-th panel's height is $h_{i}$ meters. The adjacent planks follow without a gap between them.
After Bizon painted the fence he decided to put a "for sale" s... | Let us note that we can use binary search to find answer to the one query. Suppose at some moment was fixed height $h$ and need to know will fit the rectangle with width $w$ and height $h$ to the segment of fence from $l$-th to $r$-th panel. Let us build data structure that can answer to this question. This will be per... | [
"binary search",
"constructive algorithms",
"data structures"
] | 2,500 | null |
485 | A | Factory | One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were $x$ details in the factory storage, then by the end of the day the factory has to produce $x\ {\mathrm{mod}}\ m$ (remainder after dividing $x$ by $m$) more details... | Production will stops iff exists integer $K \ge 0$ such $a \cdot 2^{K}$ is divisible by $m$. From this fact follows that $K$ maximum will be about $O(log_{2}(m))$. So if we modeling some, for example, 20 days and production does not stop, then it will never stop and answer is "No". Otherwise answer is "Yes". | [
"implementation",
"math",
"matrices"
] | 1,400 | null |
485 | B | Valuable Resources | Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. ... | Let us find minimum length needed to cover points by $Ox$. It is $Maximum(x_{i}) - Minumum(x_{i})$. The same in $Oy$ - $Maximum(y_{i}) - Minumum(y_{i})$. Since we need a square city to cover all the mines, then we need to set length of this square to the maximum from those two values. | [
"brute force",
"greedy"
] | 1,300 | null |
486 | A | Calculating Function | For a positive integer $n$ let's define a function $f$:
$f(n) = - 1 + 2 - 3 + .. + ( - 1)^{n}n$
Your task is to calculate $f(n)$ for a given integer $n$. | If $n$ is even, then the answer is $n / 2$, otherwise the answer is $(n - 1) / 2 - n$ = $- (n + 1) / 2$. | [
"implementation",
"math"
] | 800 | null |
486 | B | OR in Matrix | Let's define logical $OR$ as an operation on two logical values (i. e. values that belong to the set ${0, 1}$) that is equal to $1$ if either or both of the logical values is set to $1$, otherwise it is $0$. We can define logical $OR$ of three or more logical values in the same manner:
$a_{1}\,\mathrm{OR}\,a_{2}\,\mat... | Hint of this problem is presented in its statement. "$a_{1}\,\mathrm{OR}\,a_{2}\,\mathrm{OR}\dots\dots\mathrm{OR}\,a_{k}$ where $a_{i}\in\{0,1\}$ is equal to $1$ if some $a_{i} = 1$, otherwise it is equal to $0$." To solve this problem, do 3 following steps: Complexity: We can implement this algorithm in $O(m * n)$, bu... | [
"greedy",
"hashing",
"implementation"
] | 1,300 | null |
486 | C | Palindrome Transformation | Nam is playing with a string on his computer. The string consists of $n$ lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that... | Assuming that cursor's position is in the first half of string($i.e$ $1 \le p \le n / 2$) (if it's not, just reverse the string, and change $p$ to $n - p + 1$, then the answer will not change). It is not hard to see that, in optimal solution, we only need to move our cusor in the first half of the string only, and ... | [
"brute force",
"greedy",
"implementation"
] | 1,700 | null |
486 | D | Valid Sets | As you know, an undirected connected graph with $n$ nodes and $n - 1$ edges is called a \underline{tree}. You are given an integer $d$ and a tree consisting of $n$ nodes. Each node $i$ has a value $a_{i}$ associated with it.
We call a set $S$ of tree nodes \underline{valid} if following conditions are satisfied:
- $S... | Firstly, we solve the case $d = + \infty $. In this case, we can forget all $a_{i}$ since they doesn't play a role anymore. Consider the tree is rooted at node 1. Let $F_{i}$ be the number of valid sets contain node $i$ and several other nodes in subtree of $i$ ("several" here means 0 or more). We can easily calculate... | [
"dfs and similar",
"dp",
"math",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2000 + 10;
const int MOD = (int)(1e9) + 7;
vector<int> adj[MAXN];
int a[MAXN], f[MAXN];
bool visited[MAXN];
int d, n;
void DFS(int u, int root) {
visited[u] = true;
f[u] = 1;
for(int i = 0; i < adj[u].size(); i++) {
int v = adj[u... |
486 | E | LIS of Sequence | The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence $a$ consisting of $n$ ($1 ≤ n ≤ 10^{5}$) elements $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i} ≤ ... | LIS = Longest increasing subsequence. // Calculates $F1_{i}$ and $F2_{i}$ is familiar task, so I will not dig into this. For those who have'nt known it yet, this link may be useful) // We can calculate $D1_{i}$ and $D2_{i}$ by using advanced data structure, like BIT or Segment tree. $l$ = length of LIS of ${a_{1}, a_{2... | [
"data structures",
"dp",
"greedy",
"hashing",
"math"
] | 2,200 | null |
487 | A | Fight the Monster | A monster is attacking the Cyberland!
Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints ($HP$), offensive power ($ATK$) and defensive power ($DEF$).
During the battle, every second the monster's HP decrease by $max(0, ATK_{Y} - DEF_{M})$, while Yang's HP decre... | It is no use to make Yang's ATK > HP_M + DEF_M (Yang already can beat it in a second). And it's no use to make Yang's DEF > ATK_M (it cannot deal any damage to him). As a result, Yang's final ATK will not exceed $200$, and final DEF will not exceed $100$. So just enumerate final ATK from ATK_Y to $200$, final DEF from ... | [
"binary search",
"brute force",
"implementation"
] | 1,800 | null |
487 | B | Strip | Alexandra has a paper strip with $n$ numbers on it. Let's call them $a_{i}$ from left to right.
Now Alexandra wants to split it into some pieces (possibly $1$). For each piece of strip, it must satisfy:
- Each piece should contain at least $l$ numbers.
- The difference between the maximal and the minimal number on th... | We can use dynamic programming to solve this problem. Let $f[i]$ denote the minimal number of pieces that the first $i$ numbers can be split into. $g[i]$ denote the maximal length of substrip whose right border is $i$(included) and it satisfy the condition. Then $f[i] = min(f[k]) + 1$, where $i - g[i] \le k \le i -... | [
"binary search",
"data structures",
"dp",
"two pointers"
] | 2,000 | null |
487 | C | Prefix Product Sequence | Consider a sequence $[a_{1}, a_{2}, ... , a_{n}]$. Define its prefix product sequence $[a_{1}\mod n,(a_{1}a_{2})\mod n,\cdot\cdot\cdot,(a_{1}a_{2}\cdot\cdot\cdot a_{n})\mod n]$.
Now given $n$, find a permutation of $[1, 2, ..., n]$, such that its prefix product sequence is a permutation of $[0, 1, ..., n - 1]$. | The answer is YES if and only if $n$ is a prime or $n = 1$ or $n = 4$. First we can find $a_{1}a_{2}\cdot\cdot\cdot a_{n}=n!\equiv0\mod n$. If $n$ occurs in {a_1, \dots ,a_{n-1}} in the prefix product sequence $0$ will occur twice which do not satisfy the condition. So $a_{n}$ must be $0$ from which we know $a_{1a}_{2}... | [
"constructive algorithms",
"math",
"number theory"
] | 2,300 | null |
487 | D | Conveyor Belts | Automatic Bakery of Cyberland (ABC) recently bought an $n × m$ rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are $2(n + m)$ seats in total.
ABC placed conveyor belts on each unit square on the table. There are three types of conveyor ... | This problem can be solved by classic data structures. For example, let's try something like SQRT-decomposition. Let's divide the map horizontally into some blocks. For each grid, calculate its destination when going out the current block (or infinite loop before going out current block). For each modification, recalcu... | [
"data structures"
] | 2,700 | null |
487 | E | Tourists | There are $n$ cities in Cyberland, numbered from $1$ to $n$, connected by $m$ bidirectional roads. The $j$-th road connects city $a_{j}$ and $b_{j}$.
For tourists, souvenirs are sold in every city of Cyberland. In particular, city $i$ sell it at a price of $w_{i}$.
Now there are $q$ queries for you to handle. There a... | First we can find out all cut vertices and biconnected components(BCC) by Tarjan's Algorithm. And it must form a tree. From the lemma below, we know that if we can pass by a BCC, then we can always pass any point in the BCC. We use a priority queue for each BCC to maintain the minimal price in the component. For each m... | [
"data structures",
"dfs and similar",
"graphs",
"trees"
] | 3,200 | null |
488 | A | Giga Tower | Giga Tower is the tallest and deepest building in Cyberland. There are $17 777 777 777$ floors, numbered from $ - 8 888 888 888$ to $8 888 888 888$. In particular, there is floor $0$ between floor $ - 1$ and floor $1$. Every day, thousands of tourists come to this place to enjoy the wonderful view.
In Cyberland, it is... | The answer $b$ is very small (usually no larger than $10$), because one of $a + 1, a + 2, ..., a + 10$ has its last digit be $8$. However, $b$ can exceed $10$ when $a$ is negative and close to $0$. The worst case is $a = - 8$, where $b = 16$. Anyway $b$ is rather small, so we can simply try $b$ from $1$, and check whet... | [
"brute force"
] | 1,100 | null |
488 | B | Candy Boxes | There is an old tradition of keeping $4$ boxes of candies in the house in Cyberland. The numbers of candies are \underline{special} if their \underline{arithmetic mean}, their \underline{median} and their \underline{range} are all equal. By definition, for a set ${x_{1}, x_{2}, x_{3}, x_{4}}$ ($x_{1} ≤ x_{2} ≤ x_{3} ≤ ... | Let's sort the four numbers in ascending order: $a, b, c, d$ (where $x_{1}, x_{2}, x_{3}, x_{4}$ are used in problem statement). So ${\frac{a+b+c+d}{4}}={\frac{b+c}{2}}=d-a$. With some basic math, we can get $a: d = 1: 3$ and $a + d = b + c$. Solution 1: If $n = 0$, just output any answer (such as ${1, 1, 3, 3}$). If $... | [
"brute force",
"constructive algorithms",
"math"
] | 1,900 | null |
489 | A | SwapSort | In this problem your goal is to sort an array consisting of $n$ integers in at most $n$ swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number o... | All you need is to swap the current minimum with the $i$-th element each time. You can do it with the code like: This solution makes at most n-1 swap operation. Also if (i != j) is not necessary. | [
"greedy",
"implementation",
"sortings"
] | 1,200 | null |
489 | B | BerSU Ball | The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! $n$ boys and $m$ girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pa... | There are about 100500 ways to solve the problem. You can find maximal matching in a bipartite graph boys-girls, write dynamic programming or just use greedy approach. Let's sort boys and girls by skill. If boy with lowest skill can be matched, it is good idea to match him. It can't reduce answer size. Use girl with lo... | [
"dfs and similar",
"dp",
"graph matchings",
"greedy",
"sortings",
"two pointers"
] | 1,200 | null |
489 | C | Given Length and Sum of Digits... | You have a positive integer $m$ and a non-negative integer $s$. Your task is to find the smallest and the largest of the numbers that have length $m$ and sum of digits $s$. The required numbers should be non-negative integers written in the decimal base without leading zeroes. | There is a greedy approach to solve the problem. Just try first digit from lower values to higher (in subtask to minimize number) and check if it is possible to construct a tail in such a way that it satisfies rule about length/sum. You can use a function `can(m,s)' that answers if it is possible to construct a sequenc... | [
"dp",
"greedy",
"implementation"
] | 1,400 | null |
489 | D | Unbearable Controversy of Being | Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!
Tomash has noticed that even simple cases of... | Let's iterate through all combinations of $a$ and $c$ just two simple nested loops in $O(n^{2})$ and find all candidates for $b$ and $d$ inside. To find candidates you can go through all neighbors of $a$ and check that they are neighbors of $c$. Among all the candidates you should choose two junctions as $b$ and $d$. S... | [
"brute force",
"combinatorics",
"dfs and similar",
"graphs"
] | 1,700 | null |
490 | A | Team Olympiad | The School №0 of the capital of Berland has $n$ children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value $t_{i}$:
- $t_{i} = 1$, if the $i$-th child is good at progr... | The teams could be formed using greedy algorithm. We can choose any three children with different skills who are not participants of any team yet and form a new team using them. After some time we could not form any team, so the answer to the problem is minimum of the number of ones, twos and threes in given array. We ... | [
"greedy",
"implementation",
"sortings"
] | 800 | null |
490 | B | Queue | During the lunch break all $n$ Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID ... | This problem can be solved constructively. Find the first student - it is a student with such number which can be found among $a_{i}$ and could not be found among $b_{i}$ (because he doesn't stand behind for anybody). Find the second student - it is a student standing behind the first, number $a_{i}$ of the first stude... | [
"dsu",
"implementation"
] | 1,500 | null |
490 | C | Hacking Cypher | Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long inte... | At first, let's check all prefixes of specified number - do they have remainder 0 when divided by the $a$? It can be done with asymptotic behavior $O(N)$, where $N$ -length of specified number $C$. If we have remainder of division by $a$ of prefix, which ends in position $pos$, we can count remainder in position $pos +... | [
"brute force",
"math",
"number theory",
"strings"
] | 1,700 | null |
490 | D | Chocolate | Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is $a_{1} × b_{1}$ segments large and the second one is $a_{2} × b_{2}$ segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the o... | We can change the numbers by dividing their by two or by dividing their by three and multiply two. Firstly remove all 2 and 3 from factorization of chocolate and determine equals their square or not. If their squares are not equals answer doesn't exists. Otherwise calculate of difference between number of three in fact... | [
"brute force",
"dfs and similar",
"math",
"meet-in-the-middle",
"number theory"
] | 1,900 | null |
490 | E | Restoring Increasing Sequence | Peter wrote on the board a strictly increasing sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.
Restore the the original sequence knowing digits remaining on the b... | Let's iterate on specified numbers and try to make from current number minimal possible, which value more than value of previous number. Let's current number is $cur$, previous number is $prev$. If length of number $cur$ less than length of number $prev$ - let's print $NO$, this problem has not solution. If length of n... | [
"binary search",
"brute force",
"greedy",
"implementation"
] | 2,000 | null |
490 | F | Treeland Tour | The "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.
Treeland consists of $n$ cities, some pairs of cities are connected by bidirectional roads. Overall the country has $n - 1$ roads... | The problem is generalization of finding maximal increasing subsequence in array, so it probably can be solved using dynamic programming. We will calc dynamic $d[(u, v)]$, the state is directed edge $(u, v)$ in tree. Value $d[(u, v)]$ means the maximum number of vertices where the band will have concerts on some simple... | [
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,200 | null |
492 | A | Vanya and Cubes | Vanya got $n$ cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of $1$ cube, the second level must consist of $1 + 2 = 3$ cubes, the third level must have $1 + 2 + 3 = 6$ cubes, and so on. Thus, the $i$-th level of the pyramid must hav... | In fact need to do what is asked in the statement. We need to find in a cycle the maximum height $h$, counting, how many blocks must be in $i$-th row and adding these values to the result. Iterate until the result is not greater than $n$. | [
"implementation"
] | 800 | #include <stdio.h>
int n,h,i,cnt;
int main()
{
scanf("%d",&n);
while (cnt <= n)
{
h++;
cnt += (h*(h+1))/2;
}
printf("%d\n",h-1);
return 0;
} |
492 | B | Vanya and Lanterns | Vanya walks late at night along a straight street of length $l$, lit by $n$ lanterns. Consider the coordinate system with the beginning of the street corresponding to the point $0$, and its end corresponding to the point $l$. Then the $i$-th lantern is at the point $a_{i}$. The lantern lights all points of the street t... | Sort lanterns in non-decreasing order. Then we need to find maximal distance between two neighbour lanterns, let it be $maxdist$. Also we need to consider street bounds and count distances from outside lanterns to street bounds, it will be $(a[0] - 0)$ and $(l - a[n - 1])$. The answer will be $max(maxdist / 2, max(a[0]... | [
"binary search",
"implementation",
"math",
"sortings"
] | 1,200 | #include <stdio.h>
#include <algorithm>
using namespace std;
int n,i,a[100500],rez,l;
int main()
{
scanf("%d%d",&n,&l);
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
rez = 2*max(a[0],l-a[n-1]);
for (i = 0; i < n-1; i++)
rez = max(rez, a[i+1]-a[i]);
printf("%.10f\n",rez/... |
492 | C | Vanya and Exams | Vanya wants to pass $n$ exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least $avg$. The exam grade cannot exceed $r$. Vanya has passed the exams and got grade $a_{i}$ for the $i$-th exam. To increase the grade for the $i$-th exam by 1 point, Vanya m... | Sort $(a_{i}, b_{i})$ in non-decreasing order for number of essays $b_{i}$, after that go from the beginning of this sorted pairs and add greedily the maximal number of points we can, i.e. add value $min(avg * n - sum, r - a_{i})$, while total amount of points will not be greater, than $avg * n$. Time complexity $O(nlo... | [
"greedy",
"sortings"
] | 1,400 | #include <stdio.h>
#include <algorithm>
using namespace std;
long long n,avg,r,i,rez,sum;
pair <long long, long long> a[100500];
int main()
{
scanf("%d%d%d",&n,&r,&avg);
for (i = 0; i < n; i++)
{
scanf("%d%d",&a[i].second,&a[i].first);
sum += a[i].second;
}
sort(a,a+n);
rez = i =... |
492 | D | Vanya and Computer Game | Vanya and his friend Vova play a computer game where they need to destroy $n$ monsters to pass a level. Vanya's character performs attack with frequency $x$ hits per second and Vova's character performs attack with frequency $y$ hits per second. Each character spends fixed time to raise a weapon and then he hits (the t... | Let's create vector $rez$ with size $x + y$, in which there will be a sequence of Vanya's and Vova's strikes for the first second. To do this, we can take 2 variables $cntx = cnty = 0$. Then while $cntx < x$ and $cnty < y$, we will check 3 conditions: 1) If $(cntx + 1) / x > (cnty + 1) / y$, then add into the vector wo... | [
"binary search",
"implementation",
"math",
"sortings"
] | 1,800 | #include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
int n,x,y,i,t,cntx,cnty;
vector <int> rez;
int main()
{
scanf("%d%d%d",&n,&x,&y);
cntx = cnty = 0;
while (cntx < x||cnty < y)
{
if ((long long)(cntx+1)*y > (long long)(cnty+1)*x)
{
cnty++;
... |
492 | E | Vanya and Field | Vanya decided to walk in the field of size $n × n$ cells. The field contains $m$ apple trees, the $i$-th apple tree is at the cell with coordinates $(x_{i}, y_{i})$. Vanya moves towards vector $(dx, dy)$. That means that if Vanya is now at the cell $(x, y)$, then in a second he will be at cell $((x+d x)\operatorname*{m... | As long as $gcd(dx, n) = gcd(dy, n) = 1$, Vanya will do full cycle for $n$ moves. Let's group all possible pathes into $n$ groups, where $1 - th, 2 - nd, ... , n - th$ path will be started from points $(0, 0), (0, 1), \dots , (0, n - 1)$. Let's look on first path: $(0, 0) - (dx, dy) - ((2 * dx)$ $mod$ $n, (2 * dy)$ $m... | [
"math"
] | 2,000 | #include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
int n,m,dx,dy,x,y,i,j,a[1000500],b[1000500],rez;
int main()
{
scanf("%d%d%d%d",&n,&m,&dx,&dy);
x = y = a[0] = 0;
for (i = 0; i < n; i++)
{
x = (x+dx)%n;
y = (y+dy)%n;
a[x] = y;
}
for (i = 0; i ... |
493 | A | Vasya and Football | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.
Vasya is watching a recorded football match now and makes notes of all the fouls tha... | We need 2 arrays - for the first and second team, in which we must save "status" of the player - is he "clear", yellow carded or sent off. Then while inputing we must output the players name if he wasn't sent off, and after the event he must be sent off. | [
"implementation"
] | 1,300 | null |
493 | B | Vasya and Wrestling | Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is \textbf{lexicographically greater}, wins.
If the seq... | We need to vectors in which we will save points of first and second wrestlers, and two int-s, where we will save who made the last technique and what is the sum of all the numbers in the input. If the sum is not zero, we know the answer. Else we pass by the vectors, checking are there respective elements which are not ... | [
"implementation"
] | 1,400 | null |
493 | C | Vasya and Basketball | Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of $d$ meters, and a throw is worth 3 points if the distance is larger t... | We need an array of pairs - in each pair we save the distance and the number of team. Then we sort the array. Then we assume that all the throws bring 3 points. Then we pass by the array and one of our numbers we decrease on 1 (which one - it depends on the second element of array). Then we compare it with our answer. ... | [
"binary search",
"brute force",
"data structures",
"implementation",
"sortings",
"two pointers"
] | 1,600 | null |
493 | D | Vasya and Chess | Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.
The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell cont... | If n is odd, then black can win white doing all the moves symetric by the central line. Else white can win putting his queen on (1,2) (which is the lexicographicly smallest place) and play symetricly - never using the first row. | [
"constructive algorithms",
"games",
"math"
] | 1,700 | null |
493 | E | Vasya and Polynomial | Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. \underline{Polynomial} is a function $P(x) = a_{0} + a_{1}x^{1} + ... + a_{n}x^{n}$. Numbers $a_{i}$ are called \underline{coefficients} of a polynomial, non-negative integer $n$ is called a \underline{degree} of... | Let's discuss 2 case. 1) t!=1 and 2) t=1. 1) If our function is not constant (n>=1) than a is greater all the coefficients, so the only polynom can be the number b - in the a-ary counting system. We must only check that one and constant function. 2)if t=1 must be careful: in case 1 1 1: the answer is inf, in case 1 1 n... | [
"math"
] | 2,800 | null |
494 | A | Treasure | Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string $s$ written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that th... | Consider a string consisting of '(' and ')' characters. Let's build the following sequence from this string: $a_{0} = 0$ $a_{0} = 0$ for each $1 \le i \le |s|$ $a_{i} = a_{i - 1} + 1$ if $s_{i} = '('$ and $a_{i} = a_{i - 1} - 1$ otherwise. (The string is considered as 1-based index). for each $1 \le i \le |s|$ ... | [
"greedy"
] | 1,500 | null |
494 | B | Obsessive String | Hamed has recently found a string $t$ and suddenly became quite fond of it. He spent several days trying to find all occurrences of $t$ in other strings he had. Finally he became tired and started thinking about the following problem. Given a string $s$ how many ways are there to extract $k ≥ 1$ non-overlapping substri... | We call an index $i(1 \le i \le |s|)$ good if $t$ equals $s_{i - |t| + 1}s_{i - |t| + 2}... s_{i}$. To find all good indexes let's define $q_{i}$ as the length of longest prefix of $t$ which is a suffix of $s_{1}s_{2}... s_{i}$. A good index is an index with $q_{i} = |t|$. Calculating $q_{i}$ can be done using Knut... | [
"dp",
"strings"
] | 2,000 | null |
494 | C | Helping People | Malek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows $n$ poor people numbered from $1$ to $n$. The institute gave Malek $q$ recommendations. A recommendation is a segment of people like $[l, r]$ which means the institute recommended that ... | We'll first create a rooted tree from the given segments which each node represents a segment. We'll solve the problem using dynamic programming on this tree. First of all let's add a segment $[1, n]$ with probability of being chosen by Malek equal to $0$. The node representing this segment will be the root of the tree... | [
"dp",
"probabilities"
] | 2,600 | null |
494 | D | Birthday | Ali is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but th... | We solve this problem by answering queries offline. We'll first store in each vertex $v$ number of vertices such as $x$ for which we must calculate $f(v, x)$ . starting from the root. We'll keep two arrays $a$ and $b$. Suppose we're at vertex $v$ right now then $a_{i}$ equals $d(i, v)^{2}$ and $b_{i}$ equal $d(i, v)$. ... | [
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,700 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.