input
stringlengths
29
13k
output
stringlengths
9
73.4k
This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even. There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of cows on the plane, one at ev...
#include <bits/stdc++.h> using namespace std; int cnt[2][2]; int main() { int n, i, j, k; scanf("%d", &n); for (i = 1; i <= n; i++) { int x, y; scanf("%d%d", &x, &y); x >>= 1; y >>= 1; cnt[x & 1][y & 1]++; } long long ans = 0; for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) { k...
This is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be both odd and even. There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of cows on the ...
#include <bits/stdc++.h> using namespace std; inline int read() { int s = 0, w = 1, ch = getchar(); while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); } while (isdigit(ch)) { s = (s << 3) + (s << 1) + ch - 48; ch = getchar(); } return s * w; } const int maxn = 6050; int n, x[maxn]...
Two painters, Amin and Benj, are repainting Gregor's living room ceiling! The ceiling can be modeled as an n Γ— m grid. For each i between 1 and n, inclusive, painter Amin applies a_i layers of paint to the entire i-th row. For each j between 1 and m, inclusive, painter Benj applies b_j layers of paint to the entire j-...
#include <bits/stdc++.h> using namespace std; template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string...
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them. Gregor's favorite prime number is P. Gregor wants to find two bases of P. Formally, Gregor is looking for two integers a and b which satisfy both of the following pro...
#include <bits/stdc++.h> int main() { int t; scanf("%d", &t); long long int array[t]; for (int i = 0; i < t; i++) { scanf("%lld", &array[i]); } for (int i = 0; i < t; i++) { printf("%d %lld\n", 2, array[i] - 1); } }
There is a chessboard of size n by n. The square in the i-th row from top and j-th column from the left is labelled (i,j). Currently, Gregor has some pawns in the n-th row. There are also enemy pawns in the 1-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from (i,j) to (i-1,j)) if t...
for _ in range(int(input())): n = int(input()) s = list(map(int,list(input()))) m = list(map(int,list(input()))) ans = 0 if m[0] == 1: if s[0]==0: ans +=1 elif s[1] == 1: ans +=1; s[1] = 2 for x in range(1, n): if m[x] == 1: if s[x] == 0: ans +...
When you play the game of thrones, you win, or you die. There is no middle ground. Cersei Lannister, A Game of Thrones by George R. R. Martin There are n nobles, numbered from 1 to n. Noble i has a power of i. There are also m "friendships". A friendship between nobles a and b is always mutual. A noble is defined to...
import java.io.*; import java.util.*; public class C { static TreeSet<Integer> g[]; public static void main(String[] args) { FastReader f = new FastReader(); StringBuffer sb=new StringBuffer(); // int test=f.nextInt(); // out: // while(test-->0) // { //leaves which are bigger than thier parents ...
British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends." It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}...
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,mod1=998244353l,inf=(long)1e18+5; // 1111111999999, 311111111111113 static void solve1() throws IOException{ int n=int_v(read()); long[] a=long_arr(); ...
Polycarp must pay exactly n burles at the checkout. He has coins of two nominal values: 1 burle and 2 burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other. Thus, Polycarp wants to minimize the difference between the count of coins of 1 burle and ...
t = int(input()) for _ in range(t): n = int(input()) c1,c2 = 0,0 if n%3==0: c1 = n//3 c2 = n//3 elif n%3==1: c1 = (n+2)//3 c2 = c1-1 else: c2 = (n+1)//3 c1 = c2-1 print(c1,c2)
This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1. Paul and Mary have a favorite string s which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a stri...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class A extends Thread { static class FastReader { BufferedReader br; StringTokeniz...
This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely. Recently, Paul and Mary have found a new favorite sequence of integers a_1, a_2, ..., a_n. They want to paint it using pieces of chalk of k colors. The coloring of a sequen...
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; vector<int> a(n); vector<int> res(n); for (int &x : a) cin >> x; vector<vector<int>> pos(n + 1); for (int i = 0; i < n; i++) { pos[a[i]].push_back(i); } vector<vector<int>> b; for (int i = 1; i <= n; i++) { ...
Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'! To compose a story, Stephen wrote out n words consisting of the first 5 lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story. Let a story ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWri...
The only difference between this problem and D2 is that you don't have to provide the way to construct the answer in this problem, but you have to do it in D2. There's a table of n Γ— m cells (n rows and m columns). The value of n β‹… m is even. A domino is a figure that consists of two cells having a common side. It ma...
import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(t): m,n,k = map(int,input().split()) # if m==1: # if k==m*n//2: print("YES") # else: print("NO") # return # if n==1: # if k==0: print("YES") # else: print("NO") # return ...
The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem. There's a table of n Γ— m cells (n rows and m columns). The value of n β‹… m is even. A domino is a figure that consists of two cells having a common side. It ma...
# Author: $%U%$ # Time: $%Y%$-$%M%$-$%D%$ $%h%$:$%m%$:$%s%$ import io import os import collections import math import functools import itertools import bisect import heapq from sys import stdin, stdout, stderr from collections import * from math import * from functools import * from itertools import * from heapq impor...
Consider a sequence of integers a_1, a_2, …, a_n. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by 1 position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases b...
#include <bits/stdc++.h> using namespace std; const long long maxn = 2e5 + 50; long long n, dp[maxn], k, a[maxn], b[maxn], tp[maxn]; void solve() { for (long long i = 1; i <= n; i++) b[i] = i - a[i]; long long pos = 1, ans = 1e18; for (long long i = 1; i <= n; i++) { dp[i] = (b[i] >= 0); for (long long j ...
A tree is an undirected connected graph without cycles. You are given a tree of n vertices. Find the number of ways to choose exactly k vertices in this tree (i. e. a k-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer c such tha...
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class T> vector<T> make_unique(vector<T> a) { sort((a).begin(), (a).end()); a.erase(unique((a).begin(), (a).end()), a.end()); return a; } const int INF = 1e9; const int MOD = 1e9 + 7; co...
A string s of length n, consisting of lowercase letters of the English alphabet, is given. You must choose some number k between 0 and n. Then, you select k characters of s and permute them however you want. In this process, the positions of the other n-k characters remain unchanged. You have to perform this operation...
for _ in range(int(input())): n=int(input()) s=list(input().strip()) temp2=sorted(s) count=0 for i in range(n): if s[i]!=temp2[i]: count+=1 print(count)
The Olympic Games have just started and Federico is eager to watch the marathon race. There will be n athletes, numbered from 1 to n, competing in the marathon, and all of them have taken part in 5 important marathons, numbered from 1 to 5, in the past. For each 1≀ i≀ n and 1≀ j≀ 5, Federico remembers that athlete i r...
#include <bits/stdc++.h> using namespace std; const long long int M = 10000000007; long long int binarySearch(vector<long long int> arr, long long int l, long long int r, long long int x) { if (r >= l) { long long int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr...
On a circle lie 2n distinct points, with the following property: however you choose 3 chords that connect 3 disjoint pairs of points, no point strictly inside the circle belongs to all 3 chords. The points are numbered 1, 2, ..., 2n in clockwise order. Initially, k chords connect k pairs of points, in such a way...
def ch(x,y): if (y[0]<x[0]<y[1] and not(y[0]<x[1]<y[1])) or (y[0]<x[1]<y[1] and not(y[0]<x[0]<y[1])): return 1 return 0 t = int(input()) for i in range(t): n, k = [int(i) for i in input().split()] m = [] use = [0]*(2*n+1) for j in range(k): l,r = [int(i) for i in input().sp...
You are given a sequence of n integers a_1, a_2, ..., a_n. Does there exist a sequence of n integers b_1, b_2, ..., b_n such that the following property holds? * For each 1 ≀ i ≀ n, there exist two (not necessarily distinct) indices j and k (1 ≀ j, k ≀ n) such that a_i = b_j - b_k. Input The first ...
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import itertools t = int(input()) for _ in range(t): n = int(input()) A = list(map(int, input().split())) flag = False x = tuple([0]*n) for p in itertools.product(range(-1, 2), repeat=n): if p == x: ...
The numbers 1, 2, ..., n β‹… k are colored with n colors. These colors are indexed by 1, 2, ..., n. For each 1 ≀ i ≀ n, there are exactly k numbers colored with color i. Let [a, b] denote the interval of integers between a and b inclusive, that is, the set \\{a, a + 1, ..., b\}. You must choose n int...
#include <bits/stdc++.h> using namespace std; const long long N = 105, K = 105; const long long oo = 1e18 + 7, mod = 1e9 + 7; long long n, k, a[N * K]; bool ok[N * K], ok2[N * K]; long long lst[N * K]; pair<long long, long long> ans[N * K]; long long sum[N * K]; void process() { cin >> n >> k; for (long long i = 1;...
An ant moves on the real line with constant speed of 1 unit per second. It starts at 0 and always moves to the right (so its position increases by 1 each second). There are n portals, the i-th of which is located at position x_i and teleports to position y_i < x_i. Each portal can be either active or inactive. The ini...
#include <bits/stdc++.h> using namespace std; int n; const int mod = 998244353; struct wocao { int x, y, s; } a[200020]; int aa[400040]; map<int, int> mp; int bb[400040]; int c[400040]; int lowbit(int x) { return x & (-x); } int query(int x) { int ret = 0; while (x) (ret += c[x]) %= mod, x -= lowbit(x); return ...
Andrea has come up with what he believes to be a novel sorting algorithm for arrays of length n. The algorithm works as follows. Initially there is an array of n integers a_1, a_2, ..., a_n. Then, k steps are executed. For each 1≀ i≀ k, during the i-th step the subsequence of the array a with indexes j_{i,1}< j_{i...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") using namespace std; using Int = long long; template <class T1, class T2> ostream &operator<<(ostream &os, const pair<T1, T2> &a) { return os << "(" << a.first << ", " << a.second << ")"; }; template <class T> void pv(T a, T b...
You are the organizer of the famous "Zurich Music Festival". There will be n singers who will perform at the festival, identified by the integers 1, 2, ..., n. You must choose in which order they are going to perform on stage. You have m friends and each of them has a set of favourite singers. More precisely, for eac...
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); ...
Let's define S(x) to be the sum of digits of number x written in decimal system. For example, S(5) = 5, S(10) = 1, S(322) = 7. We will call an integer x interesting if S(x + 1) < S(x). In each test you will be given one integer n. Your task is to calculate the number of integers x such that 1 ≀ x ≀ n and x is interest...
x=int(input()) for i in range(x): y=int(input()) print((y+1)//10)
You have a string s and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i + 1. Of course, moving th...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
Consider a simplified penalty phase at the end of a football match. A penalty phase consists of at most 10 kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of...
#----------FASTIOSTART-----------# from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 d...
You are given two strings s and t, both consisting of lowercase English letters. You are going to type the string s character by character, from the first character to the last one. When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last ch...
import java.util.Scanner; public class CF1553D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int test = scanner.nextInt(); scanner.nextLine(); StringBuilder result = new StringBuilder(); for (int t = 0; t < test; t++){ Stri...
An identity permutation of length n is an array [1, 2, 3, ..., n]. We performed the following operations to an identity permutation of length n: * firstly, we cyclically shifted it to the right by k positions, where k is unknown to you (the only thing you know is that 0 ≀ k ≀ n - 1). When an array is cyclically shi...
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { FastReader s = new FastReader(); PrintWriter out = new PrintWriter(System.out); Main main = new Main(); int t = s.nextInt(); while(t > 0) { int n = s.nextInt(); ...
You have an array a consisting of n distinct positive integers, numbered from 1 to n. Define p_k as $$$p_k = βˆ‘_{1 ≀ i, j ≀ k} a_i mod a_j, where x \bmod y denotes the remainder when x is divided by y. You have to find and print p_1, p_2, \ldots, p_n$$$. Input The first line contains n β€” the length of the array (2 ≀ ...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const long long MAX = 300010; const long long MOD = (long long)1e9 + 7; const long long INF = 1e9; const long long LLINF = 0x3f3f3f3f3f3f3f3f; const long double EPS = 1e-8; struct Segtree { vector<long l...
Consider a sequence of distinct integers a_1, …, a_n, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than 1. There are q queries, in each query, you want to get from one given node a_s to another a_t. In order to ach...
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file....
You are given an array a consisting of n distinct elements and an integer k. Each element in the array is a non-negative integer not exceeding 2^k-1. Let's define the XOR distance for a number x as the value of $$$f(x) = min_{i = 1}^{n} min_{j = i + 1}^{n} |(a_i βŠ• x) - (a_j βŠ• x)|,$$$ where βŠ• denotes [the bitwise XO...
#include <bits/stdc++.h> using namespace std; template <class T> vector<T> readvec(int N) { vector<T> res(N); for (int i = 0; i < N; ++i) cin >> res[i]; return res; } void one() { int N, K; cin >> N >> K; vector<int> t = readvec<int>(N); vector<int> mins(1 << K, 1 << K); vector<vector<bool>> exists(K + ...
For a permutation p of numbers 1 through n, we define a stair array a as follows: a_i is length of the longest segment of permutation which contains position i and is made of consecutive values in sorted order: [x, x+1, …, y-1, y] or [y, y-1, …, x+1, x] for some x ≀ y. For example, for permutation p = [4, 1, 2, 3, 7, 6...
#include <bits/stdc++.h> using namespace std; template <typename T> void rd(T& x) { int f = 0, c; while (!isdigit(c = getchar())) f ^= !(c ^ 45); x = (c & 15); while (isdigit(c = getchar())) x = x * 10 + (c & 15); if (f) x = -x; } template <typename T> void pt(T x, int c = -1) { if (x < 0) putchar('-'), x =...
You are given n integers a_1, a_2, …, a_n. Find the maximum value of max(a_l, a_{l + 1}, …, a_r) β‹… min(a_l, a_{l + 1}, …, a_r) over all pairs (l, r) of integers for which 1 ≀ l < r ≀ n. Input The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line of each test case cont...
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // solution int t = sc.nextInt(); while (t != 0) { int n = sc.nextInt(); int[] arr = new int[n]; for (int ...
You are given n integers a_1, a_2, …, a_n and an integer k. Find the maximum value of i β‹… j - k β‹… (a_i | a_j) over all pairs (i, j) of integers with 1 ≀ i < j ≀ n. Here, | is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Input The first line contains a single integer t (1 ≀ t ≀ 10 000...
for _ in range(int(input())): n,k = map( int, input().split(' ') ) arr = [int(w) for w in input().split(' ')] ans = -10**18 temp =[] cnt = 0 for i in range(n-1,-1,-1): temp.append( (arr[i],i) ) cnt += 1 if cnt==300: break for i in range(len(temp)): ...
You are given two integers n and m. Find the \operatorname{MEX} of the sequence n βŠ• 0, n βŠ• 1, …, n βŠ• m. Here, βŠ• is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). \operatorname{MEX} of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in thi...
import sys input = sys.stdin.readline # sys.setrecursionlimit(400000) def I(): return input().strip() def II(): return int(input().strip()) def LI(): return [*map(int, input().strip().split())] import copy, string, math, time, functools, random, fractions from heapq import heappush, heappop, heapify from bise...
You are given an integer n. Find any string s of length n consisting only of English lowercase letters such that each non-empty substring of s occurs in s an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints. A string a is a ...
#include <bits/stdc++.h> using namespace std; int main() { int T; scanf("%d", &T); while (T--) { int N; scanf("%d", &N); if (N < 20) for (int i = 0; i < N; ++i) putchar('a' + i); else { if (N & 1) { putchar('c'); --N; } for (int i = 0; i < N / 2; ++i) putcha...
You are given a tree with n nodes. As a reminder, a tree is a connected undirected graph without cycles. Let a_1, a_2, …, a_n be a sequence of integers. Perform the following operation exactly n times: * Select an unerased node u. Assign a_u := number of unerased nodes adjacent to u. Then, erase the node u along w...
import sys input = lambda: sys.stdin.readline().rstrip("\r\n") MOD = 998244353 t = int(input()) while t > 0: t -= 1 n = int(input()) g = [[] for i in range(n)] for i in range(n - 1): x, y = map(int, input().split()) g[x - 1] += [y - 1] g[y - 1] += [x - 1] f = [0] * n pa...
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of 6 slices, medium ones consist of 8 slices, and large pizzas consist of 10 slices each. Baking them takes 15, 20 and 25 minutes, respectively. Petya's birthday is today, and n of his friends will come, s...
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int in; cin >> in; for (int i = 0; i < in; i++) solve(); return 0; } void solve() { long long n, time, tempTime; cin >> n; if (n < 7) time = 15; else { tempTime =...
You have an axis-aligned rectangle room with width W and height H, so the lower left corner is in point (0, 0) and the upper right corner is in (W, H). There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in (x_1, y_1), and the upper right corne...
from collections import * from math import * TT=int(input()) for y in range(TT): #n=int(input()) n,m=map(int,input().split()) #lst=list(map(int,input().split())) #s=input() x1,y1,x2,y2=map(int,input().split()) w,h=map(int,input().split()) if ((x2-x1)+w)<=n: if ((y2-y1)+h)<=m: ...
Alice and Bob are playing a game on a matrix, consisting of 2 rows and m columns. The cell in the i-th row in the j-th column contains a_{i, j} coins in it. Initially, both Alice and Bob are standing in a cell (1, 1). They are going to perform a sequence of moves to reach a cell (2, m). The possible moves are: * ...
#include <bits/stdc++.h> using namespace std; int n; long long a[3][100011], sum[3][100011]; void solve() { cin >> n; for (int i = 1; i <= 2; i++) for (int j = 1; j <= n; j++) cin >> a[i][j], sum[i][j] = 0; sum[2][1] = a[2][1]; sum[1][1] = a[1][1]; for (int i = 2; i <= n; i++) sum[1][i] = sum[1][i - 1...
Let's call the string beautiful if it does not contain a substring of length at least 2, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, bu...
import sys input=sys.stdin output=sys.stdout inputs=input.readline().strip().split() N=int(inputs[0]) M=int(inputs[1]) S=input.readline().strip() SL=['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] CL=[[0]*(N+1) for x in range(6)] #def check_beautiful(substring): # total=len(substring) # for i in SL: # subt...
You are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i. You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a...
#include <bits/stdc++.h> using namespace std; int n, m; struct Seg { int l; int r; int w; }; vector<int> segTree; vector<int> lazyTree; void updateSegT(int node, int st, int end, int l, int r, int val) { if (l > r) return; if (lazyTree[node]) { lazyTree[2 * node] += lazyTree[node]; lazyTree[2 * node +...
You have an undirected graph consisting of n vertices with weighted edges. A simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of edges it consists of. Let's say the graph is good if all its simple c...
#include <bits/stdc++.h> struct disjoin_set_union { std::vector<int> parent; std::vector<int> rank; disjoin_set_union(int n = 0) : parent(n), rank(n, 1) { std::iota(parent.begin(), parent.end(), 0); } int root(int v) { return (v ^ parent[v]) ? parent[v] = root(parent[v]) : v; } bool unite(int v, int u) ...
<image> William has two numbers a and b initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer k is picked, which is then used to perform one of the following operations: (note, that for each operation you can choos...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastScanner in = new FastScanner(); int tt = in.nextInt(); for(int pp = 0; pp < tt; pp++) { int a = in.nextInt(); ...
<image> William has an array of n integers a_1, a_2, ..., a_n. In one move he can swap two neighboring items. Two items a_i and a_j are considered neighboring if the condition |i - j| = 1 is satisfied. William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array doe...
#include <bits/stdc++.h> using namespace std; inline int read() { int 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 * 10 + ch - '0'; ch = getchar(); } return x * f; } template <class T> clas...
<image> William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers c_1, c_2, ..., c_n where c_i is the number of consecutive brackets "(" if i is an odd number or the number of consecutive brackets ")" if i is an even number. For example ...
#include <bits/stdc++.h> using namespace std; signed main() { setlocale(LC_ALL, "rus"); std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<long long> dp(n); stack<pair<int, int>>...
<image> This is an interactive task William has a certain sequence of integers a_1, a_2, ..., a_n in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than 2 β‹… n of the following questions: * What is the result of a [bitwise AND](https:/...
#include <bits/stdc++.h> using namespace std; const int N = 1e4 + 10; int a[N]; void solve() { int n, k; cin >> n >> k; int a1, a2, a3, o1, o2, o3; cout << "and 1 2\n"; cout.flush(); cin >> a1; cout << "and 1 3\n"; cout.flush(); cin >> a2; cout << "and 2 3\n"; cout.flush(); cin >> a3; cout << ...
<image> William has two arrays a and b, each consisting of n items. For some segments l..r of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each i from l to r holds a_i = b_i. To perform a ...
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1556E { public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.ne...
<image> William is not only interested in trading but also in betting on sports matches. n teams participate in each match. Each team is characterized by strength a_i. Each two teams i < j play with each other exactly once. Team i wins with probability (a_i)/(a_i + a_j) and team j wins with probability (a_j)/(a_i + a_...
#include <bits/stdc++.h> using namespace std; template <typename T> T inverse(T a, T m) { T u = 0, v = 1; while (a != 0) { T t = m / a; m -= t * a; swap(a, m); u -= t * v; swap(u, v); } assert(m == 1); return u; } template <typename T> class Modular { public: using Type = typename decay...
<image> As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from 0 to 2^n - 1. On each planet, there are gates that allow the player to move from planet i to planet j if the binary repr...
#include <bits/stdc++.h> using namespace std; inline int read_int() { int t = 0; bool sign = false; char c = getchar(); while (!isdigit(c)) { sign |= c == '-'; c = getchar(); } while (isdigit(c)) { t = (t << 1) + (t << 3) + (c & 15); c = getchar(); } return sign ? -t : t; } inline long l...
<image> William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of n vertices. He wants to build a spanning tree of this graph, such that for the first k vertices the following condition is satisfied: the degree of a vertex with index i d...
#include <bits/stdc++.h> using namespace std; int read() { int ret = 0; char c = getchar(); while (c > '9' || c < '0') c = getchar(); while (c >= '0' && c <= '9') ret = (ret << 3) + (ret << 1) + (c ^ 48), c = getchar(); return ret; } const int maxn = 55; const int maxk = 6; const int maxm = 2500; const in...
Ezzat has an array of n integers (maybe negative). He wants to split it into two non-empty subsequences a and b, such that every element from the array belongs to exactly one subsequence, and the value of f(a) + f(b) is the maximum possible value, where f(x) is the average of the subsequence x. A sequence x is a subs...
def process(A): A = sorted(A) answer = -1*float('inf') S = sum(A) S1 = A[0] n1 = 1 answer = max(answer, S1/n1+(S-S1)/(n-n1)) for i in range(1, n-1): n1+=1 S1+=A[i] answer = max(answer, S1/n1+(S-S1)/(n-n1)) return answer t = int(input()) for i in range(t): n =...
Moamen has an array of n distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once: 1. Split the array into exactly k non-empty subarrays such that each element belongs to exactly one subarray. 2. Reorder these subarrays arbitrary. 3. Merge t...
for _ in range(int(input())): n,k=map(int, input().split()) li=list(map(int, input().split())) di={} a=1 for i in sorted(li): di[i]=a a+=1 changes=0 i=0 while i<n-1: while i<n-1 and di[li[i+1]]-di[li[i]]==1: i+=1 if i!=n-1: changes+...
Moamen and Ezzat are playing a game. They create an array a of n non-negative integers where every element is less than 2^k. Moamen wins if a_1 \& a_2 \& a_3 \& … \& a_n β‰₯ a_1 βŠ• a_2 βŠ• a_3 βŠ• … βŠ• a_n. Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and βŠ• denotes...
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, y = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') y = -1; ch = getchar(); } while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * y; } long long b[100005]; long long c[100005]; const int...
Moamen was drawing a grid of n rows and 10^9 columns containing only digits 0 and 1. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful. A grid is beautiful if and only if for every two consecutive rows there is at least one column c...
#include <bits/stdc++.h> using namespace std; struct segment_tree { int n; vector<pair<int, int>> st, lazy; segment_tree(int n) : n(n), st(2 * n, {0, -1}), lazy(2 * n) {} inline int id(int b, int e) { return (b + e - 1) | (b != e - 1); } void prop(int l, int r) { int cur = id(l, r); st[cur] = max(st[c...
This is an interactive problem. ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king. You compete on an 8Γ—8 chessboard, the rows are numerated from top to bottom, and the columns a...
#include <bits/stdc++.h> using namespace std; int T, row, col; string s; void mov(int x, int y) { printf("%d %d\n", x, y); col = y; cin >> s; } int scan(int row) { for (int c = (col == 1 ? 2 : 1); c <= 8; ++c) { mov(row, c); if (s == "Done") return true; if (s.find("Down") != -1) return false; i...
You have a permutation: an array a = [a_1, a_2, …, a_n] of distinct integers from 1 to n. The length of the permutation n is odd. You need to sort the permutation in increasing order. In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if a = [a_1, a_2, …, a_n], you ...
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T& x) { T t = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { t = (t << 3) + (t << 1) + ch - '0'; ch = getchar(); } x = f * t; } templat...
Consider the insertion sort algorithm used to sort an integer sequence [a_1, a_2, …, a_n] of length n in non-decreasing order. For each i in order from 2 to n, do the following. If a_i β‰₯ a_{i-1}, do nothing and move on to the next value of i. Otherwise, find the smallest j such that a_i < a_j, shift the elements on po...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MOD = 998244353; const int MAXN = 4e5 + 1; int quick(int A, int B) { if (B == 0) return 1; int tmp = quick(A, B >> 1); tmp = 1ll * tmp * tmp % MOD; if (B & 1) tmp = 1ll * tmp * A % MOD; return tmp; } int inv(int A) { return qu...
In a certain video game, the player controls a hero characterized by a single integer value: power. On the current level, the hero got into a system of n caves numbered from 1 to n, and m tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cave can be...
#include <bits/stdc++.h> using namespace std; template <typename T> void chmin(T &x, const T &y) { if (x > y) x = y; } template <typename T> void chmax(T &x, const T &y) { if (x < y) x = y; } char readc() { char c; while (isspace((c = getchar()))) ; return c; } int read() { char c; while ((c = getchar...
Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation. This day, Mocha got a sequence a of length n. In each operation, she can select an arbitrary in...
import sys import os from math import * from functools import reduce # sys.stdin = open(r"hack.txt", "r") def main(): t = int(input()) for i in range(t): n = int(input()) l = list(map(int, input().split())) print(reduce(lambda x, y: x & y, l)) if __name__ == "__main__": main()
As their story unravels, a timeless tale is told once again... Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to s...
import java.io.*; public class MochaRedandBlue { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.p...
The city where Mocha lives in is called Zhijiang. There are n+1 villages and 2n-1 directed roads in this city. There are two kinds of roads: * n-1 roads are from village i to village i+1, for all 1≀ i ≀ n-1. * n roads can be described by a sequence a_1,…,a_n. If a_i=0, the i-th of these roads goes from village ...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; const int INF = 0x3f3f3f3f; const long long INFF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; int t, n, a[N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; if (a[n] == 0) { for (int i = 1; i <= n; i++) cout << i << ' ...
This is the easy version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved. A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a fore...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000; vector<int> dis1(maxn), dis2(maxn); void init() { for (int i = 0; i < maxn; i++) { dis1[i] = dis2[i] = i; } } int find_root(int w, int n) { if (w == 1) return dis1[n] == n ? n : dis1[n] = find_root(w, dis1[n]); else if (w == 2) ret...
This is the hard version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved. A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a fore...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 7; int rd() { int s = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { s = s * 10 + c - '0'; c = getchar(); } return s * f; } int n, m1, m2, ...
Mocha wants to be an astrologer. There are n stars which can be seen in Zhijiang, and the brightness of the i-th star is a_i. Mocha considers that these n stars form a constellation, and she uses (a_1,a_2,…,a_n) to show its state. A state is called mathematical if all of the following three conditions are satisfied: ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5, mod = 998244353; long long f[55][N], l[N], r[N], sum[N], prim[N], nump, vis[N], mu[N]; void init() { mu[1] = 1; for (int i = 2; i < N; i++) { if (!vis[i]) { prim[++nump] = i; mu[i] = -1; } for (int j = 1; j <= nump && i * p...
Polycarp doesn't like integers that are divisible by 3 or end with the digit 3 in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too. Polycarp starts to write out the positive (greater than 0) integers which he likes: 1, 2, 4, 5, 7, 8, 10, 11, 14, 16, .... Output the k-th el...
#include <bits/stdc++.h> using namespace std; int main() { int n, t; cin >> t; while (t--) { int count = 0; int ans; cin >> n; for (int i = 1; i <= 1666; i++) { if ((i % 10 != 3) && i % 3 != 0) { count++; } if (count == n) { ans = i; break; } } ...
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number 1. Each person is looking through the circle's center at the opposite person. <image> A sample of a circle of 6 persons. The orange arrows indica...
import math t = int(input()) for _ in range(t): a,b,c = map(int,input().split()) n = abs(b-a)*2 diff = abs(b-a) if a>n or b>n or c>n: print(-1) continue x1,x2 = c + diff , c-diff ans = -1 if 1<=x1<=n: ans = c+diff if 1<=x2<=n: ans = c-diff print(ans)
Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from 1, starting from the topmost one. The columns are numbered from 1, starting from the leftmost one. Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from 1 and so on to the table ...
import java.util.*; import java.io.*; public class C_1560 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int k = sc.nextInt(); int start = 1, end = (int)(Math.sqrt(1e9)...
You are given an integer n. In 1 move, you can do one of the following actions: * erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); * add one digit to the right. The actions may be performed in any order any numbe...
import java.io.*; import java.util.*; public class Main { static int M = 1_000_000_007; static int INF = 2_000_000_000; static int N = (int)1e5+1; static final FastScanner fs = new FastScanner(); //variable public static void main(String[] args) throws IOException { int T = fs.nex...
Polycarp has a string s. Polycarp performs the following actions until the string s is empty (t is initially an empty string): * he adds to the right to the string t the string s, i.e. he does t = t + s, where t + s is a concatenation of the strings t and s; * he selects an arbitrary letter of s and removes from ...
def func(): t = input() #t = t[:-1] #print(t) s = "" n = len(t) m = 0 sc = [0 for i in range(26)] tc = [0 for i in range(26)] for i in range(n): temp = ord(t[i]) #print(temp) tc[temp - 97] += 1 for i in range(26): if(tc[i]!=0): ...
It is a simplified version of problem F2. The difference between them is the constraints (F1: k ≀ 2, F2: k ≀ 10). You are given an integer n. Find the minimum integer x such that x β‰₯ n and the number x is k-beautiful. A number is called k-beautiful if its decimal representation having no leading zeroes contains no mo...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class C2 { static TreeSet<Long> set1; static TreeSet<Long> set2; private static void sport(int n, int k) { if (k == 1) { Long ceiling = set1.ceiling((...
It is a complicated version of problem F1. The difference between them is the constraints (F1: k ≀ 2, F2: k ≀ 10). You are given an integer n. Find the minimum integer x such that x β‰₯ n and the number x is k-beautiful. A number is called k-beautiful if its decimal representation having no leading zeroes contains no m...
l=len _,*t=open(0) for p in t: x,k=p.split();k=int(k);n=x while l(set(x))>k:x=str(int(x)+1).strip('0') print(x+(l(n)-l(x))*min(x+'0'*(l(set(x))<k)))
You have a permutation: an array a = [a_1, a_2, …, a_n] of distinct integers from 1 to n. The length of the permutation n is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, f(i), takes a single argument i (1 ≀ i ≀ n-1) and does the following. ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for(int tt = 0 ; tt < t; tt++) { int n = sc.nextInt(); int a[] = new int[n...
Alice and Borys are playing tennis. A tennis match consists of games. In each game, one of the players is serving and the other one is receiving. Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa. Each game ends with a victory of one of the players. If ...
#include <bits/stdc++.h> using namespace std; void debugs() { ios_base::sync_with_stdio(false); cin.tie(NULL); } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } long long multiply(long long x, long long res[], long long ressize) { long long carry = 0; for (long long i...
In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor. On the current level, the hero is facing n caves. To pass the level, the hero must enter all the caves in some order, eac...
import os import sys from io import BytesIO, IOBase import math from queue import Queue import collections import itertools import bisect import heapq # sys.setrecursionlimit(100000) # ^^^TAKE CARE FOR MEMORY LIMIT^^^ import random def main(): pass BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 de...
This version of the problem differs from the next one only in the constraint on n. Note that the memory limit in this problem is lower than in others. You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom. You also have a token that is initially placed in cell n. You will move...
# template begins ##################################### from io import BytesIO, IOBase import sys import math import os import heapq from collections import defaultdict, deque from math import ceil from bisect import bisect_left, bisect_left from time import perf_counter # region fastio BUFSIZE = 8192 class FastIO...
Note that the memory limit in this problem is lower than in others. You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom. You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1. Let the token be in cell x > 1 at some mo...
n, m = map(int, input().split()) c = [0]*n + [1] + [0]*n for i in range(n-1, 0, -1): c[i] = 2*c[i+1] % m for j in range(2, n//i + 1): c[i] = (c[i] + c[i*j] - c[(i+1)*j]) % m print((c[1] - c[2]) % m)
You are given two integers l and r, l≀ r. Find the largest possible value of a mod b over all pairs (a, b) of integers for which rβ‰₯ a β‰₯ b β‰₯ l. As a reminder, a mod b is a remainder we get when dividing a by b. For example, 26 mod 8 = 2. Input Each test contains multiple test cases. The first line contains one posit...
import java.io.*; import java.lang.Math; import java.math.*; import java.util.*; public final class A_The_Miracle_and_the_Sleeper { public static void main(String[] args) throws IOException { int testCases = sc.nextInt(); for (int cases = 0; cases < testCases; cases++) { // My code ...
During the hypnosis session, Nicholas suddenly remembered a positive integer n, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equa...
def f(a, b): c = (23, 37, 73, 53) return not a * 10 + b in c for _ in range(int(input())): k = int(input()) a = [int(i) for i in input()] c = (1, 4, 6, 8, 9) for i in a: if i in c: print(1) print(i) break else: print(2) if f(a[0]...
Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents β€”there was a pile of different rings: gold and silver... "How am I to tell which is the One?!" the mage howled. "Throw them one by one into the Cracks of Doom and watch when Mordor falls!" Somewhere in a parallel Middle-earth, wh...
#include <bits/stdc++.h> using namespace std; const long long MX = 303030; const long long INF = 9e15; long long tc; vector<long long> v[2]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> tc; while (tc--) { long long n; string s; cin >> n; cin >> s; lo...
This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved. Stitch likes experimenting with different machines with his friend Sparky. Today...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, q; cin >> n >> q; string s; cin >> s; vector<int> a = {0}; int x = 0; for (int i = 0; i < n; i++) { int c = 1; if (s[i] == '-') { c = -1; } if (i % 2 == 0) {...
This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved. Stitch likes experimenting with different machines with his friend Sparky. Today the...
import java.util.*; import java.io.*; public class D1562 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int q = sc.nextInt(); char[] s = sc....
Morning desert sun horizon Rise above the sands of time... Fates Warning, "Exodus" After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open! Ori was taken aback, but th...
#include <bits/stdc++.h> using namespace std; const int N = 5e3 + 9; const int Log2 = 23; const int inf = 1e9 + 7; vector<int> g[N]; string s; int T, n, lcp[N][N], dp[N][N]; void Repack() { for (int i = 1; i <= n; i++) lcp[i][n + 1] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) dp[i][j] = 0; ...
You are given two positive integers n and s. Find the maximum possible median of an array of n non-negative integers (not necessarily distinct), such that the sum of its elements is equal to s. A median of an array of integers of length m is the number standing on the ⌈ {m/2} βŒ‰-th (rounding up) position in the non-dec...
import java.util.*; import java.io.*; public class A { static HashMap<Integer, Integer> map = new HashMap<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = in.nextInt(); for(int tt = 0; tt < ...
A binary string is a string that consists of characters 0 and 1. Let \operatorname{MEX} of a binary string be the smallest digit among 0, 1, or 2 that does not occur in the string. For example, \operatorname{MEX} of 001011 is 2, because 0 and 1 occur in the string at least once, \operatorname{MEX} of 1111 is 0, becaus...
import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from collections import Counter from collections import defaultdict as dd # sys.setrecursionlimit(100000000) flus...
A binary string is a string that consists of characters 0 and 1. A bi-table is a table that has exactly two rows of equal length, each being a binary string. Let \operatorname{MEX} of a bi-table be the smallest digit among 0, 1, or 2 that does not occur in the bi-table. For example, \operatorname{MEX} for \begin{bmatr...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); String s1=sc.next(); String s2=sc.next(); int ans=0; for(int i=0;i<n;i++) { int a=s1....
It is the easy version of the problem. The only difference is that in this version n = 1. In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from...
#include <bits/stdc++.h> using namespace std; void solve() { long long int n, m, i, j, k, l; cin >> n >> m; long long int a[m + 2]; for (i = 0; i < m; i++) { cin >> a[i]; } long long int ct = 0; for (i = 0; i < m; i++) { long long int cc = a[i]; long long int vc = 0; for (j = 0; j < i; j++...
It is the hard version of the problem. The only difference is that in this version 1 ≀ n ≀ 300. In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th ro...
import os, sys from io import BytesIO, IOBase from collections import * class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self...
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent. A vertex is a leaf if it ha...
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<vector<int>> graph(n + 1); for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; graph[u].push_back(v); graph[v].push_back(u); } int ans = 0; int cnt = 0; int flag = 0; function<int(int, int, int)> df...
There are n points and m segments on the coordinate line. The initial coordinate of the i-th point is a_i. The endpoints of the j-th segment are l_j and r_j β€” left and right endpoints, respectively. You can move the points. In one move you can move any point from its current coordinate x to the coordinate x - 1 or the...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Deque; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collection; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets...
You are given an undirected weighted graph, consisting of n vertices and m edges. Some queries happen with this graph: * Delete an existing edge from the graph. * Add a non-existing edge to the graph. At the beginning and after each query, you should find four different vertices a, b, c, d such that there ex...
#include <bits/stdc++.h> using namespace std; const int N = 100005; int n, m; long long s3[N]; map<pair<int, int>, int> mpw, mpc; set<pair<int, int> > G[N], T[N]; set<pair<int, pair<int, int> > > st; set<pair<long long, int> > st3; inline void mdf_edge(int u, int v, int w, int d) { if (u > v) swap(u, v); int lst = ...
This is an interactive problem. You are given two integers c and n. The jury has a randomly generated set A of distinct positive integers not greater than c (it is generated from all such possible sets with equal probability). The size of A is equal to n. Your task is to guess the set A. In order to guess it, you can...
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.arraycopy; import static java.lang.System.exit; import static java.util.Arrays.copyOf; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter...
Alice gave Bob two integers a and b (a > 0 and b β‰₯ 0). Being a curious boy, Bob wrote down an array of non-negative integers with \operatorname{MEX} value of all elements equal to a and \operatorname{XOR} value of all elements equal to b. What is the shortest possible length of the array Bob wrote? Recall that the \o...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 15; const int mod = 1e9 + 7; inline int read() { int ret = 0, op = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') op = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { ret = ret * 10 + ch - '0'; ch =...
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully β€” instead of carrying to the next column, she carries to the column two columns to the left. For example, the regular way to evaluate the sum 2039 + 2976 would be as shown: <image> However, Alice evaluates it as shown: <i...
#include <bits/stdc++.h> using namespace std; const long long N = 300010, M = 11, Mod = 1e9 + 7; long long n, m, a[N]; long long Dp[M][2][2]; string s; long long Solve(int i = 0, int Cur = 0, int Nxt = 0) { if (i == n) { return (Cur == 0 && Nxt == 0); } long long &Res = Dp[i][Cur][Nxt]; if (Res != -1) { ...
On the board, Bob wrote n positive integers in [base](https://en.wikipedia.org/wiki/Positional_notation#Base_of_the_numeral_system) 10 with sum s (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-11 integers and adds them up (in base 11). What numbers...
#include <bits/stdc++.h> using namespace std; int main() { int tests; cin >> tests; while (tests--) { int sum, elements; cin >> sum >> elements; int aux_sum = sum, digit_sum = 0; while (aux_sum) { digit_sum += aux_sum % 10; aux_sum /= 10; } int power = 1; if (elements <= di...
Alice has recently received an array a_1, a_2, ..., a_n for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too! However, soon Bob became curious, and as any sane friend would do, asked Alice to perform q operations of two types on her arra...
#include <bits/stdc++.h> using namespace std; long long s[2000500], sum[2000500]; void add(int l, int r, int nl, int nr, int cur, long long ad) { if (l == nl && r == nr) { sum[cur] = (sum[cur] + ad); s[cur] = (s[cur] + ad * (r - l + 1)); if (l != r && sum[cur]) { sum[(cur << 1)] = (sum[(cur << 1)] +...
Alice has an empty grid with n rows and m columns. Some of the cells are marked, and no marked cells are adjacent to the edge of the grid. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: * every unmarked cell contains either...
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; const int N = 505; char c[N][N]; int comp[N][N]; int countComp = 0; int color[N * N]; int res[N][N]; int n, m; vector<int> adj[N * N]; inl...
You are given a string s, consisting of n letters, each letter is either 'a' or 'b'. The letters in the string are numbered from 1 to n. s[l; r] is a continuous substring of letters from index l to r of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of let...
for _ in range (int(input())): n=int(input()) s=input() p=0 if("a" in s): p+=1 if("b" in s): p+=1 if(p<2): print("-1 -1") else: if("ab" in s): z=s.index("ab") print(str(z+1)+" "+str(z+2)) else: z=s.index("ba") ...
A chess tournament will be held soon, where n chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players. Each of the players has their own expectations about the tournament,...
from collections import Counter, defaultdict from sys import stdin,stdout import io , os , sys #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline input = stdin.readline def mapinput(): return map(int, input().split()) def listinput(): return list( map( int, input().split())) def intinput(): ...
n people gathered to hold a jury meeting of the upcoming competition, the i-th member of the jury came up with a_i tasks, which they want to share with each other. First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation p of numbers from 1 to n (an array of siz...
#include <bits/stdc++.h> using namespace std; int a[1111111]; int q; int n; int64_t gt[1111111]; int64_t Powe(int a, int n) { if (n == 0) return 1; if (n == 1) return a; int64_t b = Powe(a, n / 2); b = (b * b) % 998244353; if (n % 2 == 1) return (b * a) % 998244353; else return b; } int main() { s...