input
stringlengths
29
13k
output
stringlengths
9
73.4k
Alice and Bob always had hard time choosing restaurant for the dinner. Previously they performed Eenie Meenie Miney Mo game, but eventually as their restaurant list grew, they had to create a new game. This new game starts as they write restaurant names on N cards and align the cards in one line. Before the game begins...
#include <bits/stdc++.h> using namespace std; long long w, n, a, b, da, db; string s, s2; bool jo; void v0() { if (!jo) { cout << 0 << "\n"; jo = 1; } } void v1() { if (!jo) { cout << n - 1 << "\n"; jo = 1; } } void valt() { if (a == 1 && da == -1 || a == n && da == 1) { da *= -1; } if...
Little Johnny Bubbles enjoys spending hours in front of his computer playing video games. His favorite game is Bubble Strike, fast-paced bubble shooting online game for two players. Each game is set in one of the N maps, each having different terrain configuration. First phase of each game decides on which map the gam...
#include <bits/stdc++.h> using namespace std; int main() { int N; float P; cin >> N >> P; for (int k = 0; k <= N; k++) { float c0 = (N - k) * (N - k - 1) * (N - k - 2) / 6.0; float c1 = k * ((N - k) * (N - k - 1)) / 2.0; float c2 = k * (k - 1) / 2 * (N - k) / 1.0; float c3 = k * (k - 1) * (k - 2...
There are N bubbles in a coordinate plane. Bubbles are so tiny that it can be assumed that each bubble is a point (X_i, Y_i). Q Bubble Cup finalists plan to play with the bubbles. Each finalist would link to use infinitely long Bubble Cup stick to pop some bubbles. The i-th finalist would like to place the stick in t...
#include <bits/stdc++.h> using namespace std; using Point = complex<int>; using ll = long long; ll cross(Point a, Point b) { return 1LL * a.real() * b.imag() - 1LL * b.real() * a.imag(); } ll det(Point a, Point b, Point c) { return cross(b - a, c - a); } namespace std { bool operator<(const Point& a, const Point& b) ...
You are given two integer arrays of length N, A1 and A2. You are also given Q queries of 4 types: 1 k l r x: set Ak_i:=min(Ak_i, x) for each l ≤ i ≤ r. 2 k l r x: set Ak_i:=max(Ak_i, x) for each l ≤ i ≤ r. 3 k l r x: set Ak_i:=Ak_i+x for each l ≤ i ≤ r. 4 l r: find the (∑_{i=l}^r F(A1_i+A2_i)) \% (10^9+7) where F(...
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &t) { t = 0; char ch = getchar(); int f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } do { (t *= 10) += ch - '0'; ch = getchar(); } while ('0' <= ch && ch <= '9'); t *= f; } tem...
In the year 2420 humans have finally built a colony on Mars thanks to the work of Elon Tusk. There are 10^9+7 cities arranged in a circle in this colony and none of them are connected yet. Elon Tusk wants to connect some of those cities using only roads of the same size in order to lower the production cost of those ro...
#include <bits/stdc++.h> using namespace std; const int N = 200010, mo = 1e9 + 7; int n, q; long long a[N], s1[N], s2[N], c[N]; long long qmi(long long a, long long k) { long long res = 1; while (k) { if (k & 1) res = res * a % mo; a = a * a % mo; k >>= 1; } return res; } long long mod(long long x) ...
You are given N points on an infinite plane with the Cartesian coordinate system on it. N-1 points lay on one line, and one point isn't on that line. You are on point K at the start, and the goal is to visit every point. You can move between any two points in a straight line, and you can revisit points. What is the min...
#include <bits/stdc++.h> using namespace std; const int DIM = 2e5 + 5; struct point { int x, y; point() : x(0), y(0){}; }; bool colinear(point a, point b, point c) { if (1LL * (a.x - b.x) * (a.y - c.y) == 1LL * (a.x - c.x) * (a.y - b.y)) { if (a.x - b.x == 0) { if (a.x - c.x == 0) return true; ret...
This is an interactive problem! As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant 10^9 × 10^9 grid, with squares having both coordinates between 1 and 10^9. You know that the enemy base has the shape of a rectangle...
#include <bits/stdc++.h> using namespace std; inline int read(void) { register int x = 0, sgn = 1, ch = getchar(); while (ch < 48 || 57 < ch) { if (ch == 45) sgn = 0; ch = getchar(); } while (47 < ch && ch < 58) { x = x * 10 + ch - 48; ch = getchar(); } return sgn ? x : -x; } void write(int ...
You are given an undirected graph of N nodes and M edges, E_1, E_2, ... E_M. A connected graph is a cactus if each of it's edges belogs to at most one simple cycle. A graph is a desert if each of it's connected components is a cactus. Find the number of pairs (L, R), (1 ≤ L ≤ R ≤ M) such that, if we delete all the e...
#include <bits/stdc++.h> using namespace std; struct node { int son[2], fa; int revtag, tag, key, sum, qwq; } t[750010]; int n, m; inline void up(int x) { t[x].sum = t[t[x].son[0]].sum | t[t[x].son[1]].sum | t[x].key; t[x].qwq = t[t[x].son[0]].qwq | t[t[x].son[1]].qwq | (x > n); } inline void rev(int x) { t[x...
Bob really likes playing with arrays of numbers. That's why for his birthday, his friends bought him a really interesting machine – an array beautifier. The array beautifier takes an array A consisting of N integers, and it outputs a new array B of length N that it constructed based on the array given to it. The arra...
#include <bits/stdc++.h> using namespace std; const int M = 1000000007; const int MM = 998244353; template <typename T, typename U> static inline void amin(T &x, U y) { if (y < x) x = y; } template <typename T, typename U> static inline void amax(T &x, U y) { if (x < y) x = y; } map<int, map<int, pair<int, int>>> m...
Alice and Bob are playing a game. They are given an array A of length N. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the s...
from __future__ import division, print_function import math import sys import os from io import BytesIO, IOBase #from collections import deque, Counter, OrderedDict, defaultdict #import heapq #ceil,floor,log,sqrt,factorial,pow,pi,gcd #import bisect #from bisect import bisect_left,bisect_right BUFSIZE = 8192 class Fa...
On the great island of Baltia, there live N people, numbered from 1 to N. There are exactly M pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party ...
#include <bits/stdc++.h> using namespace std; const int mxN = 1000006, mod = 1e9 + 7, LOG = 23; int n, m, u, v; bool veze[55][55]; bool check(int i1, int i2, int i3, int i4, int i5) { if (veze[i1][i2] && veze[i1][i3] && veze[i1][i4] && veze[i1][i5]) { if (veze[i2][i3] && veze[i2][i4] && veze[i2][i5]) { if (...
You have received data from a Bubble bot. You know your task is to make factory facilities, but before you even start, you need to know how big the factory is and how many rooms it has. When you look at the data you see that you have the dimensions of the construction, which is in rectangle shape: N x M. Then in the ...
import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !...
You are given array a_1, a_2, …, a_n, consisting of non-negative integers. Let's define operation of "elimination" with integer parameter k (1 ≤ k ≤ n) as follows: * Choose k distinct array indices 1 ≤ i_1 < i_2 < … < i_k ≤ n. * Calculate x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ … ~ \& ~ a_{i_k}, where \& denotes the [...
#include <bits/stdc++.h> int n, a[200011], buc[30]; int gcd(int a, int b) { return !b ? a : gcd(b, a % b); } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); for (int i = 0; i < 30; ++i) buc[i] = 0; for (int i = 1; i <= n; ++i) ...
Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of n meters depth. Now Gorf is on the bottom of the well and has a long way up. The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf...
#include <bits/stdc++.h> using namespace std; const int M = 3e5 + 5; int a[M], b[M], c, lst[M], sl[M], ans[M]; struct D { int p1, p, s; }; queue<D> q; int read() { int s = 0, t = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') t = -1; for (; isdigit(ch); ch = getchar()) s = s *...
You are given two arrays of integers a_1, a_2, …, a_n and b_1, b_2, …, b_m. You need to insert all elements of b into a in an arbitrary way. As a result you will get an array c_1, c_2, …, c_{n+m} of size n + m. Note that you are not allowed to change the order of elements in a, while you can insert elements of b at a...
#include <bits/stdc++.h> using namespace std; int a[1001000], b[1001000], buf[1001000]; long long cnt_inv(int f[], int l, int r) { if (r - l <= 1) return 0; int m = (l + r) / 2; long long ans = cnt_inv(f, l, m) + cnt_inv(f, m, r); int tl = l, tm = m, s = l; while (s < r) { if (tl < m && (tm == r || f[tl] ...
A group of n alpinists has just reached the foot of the mountain. The initial difficulty of climbing this mountain can be described as an integer d. Each alpinist can be described by two integers s and a, where s is his skill of climbing mountains and a is his neatness. An alpinist of skill level s is able to climb a...
#include <bits/stdc++.h> #pragma warning(disable : 4996) #pragma comment(linker, "/STACK:16777216") using namespace std; const int INF = 1000000000 + 1e8; const long long LINF = 2000000000000000000; struct elem { int s, a; }; void solve() { int n, d; cin >> n >> d; vector<elem> good, bad; for (int i = 0; i < ...
Students of one unknown college don't have PE courses. That's why q of them decided to visit a gym nearby by themselves. The gym is open for n days and has a ticket system. At the i-th day, the cost of one ticket is equal to a_i. You are free to buy more than one ticket per day. You can activate a ticket purchased at ...
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(0)); const long long mod = 1e9 + 7; long long fastpow(long long a, long long b) { if (b == 0) return 1; assert(b >= 0); if (b & 1) return fastpow(a, b - 1) * 1LL * a % mod; long long t = fastpow(a, b / 2); return t * 1LL * t % mod; } const long lo...
Integers from 1 to n (inclusive) were sorted lexicographically (considering integers as strings). As a result, array a_1, a_2, ..., a_n was obtained. Calculate value of (∑_{i = 1}^n ((i - a_i) mod 998244353)) mod 10^9 + 7. x mod y here means the remainder after division x by y. This remainder is always non-negative a...
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &t) { t = 0; char ch = getchar(); int f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } do { (t *= 10) += ch - '0'; ch = getchar(); } while ('0' <= ch && ch <= '9'); t *= f; } tem...
For two positive integers l and r (l ≤ r) let c(l, r) denote the number of integer pairs (i, j) such that l ≤ i ≤ j ≤ r and \operatorname{gcd}(i, j) ≥ l. Here, \operatorname{gcd}(i, j) is the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers i and j. YouKn0wWho has two ...
#include <bits/stdc++.h> #pragma GCC optimize(3) using namespace std; using ll = long long; template <class T> void read(T &x) { char ch; x = 0; int f = 1; while (isspace(ch = getchar_unlocked())) ; if (ch == '-') ch = getchar_unlocked(), f = -1; do x = x * 10 + (ch - '0'); while (isdigit(ch = getchar...
A sequence of integers b_1, b_2, …, b_m is called good if max(b_1, b_2, …, b_m) ⋅ min(b_1, b_2, …, b_m) ≥ b_1 + b_2 + … + b_m. A sequence of integers a_1, a_2, …, a_n is called perfect if every non-empty subsequence of a is good. YouKn0wWho has two integers n and M, M is prime. Help him find the number, modulo M, of ...
#include <bits/stdc++.h> template <typename _Tp> void read(_Tp &x) { char ch(getchar()); bool f(false); while (!isdigit(ch)) f |= ch == 45, ch = getchar(); x = ch & 15, ch = getchar(); while (isdigit(ch)) x = x * 10 + (ch & 15), ch = getchar(); if (f) x = -x; } template <typename _Tp, typename... Args> void...
It was October 18, 2017. Shohag, a melancholic soul, made a strong determination that he will pursue Competitive Programming seriously, by heart, because he found it fascinating. Fast forward to 4 years, he is happy that he took this road. He is now creating a contest on Codeforces. He found an astounding problem but h...
#include <bits/stdc++.h> const long long MOD = 998244353; int T, n, k, x, pow2[10000005], pw[10000005], ans; int power(int A, int B) { int res = 1; while (B) { if (B & 1) res = 1ll * res * A % MOD; B >>= 1; A = 1ll * A * A % MOD; } return res; } signed main() { std::ios::sync_with_stdio(false); ...
Shohag has an integer sequence a_1, a_2, …, a_n. He can perform the following operation any number of times (possibly, zero): * Select any positive integer k (it can be different in different operations). * Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two e...
import java.lang.Math; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; public class codeforces { public static void main(String[] args) { Scanner sc = new Scanner...
YouKn0wWho has an integer sequence a_1, a_2, … a_n. Now he will split the sequence a into one or more consecutive subarrays so that each element of a belongs to exactly one subarray. Let k be the number of resulting subarrays, and h_1, h_2, …, h_k be the lengths of the longest increasing subsequences of corresponding s...
#include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; vector<long long> a(n); for (long long i = 0; i < n; ++i) cin >> a[i]; bool sorted = true; for (long long i = 1; i < n; ++i) { if (a[i] <= a[i - 1]) sorted = false; } if (sorted and n % 2) { cout << "NO"; } els...
YouKn0wWho has an integer sequence a_1, a_2, …, a_n. He will perform the following operation until the sequence becomes empty: select an index i such that 1 ≤ i ≤ |a| and a_i is not divisible by (i + 1), and erase this element from the sequence. Here |a| is the length of sequence a at the moment of operation. Note that...
import java.util.Scanner; public class Hello { public static void main(String[] args){ Scanner r = new Scanner(System.in); int test = r.nextInt(); while(test-->0){ int n = r.nextInt(); String ans = "YES"; boolean f = true; me2: for(int i=0;i<n...
YouKn0wWho has two even integers x and y. Help him to find an integer n such that 1 ≤ n ≤ 2 ⋅ 10^{18} and n mod x = y mod n. Here, a mod b denotes the remainder of a after division by b. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints. Inp...
#include <bits/stdc++.h> using namespace std; int main() { int _TC_; cin >> _TC_; while (_TC_--) { int x, y; cin >> x >> y; if (x > y) { cout << x + y << endl; continue; } cout << (y + (y / x * x)) / 2 << endl; } }
For an array b of n integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make b non-decreasing: * Select an index i such that 1 ≤ i ≤ |b|, where |b| is the current length of b. * Replace b_i with two elements x and y such that x ...
#include <bits/stdc++.h> using namespace std; const long long maxl = 2e5 + 7; const long long mod = 998244353; vector<long long> v[2]; long long dp[2][maxl]; signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long t; cin >> t; while (t--) { long long n; cin >> n; long lon...
You are given a string s of length n consisting of characters a and/or b. Let \operatorname{AB}(s) be the number of occurrences of string ab in s as a substring. Analogically, \operatorname{BA}(s) is the number of occurrences of ba in s as a substring. In one step, you can choose any index i and replace s_i with char...
#include <bits/stdc++.h> using namespace std; template <typename t1, typename t2> using umap = unordered_map<t1, t2>; template <typename t> using uset = unordered_set<t>; struct pair_hash { template <class T1, class T2> std::size_t operator()(const std::pair<T1, T2>& p) const { auto h1 = std::hash<T1>{}(p.first...
Berland State University has received a new update for the operating system. Initially it is installed only on the 1-st computer. Update files should be copied to all n computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them usin...
import java.io.*; import java.math.BigInteger; import java.util.*; import java.lang.*; import static java.lang.Math.*; // Sachin_2961 submission // public class Codeforces { static void solve(){ long n = fs.nLong(), k = fs.nLong(); long ans = 0,cur = 1L; while( cur < k ){ cur ...
In Berland, n different types of banknotes are used. Banknotes of the i-th type have denomination 10^{a_i} burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly 1. Let's denote f(s) as the minimum number of banknotes required to represent exactly s burles. For exa...
for _ in range(int(input())): n,k = list(map(int,input().split(" "))) ls = list(map(int,input().split(" "))) p10s = [10**i for i in ls] ans = 0 used = 0 kk = k last = 1 for i,j in zip(p10s,p10s[1:]): if kk*i == j-1: ans += j + (kk-1)*i kk = 0 b...
You are given a matrix, consisting of n rows and m columns. The j-th cell of the i-th row contains an integer a_{ij}. First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue. Then, you have to choose an integer k (1 ≤ k...
#include <bits/stdc++.h> using namespace std; template <class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; } template <class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; } mt19937 rng(chrono::system_clock::now().time_since_epoch().count()); const int maxN = 1e5 + 10; int n, m; vo...
There are n heroes fighting in the arena. Initially, the i-th hero has a_i health points. The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals 1 damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than 1 at the end of t...
#include <bits/stdc++.h> using namespace std; int n, x; int f[505][505], C[505][505], pw[505][505]; void add(int &a, int b) { a += b; if (a >= 998244353) a -= 998244353; } void init() { for (int i = 0; i <= 500; i++) C[0][i] = 1; for (int i = 1; i <= 500; i++) for (int j = i; j <= 500; j++) C[i][j] = ...
You are given a tree consisting of n vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex 1. You have to process q queries. In each query, you are given a vertex of the tree v and an integer k. To process a query, you may delete any vertices from the tree in an...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC target("sse4") using namespace std; const long long N = 2e5 + 11; const long long M = 1e6 + 21; const long long big = 1e17; const long long hsh2 = 1964325029; const long long mod = 1e9 + 7; const double EPS = 1e-9; const long long block = 100; const long l...
You are given a keyboard that consists of 26 keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter. You have to type the word s on this keyboard. It also consists only of lowercase Latin letters. To type a word, you need to type all its letters...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; string wrd; cin >> wrd; int arr[200] = {}; for (int i = 0; i < s.size(); i++) { arr[s[i]] = i; } int time = 0; for (int i = 1; i < wrd.length(); i++) { time...
The grasshopper is located on the numeric axis at the point with coordinate x_0. Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate x with a distance d to the left moves the grasshopper to a point with a coordinate x - d, while jumping to the righ...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); int t; cin >> t; while (t--) { long long n, x; cin >> x >> n; if (x & 1) { if (n & 1) { if ((n / 2) & 1) x = x - n - 1; else x = x + n; } else { if (((n / 2...
Yelisey has an array a of n integers. If a has length strictly greater than 1, then Yelisei can apply an operation called minimum extraction to it: 1. First, Yelisei finds the minimal number m in the array. If there are several identical minima, Yelisey can choose any of them. 2. Then the selected minimal eleme...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> list; int max_value = INT_MIN; for (int i = 0; i < n; i++) { int temp; cin >> temp; list.push_back(temp)...
You are given an array of integers a of length n. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: * either you...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; pair<int, int> a[N]; char c[N]; int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i].first); scanf("%s", c + 1); for (int i = 1; i <= n; i++) { if (c...
The robot is located on a checkered rectangular board of size n × m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. The sequence of comma...
import sys input = sys.stdin.readline def solution(): n,m = [int(x) for x in input().strip().split()] s = input().strip() minx = 1 maxx = n miny = 1 maxy = m res = ['1','1'] updown = 0 leftright = 0 for command in s: if (command == 'U'): updown -=1 if (command == ...
The robot is located on a checkered rectangular board of size n × m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. Each cell has one of ...
#include <bits/stdc++.h> const int N = 2010; int n, m; char mp[N][N]; int a, b, d; int f[N][N]; bool vis[N][N]; bool flg; int top; std::pair<int, int> stk[N * N]; int dx[N], dy[N]; int dfs(int x, int y) { stk[++top] = std::make_pair(x, y); if (x == 0 || y == 0 || x > n || y > m) return 0; if (vis[x][y]) { flg...
A known chef has prepared n dishes: the i-th dish consists of a_i grams of fish and b_i grams of meat. The banquet organizers estimate the balance of n dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat. Technically, the balance e...
#include <bits/stdc++.h> #pragma GCC optimize(3) #pragma GCC target("avx,sse2,sse3,sse4,mmx") #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vr...
The chef has cooked n dishes yet again: the i-th dish consists of a_i grams of fish and b_i grams of meat. Banquet organizers consider two dishes i and j equal if a_i=a_j and b_i=b_j at the same time. The banquet organizers estimate the variety of n dishes as follows. The variety of a set of dishes is equal to the n...
import io,os import heapq input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline inf = 2147483647 def main(t): space = input() n = int(input()) dic = {} target = [-1]*n temp = [] for i in range(n): a,b,req = map(int,input().split()) temp.append([a,b,req]) ...
Given n, find any array a_1, a_2, …, a_n of integers such that all of the following conditions hold: * 1 ≤ a_i ≤ 10^9 for every i from 1 to n. * a_1 < a_2 < … <a_n * For every i from 2 to n, a_i isn't divisible by a_{i-1} It can be shown that such an array always exists under the constraints of the proble...
for i in range(int(input())):print(*range(2, int(input()) + 2))
You are given three integers n, a, b. Determine if there exists a permutation p_1, p_2, …, p_n of integers from 1 to n, such that: * There are exactly a integers i with 2 ≤ i ≤ n-1 such that p_{i-1} < p_i > p_{i+1} (in other words, there are exactly a local maximums). * There are exactly b integers i with 2 ≤ i ≤...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static String nextToken() { try { ...
n players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to org...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; int n; while (t--) { cin >> n; vector<pair<pair<long long int, long long int>, int> > Data(n); for (int i = 0; i < n; i++) cin >> Data[i].first.first; for (int i = 0; ...
You are given n dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet. The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each 1 ≤ i ≤ n the color of the ...
#include <bits/stdc++.h> using namespace std; char ch[100010][5]; const int mod = 998244353; int fac[200010], facinv[200010]; long long qpow(long long a, long long b) { long long m = 1; while (b) { if (b & 1) m = m * a % mod; b >>= 1; a = a * a % mod; } return m; } void init(int x) { fac[0] = 1; ...
On an endless checkered sheet of paper, n cells are chosen and colored in three colors, where n is divisible by 3. It turns out that there are exactly n/3 marked cells of each of three colors! Find the largest such k that it's possible to choose k/3 cells of each color, remove all other marked cells, and then select ...
#include <bits/stdc++.h> using namespace std; int gi() { int x = 0, c = getchar(); bool f = 0; for (; !isdigit(c); c = getchar()) if (c == '-') f = 1; for (; isdigit(c); c = getchar()) x = x * 10 + (c & 15); return f ? -x : x; } constexpr int N = (int)1e5 + 5; int n, x[N], y[N], c[N], _n, _m; vector<int> ...
For an array c of nonnegative integers, MEX(c) denotes the smallest nonnegative integer that doesn't appear in it. For example, MEX([0, 1, 3]) = 2, MEX([42]) = 0. You are given integers n, k, and an array [b_1, b_2, …, b_n]. Find the number of arrays [a_1, a_2, …, a_n], for which the following conditions hold: * 0...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { x = (x << 3) + (x << 1) + (c ^ 48); c = getchar(); } return f == -1 ? ~x + 1 : x; } int n, k; int b[2010...
You are given m strings and a tree on n nodes. Each edge has some letter written on it. You have to answer q queries. Each query is described by 4 integers u, v, l and r. The answer to the query is the total number of occurrences of str(u,v) in strings with indices from l to r. str(u,v) is defined as the string that i...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10, M = 6e5 + 10; int n, m, q, k, head[N], tot, st[M], ed[M], ans[N]; char s[M]; struct node { int to, nxt; char c; } e[N << 1]; void add(int x, int y, char c) { e[++k].to = y; e[k].nxt = head[x]; head[x] = k; e[k].c = c; } namespace SA { int...
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer x with p zeros appended to its end. Now Monocarp asks you to compare these two numbers. Can you help him? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases. The first li...
import java.io.*; import java.util.*; public class Aqueous { static MyScanner sc = new MyScanner(); public static void main(String[] args){ int t = sc.nextInt(); while(t-->0) { String x1 = sc.next(); int n1 = sc.nextInt(); String x2 =sc.next(); int n2 = sc.nextInt...
You are given a sequence a_1, a_2, ..., a_n consisting of n pairwise distinct positive integers. Find \left⌊ \frac n 2 \right⌋ different pairs of integers x and y such that: * x ≠ y; * x and y appear in a; * x~mod~y doesn't appear in a. Note that some x or y can belong to multiple pairs. ⌊ x ⌋ denotes t...
#include <bits/stdc++.h> using namespace std; void solve() { long long int n, i; cin >> n; long long int a[n]; for (i = 0; i < n; i++) cin >> a[i]; ; sort(a, a + n); for (i = 1; i < n / 2 + 1; i++) cout << a[i] << " " << a[0] << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); ...
Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts 100^{500} seconds, during which Monocarp attacks the dragon with a poisoned dagger. The i-th attack is performed at the beginning of the a_i-th second from the battle start. The dagger itsel...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const long long int llINF = (long long)(1e18) + 100; const int MAXN = 4e5 + 10; long long int n, a[200], h; bool test(long long int val) { long long int hp = h; for (int i = 0; i < n - 1; i++) { long long int aux = min(val, a[i + 1] - a[i...
Let's call a sequence of integers x_1, x_2, ..., x_k MEX-correct if for all i (1 ≤ i ≤ k) |x_i - \operatorname{MEX}(x_1, x_2, ..., x_i)| ≤ 1 holds. Where \operatorname{MEX}(x_1, ..., x_k) is the minimum non-negative integer that doesn't belong to the set x_1, ..., x_k. For example, \operatorname{MEX}(1, 0, 1, 3) = 2 an...
import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import javax.security.auth.login.AccountExpiredException; import javax.swing.text.Segment; import java.io.*; import java.math.*; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; public class Main { private static...
There is a grid, consisting of n rows and m columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked. A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the foll...
# pylint: disable=unused-variable # pylint: enable=too-many-lines # * Just believe in yourself # $ Author @CAP # import numpy import os import sys from io import BytesIO, IOBase import math as M import itertools as ITR from collections import defaultdict as D from collections import Counter as C from collections im...
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is the vertex 1. You have to color all vertices of the tree into n colors (also numbered from 1 to n) so that there is exactly one vertex for each color. Let c_i be the color of vertex i, and p_i be the parent of vertex i i...
#include <bits/stdc++.h> using namespace std; const int G = 3; const int Gi = 332748118; long long su(long long a, long long b) { a += b; return (a >= 998244353) ? a - 998244353 : a; } int r[300000], lim; long long ksm(long long a, long long p) { long long res = 1; while (p) { if (p & 1) { res = res *...
There are n block towers in a row, where tower i has a height of a_i. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: * Choose two indices i and j (1 ≤ i, j ≤ n; i ≠ j), and move a block from tower i to tower j. Th...
# -*- coding: UTF-8 -*- t = int(input()) inputdata = [] for i in range(t): input() inputdata.append(input().split(" ")) for j in range(len(inputdata[i])): inputdata[i][j] = int(inputdata[i][j]) for i in range(t): res = 0 l = len(inputdata[i]) ost = sum(inputdata[i]) % l while(ost > 0...
You are given an array consisting of all integers from [l, r] inclusive. For example, if l = 2 and r = 5, the array would be [2, 3, 4, 5]. What's the minimum number of elements you can delete to make the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the array non-zero? A bitwise AND is a binary...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
There are n candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string s, where the i-th candle is lit if and only if s_i=1. <image> Initially, the candle lights are described by a string a. In an operation, you select a candle that is currentl...
// हर हर महादेव import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; public final class Solution { static int inf = Integer.MAX_VALUE; static long mod = 1000000000 + 7; static void ne(Scanner sc, BufferedWriter op) throws Exception { ...
'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are n nodes in the tree, connected by n-1 edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation. <image> He has m elves come over and admire ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class d { static final int LOG=30; public static void main(String[] args)...
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game. The game works as follows: there is a tree of size n, rooted at node 1, where each node is initially white. Red and Blue...
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); return 0; } const int inf = 2e9; const long long linf = 2e18; const long long mod = 998244353; const int N = 2e5 + 100; vector<int> g[N]; struct Elem { int value, node, po...
After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height 1 and length n, some positions of which are occupied by 1 by 1 Lego pieces. In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Le...
#include <bits/stdc++.h> using namespace std; const long long P = 1e9 + 7; const int N = 2005; const long long INF = (1ll << 62) - 1; const double pi = acos(-1); mt19937 rng(time(0)); int T, n; int f[N][N * 2], g[N][N * 2]; char s[N], t[N]; void revbit(char s[]) { for (int i = 2; i <= n; i += 2) if (s[i] != '?') ...
You are given an array a consisting of n non-negative integers. You have to replace each 0 in a with an integer from 1 to n (different elements equal to 0 can be replaced by different integers). The value of the array you obtain is the number of integers k from 1 to n such that the following condition holds: there ex...
#include <bits/stdc++.h> using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; template <class A, class B> bool smin(A &x, B &&y) { if (y < x) { x = y; return true; } return false; } template <class A, class B> bool smax(A &x, B &&y) { if (x < y) { x =...
There are n reindeer at the North Pole, all battling for the highest spot on the "Top Reindeer" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the "Top Reindeer" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer g...
#include <bits/stdc++.h> using namespace std; const int Maxn = 2005; int n, m, s, t, cnt, x[Maxn], y[Maxn], dis[Maxn], head[Maxn], cur[Maxn], a[Maxn]; bool vis[Maxn]; vector<int> G[Maxn]; struct edg { int nxt, to, w; } edge[2 * Maxn]; void add(int x, int y, int w) { edge[++cnt] = (edg){head[x], y, w}; head[x]...
You are given strings S and T, consisting of lowercase English letters. It is guaranteed that T is a permutation of the string abc. Find string S', the lexicographically smallest permutation of S such that T is not a subsequence of S'. String a is a permutation of string b if the number of occurrences of each distin...
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int x =Integer.parseInt(scan.nextLine()); while(x-->0) { String s=scan.nextLine(); String t=scan.nextLine(); // System.out.println(s+" "+t); ...
Given a positive integer n. Find three distinct positive integers a, b, c such that a + b + c = n and \operatorname{gcd}(a, b) = c, where \operatorname{gcd}(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y. Input The input consists of multipl...
def main(): for _ in range(int(input())): n = int(input()) if n%2 == 0: print(2, n-2-1,1) else: n-=1 n=n//2 if n%2 ==0: print(n-1,n+1,1) else: print(n-2,n+2,1) main()
Paprika loves permutations. She has an array a_1, a_2, ..., a_n. She wants to make the array a permutation of integers 1 to n. In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers i (1 ≤ i ≤ n) and x (x > 0), then perform a_i := a_i mod x (that is, repla...
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class hello{ static class Pair implements Comparable<Pair>{ long val; long ind; public Pair(long val,long ind) { this.val=val; ...
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions. There are n players labelled from 1 to n. It is guaranteed that n is a multiple of 3. Among them, there are k impostors and n-k crewmates. The number of impostors, k, is not given to you. It is g...
#include <bits/stdc++.h> using namespace std; int ask(int a, int b, int c) { cout << "? " << a + 1 << " " << b + 1 << " " << c + 1 << endl; int r; cin >> r; return r; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; int q[n]; fill(q, q + n, -1); int one = -1, zero = -1; ...
Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains n chocolates. The i-th chocolate has a non-negative integer type a_i. Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all a_i are distinct). Icy wants to make at leas...
#include <bits/stdc++.h> const double PI = 3.1415926535897932384626433; using namespace std; struct edge { long long to, cost; edge() {} edge(long long a, long long b) { to = a, cost = b; } }; const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1}; const int mod = 1000000007; struct mint { int x; mint(long long...
Polycarp had an array a of 3 positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array b of 7 integers. For example, if a = \{1, 4, 3\}, then Polycarp wrote out 1, 4, 3, 1 + 4 = 5, 1 + 3 = 4, 4 + 3 = 7, 1 + 4 + 3 = 8. After sorting, he g...
t = int(input()) for i in range(t): k=[] z=[] a = list(map(int, input().split()[:7])) a.sort() k = a[-1]-(a[0]+a[1]) z = [str(a[0]), str(a[1])] a.pop(0) a.pop(0) for i in a: if i==k: z.append(str(i)) break print(" ".join(z))
Polycarp has come up with a new game to play with you. He calls it "A missing bigram". A bigram of a word is a sequence of two adjacent letters in it. For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba". The game goes as follows. First, Polycarp comes up with a word, consisting only of...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5; long long int ar[N], br[N], l[N], r[N]; int parent[1000]; int main() { int tt; cin >> tt; while (tt--) { int n; cin >> n; vector<string> v; n = n - 2; for (int i = 1; i <= n; i++) { string s; cin >> s; v.pus...
You are given an array a consisting of n positive integers. You have to choose a positive integer d and paint all elements into two colors. All elements which are divisible by d will be painted red, and all other elements will be painted blue. The coloring is called beautiful if there are no pairs of adjacent elements...
from collections import Counter, defaultdict import math import bisect def getlist(): return list(map(int, input().split())) def compute_gcd(x, y): while(y): x, y = y, x % y return x def maplist(): return map(int, input().split()) def main(): t = int(input()) for num in range(t): ...
You are given an array a of n integers, and another integer k such that 2k ≤ n. You have to perform exactly k operations with this array. In one operation, you have to choose two elements of the array (let them be a_i and a_j; they can be equal or different, but their positions in the array must not be the same), remo...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> ar(n); for (int i = 0; i < n; i++) { cin >> ar[i]; } sort(ar.begin(), ar.end()); long long int ans = 0; for (int i = 0; i < n - k; i++) { if (i...
n towns are arranged in a circle sequentially. The towns are numbered from 1 to n in clockwise order. In the i-th town, there lives a singer with a repertoire of a_i minutes for each i ∈ [1, n]. Each singer visited all n towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each...
T = int(input()) for _ in range(T): n = int(input()) B = [int(i) for i in input().split()] m = n*(n+1)//2 if sum(B) % m != 0: print("NO") else: A = sum(B)//m ans = [] for i, j in zip(B, B[1:] + [B[0]]): ans += [(A + i - j)/n] if any(int(x...
You are given two positive integers x and y. You can perform the following operation with x: write it in its binary form without leading zeros, add 0 or 1 to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of x. For example: * 34 can be turned into 81 v...
#import io,os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import deque def main(t): x, y = map(int,input().split()) sx, sy = bin(x)[2:],bin(y)[2:] dic = {} queue = deque() queue.append(sx) dic[sx] = 1 i = len(sx)-1 while i>=0 and sx[i]=='0': ...
Monocarp plays a computer game (yet again!). This game has a unique trading mechanics. To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price x, then he can trade it fo...
from itertools import accumulate class Dsu: def __init__(self, n): self.f = list(range(n)) def find(self, x): if self.f[x] != x: self.f[x] = self.find(self.f[x]) return self.f[x] def union(self, i, j, cnt, psum, maxv): fi, fj = self.find(i), self.find(j) ...
A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square. For a given string s determine if it is square. Input The first line of input data contains an integer t (1 ≤ t...
#include <bits/stdc++.h> using namespace std; int main() { int t, s, d; cin >> t; while (t--) { int count = 0; string a; cin >> a; s = a.size(); d = s / 2; if (s % 2 == 1) { cout << "no" << endl; } else { for (int i = 0; i < d; i++) { if (a[i] != a[i + d]) { ...
Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: 1, 4, 8, 9, .... For a given number n, count the number of integers from 1 to n that Polycarp likes. In other words, find the number of such x that x is a square of a positive integer number or a cube of a...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { long n=sc.nextLong(); long ans=(long)Math.sqrt(n)+(long)Math.cbrt(n)-(long)Math.sqrt(Math.cbrt(n)); System.out.println(ans); } } }
Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers a and b using the following algorithm: 1. If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length. 2. The numbers are processed from right to left (th...
#include <bits/stdc++.h> using namespace std; string solve() { string a, s, b = ""; cin >> a >> s; reverse(a.begin(), a.end()); reverse(s.begin(), s.end()); int k = 0; for (int i = 0; i < a.size(); i++) { if (i + k >= s.size()) { return "-1"; } if (a[i] == s[i + k]) { b = "0" + b; ...
Vlad has n friends, for each of whom he wants to buy one gift for the New Year. There are m shops in the city, in each of which he can buy a gift for any of his friends. If the j-th friend (1 ≤ j ≤ n) receives a gift bought in the shop with the number i (1 ≤ i ≤ m), then the friend receives p_{ij} units of joy. The re...
#include <bits/stdc++.h> using namespace std; double PI = (acos(-1)); long long md = 1000000007; long long pw(long long a, long long b) { long long c = 1, m = a; while (b) { if (b & 1) c = (c * m); m = (m * m); b /= 2; } return c; } long long pwmd(long long a, long long b) { long long c = 1, m = a...
Dmitry has an array of n non-negative integers a_1, a_2, ..., a_n. In one operation, Dmitry can choose any index j (1 ≤ j ≤ n) and increase the value of the element a_j by 1. He can choose the same index j multiple times. For each i from 0 to n, determine whether Dmitry can make the MEX of the array equal to exactly ...
from typing import Counter def find(arr: list, n): res = [-1]*(n+1) count = [0]*(n+1) maxx = 0 maxxx = 0 d = 0 for i in range(n): count[arr[i]] += 1 if count[0] < 1: res[0] =0 return res res[0] = count[0] for i in range(1,n+1): d = 0 res[i] =...
The Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play). n people gathered in a room with m tables (n ≥...
def solve(): n, m, k = readIntArr() # assume n % m != 0 smallPeople = n // m # number of people at smallTable largePeople = smallPeople + 1 smallTable = largePeople * m - n # number of small Tables largeTable = m - smallTable ans = [] largeIdx = 0 for roundd in range(k): ...
Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules. There are mines on the field, for each the coordinates of its location are known (x_i, y_i). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates a...
#include <bits/stdc++.h> using namespace std; char BB[1 << 16], *SB = BB, *TB = BB; template <typename T> void read(T &n) { T w = 1; n = 0; char ch = (SB == TB && (TB = (SB = BB) + fread(BB, 1, 1 << 15, stdin), SB == TB) ? EOF : *SB++); while (!isdigit(ch)) { if (ch == '-') w = -...
You are given a permutation p of n elements. A permutation of n elements is an array of length n containing each integer from 1 to n exactly once. For example, [1, 2, 3] and [4, 3, 5, 1, 2] are permutations, but [1, 2, 4] and [4, 3, 2, 1, 2] are not permutations. You should perform q queries. There are two types of qu...
import sys raw_input = iter(sys.stdin.read().splitlines()).next class Node(object): def __init__(self, v): self.v = v self.children = [None]*2 self.parent = None self.size = 1 def pull(self): self.size = 1 if self.children[0]: self.size += self.child...
You had n positive integers a_1, a_2, ..., a_n arranged in a circle. For each pair of neighboring numbers (a_1 and a_2, a_2 and a_3, ..., a_{n - 1} and a_n, and a_n and a_1), you wrote down: are the numbers in the pair equal or not. Unfortunately, you've lost a piece of paper with the array a. Moreover, you are afraid...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringJoiner; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ...
A rectangle with its opposite corners in (0, 0) and (w, h) and sides parallel to the axes is drawn on a plane. You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle. Your task is to choose three...
import java.util.*; import java.io.*; import java.lang.*; // Problem - Multiples of 3 onn codeforces MNedium difficulty level // or check on youtube channel CodeNCode public class Problem { static int Mod = 1000000007; static long dp[][]; static int g[][]; static int fact[]; public static void...
You are given an integer k and a string s that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk). Each asterisk should be replaced with several (from 0 to k inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'. The result of the ...
def solution(n, k, x, s): current_len = 0 astrics = [] for c in s: if c == '*': current_len += 1 elif c == 'a': if current_len != 0: astrics.append(current_len) current_len = 0 if current_len != 0: astrics.append(current_len) ...
One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of n different flavors. A bag of the i-th flavor costs a_i burles. The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan...
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int answer = 1e9; for (int x = 0; x <= 2; x++) { for (int y = 0; y <= 2; y++) { int result = 0; for (int i = 0; i < n; i++) { int tmp = 1...
You have an array of integers (initially empty). You have to perform q queries. Each query is of one of two types: * "1 x" — add the element x to the end of the array; * "2 x y" — replace all occurrences of x in the array with y. Find the resulting array after performing all the queries. Input The first l...
from collections import * import sys import io, os import math from heapq import * gcd = math.gcd sqrt = math.sqrt def ceil(a, b): a = -a k = a // b k = -k return k # arr=list(map(int, input().split())) input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def strinp(testcases): k = 5 if ...
You are given a permutation p consisting of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once). Let's call an array a bipartite if the following undirected graph is bipartite: * the graph consists of n vertices; * two vertices i and j are connected by an edge i...
#include <bits/stdc++.h> using namespace std; long long a[1000005], dp[1000005][2]; signed main() { ios::sync_with_stdio(false); cin.tie(0); long long T; cin >> T; while (T--) { long long n; cin >> n; for (long long i = 1; i <= n; i++) cin >> a[i]; a[0] = 1e9, dp[0][0] = -1e9; for (long lo...
For a sequence of strings [t_1, t_2, ..., t_m], let's define the function f([t_1, t_2, ..., t_m]) as the number of different strings (including the empty string) that are subsequences of at least one string t_i. f([]) = 0 (i. e. the number of such strings for an empty sequence is 0). You are given a sequence of string...
#include <bits/stdc++.h> using namespace std; long long mod = 998244353; long double pi = 3.141592653589793238; void pls() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int dp[(1 << 23)]; int arr[23][26]; int mul(long long a, long long b) { return (a % mod * b % mod) % mod; } void solve() { { i...
There are three sticks with integer lengths l_1, l_2 and l_3. You are asked to break exactly one of them into two pieces in such a way that: * both pieces have positive (strictly greater than 0) integer length; * the total length of the pieces is equal to the original length of the stick; * it's possible to ...
import java.io.*; import java.util.*; /* */ public class A{ static FastReader sc=null; public static void main(String[] args) { sc=new FastReader(); int t=sc.nextInt(); for(int tt=0;tt<t;tt++) { int s[]=sc.readArray(3); ruffleSort(s); if((s[0]+s[1]+s[2])%2==1) { System.out.println...
Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module. So imagine Monocarp got recommended n songs, numbered from 1 to n. The i-th song had its predicted rating equal to p_i, where 1 ≤ p_i ≤ n and every intege...
for i in range(int(input())): n, p, s = int(input()), [int(i) for i in input().split()], input() p = sorted(zip(s, p, range(n))) w = [0] * n for i in range(n): w[p[i][2]] = i + 1 print(*w) zip()
You are given an integer array a_1, a_2, ..., a_n and integer k. In one step you can * either choose some index i and decrease a_i by one (make a_i = a_i - 1); * or choose two indices i and j and set a_i equal to a_j (make a_i = a_j). What is the minimum number of steps you need to make the sum of array ∑_{...
import sys import os.path from collections import * import math import bisect import heapq as hq from fractions import Fraction from random import randint if os.path.exists("input.txt"): sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") input = sys.stdin.readline #######################...
You are given a binary string (i. e. a string consisting of characters 0 and/or 1) s of length n. You can perform the following operation with the string s at most once: choose a substring (a contiguous subsequence) of s having exactly k characters 1 in it, and shuffle it (reorder the characters in the substring as you...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 9; const long long MOD = 1e9 + 7; const int mod = 998244353; inline long long qpow(long long b, long long e, long long m) { long long a = 1; for (; e; e >>= 1, b = b * b % m) if (e & 1) a = a * b % m; return a; } long long exgcd(long long a,...
Petya is a math teacher. n of his students has written a test consisting of m questions. For each student, it is known which questions he has answered correctly and which he has not. If the student answers the j-th question correctly, he gets p_j points (otherwise, he gets 0 points). Moreover, the points for the quest...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* e = expected, a = actual e_1 - a_1 a_2 - e_2 e_3 ...
Let's call a set of positive integers a_1, a_2, ..., a_k quadratic if the product of the factorials of its elements is a square of an integer, i. e. ∏_{i=1}^{k} a_i! = m^2, for some integer m. You are given a positive integer n. Your task is to find a quadratic subset of a set 1, 2, ..., n of maximum size. If there a...
#include <bits/stdc++.h> using ULL = unsigned long long; std::vector<int> spfS(int N) { std::vector<int> sp(N); std::iota(sp.begin(), sp.end(), 0); for (int i = 2; i * i < N; ++i) if (sp[i] == i) { for (int j = i * i; j < N; j += i) if (sp[j] == j) { sp[j] = i; } } return...
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th ...
import java.io.*; public class CP { static void giveTime(int n, int m, int rb, int cb, int rd, int cd){ boolean colForward = true; boolean rowForward = true; int time = 0; while((rb!=rd)&&(cb!=cd)){ if((rb==n)&&(rowForward)){ rowForward = false; ...
Alice and Bob play the following game. Alice has a set S of disjoint ranges of integers, initially containing only one range [1, n]. In one turn, Alice picks a range [l, r] from the set S and asks Bob to pick a number in the range. Bob chooses a number d (l ≤ d ≤ r). Then Alice removes [l, r] from S and puts into the s...
# from operator import itemgetter t = int(input()) for _ in range(t): n = int(input()) a = [] for i in range(n): x,y = map(int,input().split()) d = y-x a.append([d,x,y]) a.sort(reverse = True) for i in range(n): mx = 0 for j in range(i+1,n): ...
There are n heaps of stone. The i-th heap has h_i stones. You want to change the number of stones in the heap by performing the following process once: * You go through the heaps from the 3-rd heap to the n-th heap, in this order. * Let i be the number of the current heap. * You can choose a number d (0 ≤ 3 ⋅...
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using PII = pair<long long, long long>; using VI = vector<long long>; string to_string(string s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true...
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different. A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are num...
#include <bits/stdc++.h> using namespace std; const int N = 2e6 + 5, M = 2e3 + 5, mod = 1e9 + 7; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) +...
A binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not ...
#include <bits/stdc++.h> const int N = 200005; int n, k, rem; char c[N]; int ls[N], rs[N], fa[N]; int cst[N]; int from[N]; bool vis[N], coled[N]; void dfs(int x, int &tt) { if (!x) return; dfs(ls[x], tt), from[++tt] = x, dfs(rs[x], tt); return; } inline void add(int x) { for (int i = 1; x; x = ls[x], ++i) cst[x...
Three little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the n-th minute, the convention ends. The big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and e...
#include <bits/stdc++.h> using namespace std; vector<long long> inverses(int n, int P) { vector<long long> inv(n + 1, 1); for (int i = 2; i <= n; ++i) inv[i] = inv[P % i] * (P - P / i) % P; return inv; } const int mod = 1e9 + 7; namespace combi { const int N = 3e6 + 10; int fac[N], ifac[N]; void init() { fac[0]...