input
stringlengths
29
13k
output
stringlengths
9
73.4k
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is ...
#include <bits/stdc++.h> using namespace std; const int c = 2e5 + 5; int strength[c], level[c], size[c], visited[c], tree_even[4 * c], tree_odd[4 * c], M; std::vector<int> v[c], preorder; map<int, int> Map; int dfs(int vertex, int lev) { if (visited[vertex]) return 0; visited[vertex] = 1; level[vertex] = lev;...
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them bac...
#include <bits/stdc++.h> using namespace std; bool a[1000000 + 100]; int tot = 0, idx = 0, ans[1000000], n; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { int p; scanf("%d", &p); a[p] = 1; } for (int i = 1; i <= 1000000 / 2; i++) { if (a[i] && !a[1000000 - i + 1]) ans[++tot] = 1000...
You have an n × m rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: * each cell must be painted some color (the colors are marked by uppercase Latin letters); * we will assume that ...
#include <bits/stdc++.h> using namespace std; template <typename T> bool MinPlace(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } template <typename T> bool MaxPlace(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <typename S, typename T...
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the re...
#include <bits/stdc++.h> using namespace std; const int inf = int(1e9); const double pi = 4 * atan(double(1.0)); const double eps = 1e-9; const int LEN = int(1e5) + 100; char s[LEN]; bool can_win[LEN], can_loose[LEN]; int _next[LEN][26]; void dfs(int v) { bool exists = false; for (int i = 0; i < 26; ++i) { if (...
Dreamoon has just created a document of hard problems using notepad.exe. The document consists of n lines of text, ai denotes the length of the i-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long. Let (r, c) be a current cursor position, where r is row ...
#include <bits/stdc++.h> using namespace std; int Ans[400005], n, m; int a[400005], b[400005], W[400005], top; int lc[800005], rc[800005], f[3][800005], rt; struct O { int p, q, x, y, i; } o[400005]; bool cmo(O a, O b) { return a.x < b.x; } void build(int &u, int p, int q) { u = ++top; f[1][u] = f[2][u] = 1000000...
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible. Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all ho...
par=[0]*310 rank=[0]*310 def init_union_find(V):#initial state for i in xrange(V): par[i]=i rank[i]=0 def find(x):#where the root if par[x]==x: return x else: par[x]=find(par[x]) return par[x] def unite(x,y):#x and y unite x=find(x) y=find(y) if x==y: ...
Anya loves to fold and stick. Today she decided to do just that. Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes. Anya can stick a...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; const int Mod = 1e9 + 7; map<long long, int> Left[26], Right[26]; int n, k, a[30]; long long sum, fact[20]; void cal(int pos, int crk, long long crSum, int last) { if (pos == last) { if (last != n) Left[crk][crSum]++; else Right...
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
#include <bits/stdc++.h> using namespace std; int a[2001] = {0}, b[2001]; int main() { int n; cin >> n; for (int i = 1, j; i <= n; i++) { cin >> j; a[j]++; b[i] = j; } int ranking = 1, temp; for (int i = 2000; i >= 1; i--) { if (a[i] != 0) { temp = a[i]; a[i] = ranking; ran...
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR. Find the maximum possible value of <image> after performing at most k operations optimally. I...
#include <bits/stdc++.h> using namespace std; int N, y, K; long long P; int A[2 * 100005]; int pref[2 * 100005], suf[2 * 100005]; int main() { cin >> N >> K >> P; for (int i = 0; i < N; ++i) { cin >> A[i]; } pref[0] = A[0]; suf[N] = A[N]; for (int i = 1; i < N; ++i) pref[i] = (A[i] | pref[i - 1]); for...
In Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there ar...
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); long long n, m, k; cin >> n >> m >> k; vector<vector<long long>> a(n + 1); set<vector<long long>> s; for (long long i = 0; i < m; i++) { long long u, v; cin >> u >> v...
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too. Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from...
import java.util.Scanner; public class Main { Scanner in = new Scanner(System.in); double calc(int l, int r, int p) { return (double)(r / p - (l - 1) / p) / (r - l + 1); } public void run() { int n = in.nextInt(), p = in.nextInt(); int[] l = new int[n]; int[] r = new int[n]; for (int i = 0; i < n...
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the bigges...
#include <bits/stdc++.h> using namespace std; long long n, i, j, a[10001], b[10001], v, h[10001], k; int main() { cin >> n; for (i = 1; i <= n; i++) cin >> a[i]; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) b[j] = 0; k = 0; for (j = i; j <= n; j++) { v = a[j]; b[v]++; if (b[v]...
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. Input The first line of the input contains a ...
#include <bits/stdc++.h> using namespace std; int n; int main() { scanf("%d", &n); int minday = n / 7 * 2, maxday = n; if (n % 7 == 6) minday++; if (n > 2) { maxday = 2; n -= 2; maxday += n / 7 * 2; if (n % 7 == 6) maxday++; } cout << minday << " " << maxday << endl; return 0; }
You are given a positive decimal number x. Your task is to convert it to the "simple exponential notation". Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without d...
#include <bits/stdc++.h> using namespace std; template <class T1, class T2> inline void gmax(T1 &a, T2 b) { if (b > a) a = b; } template <class T1, class T2> inline void gmin(T1 &a, T2 b) { if (b < a) a = b; } const int N = 1e6 + 10; const long long INF = 1e18; int casenum, casei; const int Z = 1e9 + 7; int n, m; c...
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : 1. Pr...
n=int(input()) print(2) for lvl in range(2,n+1): print(lvl*(lvl+1)*(lvl+1)-(lvl-1))
Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were m players participating and each pair of players played exactly one game. The victory gives 2 points, draw — 1 points, lose — 0 points. Ostap is lazy, so he never tries t...
#include <bits/stdc++.h> using namespace std; void assign(vector<vector<int>> &res, int i, int j, int v) { res[i][j] = v; res[j][i] = 2 - v; } int main() { ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int N, K; cin >> N >> K; vector<pair<int, int>> pts(N)...
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made m operat...
#include <bits/stdc++.h> using namespace std; int getint() { int f = 1, x = 0; 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 f * x; } struct node { long long x,...
Input The input contains a single integer a (1 ≤ a ≤ 30). Output Output a single integer. Example Input 3 Output 27
#include <bits/stdc++.h> using namespace std; int main() { int a[31] = {0, 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645}; int n; cin >> n; cout << a[n] << endl; return 0; }
In Isart people don't die. There are n gangs of criminals. The i-th gang contains si evil people numerated from 0 to si - 1. Some of these people took part in a big mine robbery and picked one gold bullion each (these people are given in the input). That happened 10100 years ago and then all of the gangs escaped to a r...
#include <bits/stdc++.h> inline int read() { int x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { ch = getchar(); if (ch == '-') w = -1; } while (ch <= '9' && ch >= '0') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * w; } using namespace std; const int N = 5005...
Consider a house plan. Let the house be represented by an infinite horizontal strip defined by the inequality - h ≤ y ≤ h. Strictly outside the house there are two light sources at the points (0, f) and (0, - f). Windows are located in the walls, the windows are represented by segments on the lines y = h and y = - h...
#include <bits/stdc++.h> using namespace std; const int maxn = 500 + 5; const double eps = 1e-10; const int INF = 10000000; struct point { double x, y; point() {} point(double x, double y) : x(x), y(y) {} }; point operator-(point a, point b) { return point(a.x - b.x, a.y - b.y); } point operator+(point a, point b...
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
import java.util.*; import java.io.*; import java.math.*; public final class Solution { public static void main(String[] args) { Reader input = new Reader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = input.nextInt(), k = input.nextInt(), t = input....
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large ve...
#include <bits/stdc++.h> using namespace std; const int max_n = 100111, inf = 1011111111; int n, m, f[max_n], used[max_n], len[max_n]; vector<int> g[max_n], a[max_n], ans; void dfs(int v) { ans.push_back(v); used[v] = 1; f[v] = 1; for (int to : g[v]) { if (used[to] == 0) { dfs(to); } } } bool cm...
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on t...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:160000000") const int L = 1111; const int N = 111; string s; map<string, int> M; long long x[N]; long long y[N]; vector<int> v[N]; long long sp[N]; long long brd[N]; int t[N]; bool color[N]; int K = 0; void dfs(int u) { color[u] = 1; if (...
Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly V ml of water. Petya has got N tanks, i-th of them initially containing ai ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is). Also Petya has got a scoop t...
#include <bits/stdc++.h> using namespace std; const int N = 5005; int n; long long k, v; int fnum[N], fpre[N]; long long a[N]; int main() { scanf("%d%d%d", &n, &k, &v); for (int i = 1; i <= n; ++i) scanf("%I64d", a + i), a[0] += a[i]; if (a[0] < v) { printf("NO"); return 0; } for (int i = 0; i < k; ++...
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that i...
#include <bits/stdc++.h> using namespace std; int main() { long long n, m, t; cin >> n >> m; while (m--) { cin >> t; while (t % 2 == 0) { t = t / 2 + n; } cout << (t + 1) / 2 << endl; } return 0; }
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
a, b = input().split(' ') a=int(a) for i in range(int(b)): if (a%10 != 0): a -= 1 else: a /= 10 print(int(a))
For a vector \vec{v} = (x, y), define |v| = √{x^2 + y^2}. Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, ⋅⋅⋅, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_...
#include <bits/stdc++.h> using namespace std; struct LLI { public: int x; int y; int inx; LLI(int X = 0, int Y = 0, int INX = 0) { x = X; y = Y; inx = INX; } }; int n, i, j; LLI now; LLI p[100001]; bool out[100001]; bool OUT[100001]; inline long long dist(LLI a) { long long X = ((long long)(a.x...
Zubin is the dark messiah. He roams the streets at night, helping the poor and the innocent from evil. He's Batman. Ghosh is Zubin's nemesis. He's the Riddler to Zubin's Batman. He delights in torturing people with his puzzles. Tonight, Ghosh has gotten hold of yet another innocent victim. When Zubin tries to save him,...
import math t=input() raw_input() while t: t-=1 n=input() if (n==0 or n==1): print 1 else: print int(math.ceil((math.log(math.sqrt(2*math.pi*n))+n*math.log(n/math.e))/math.log(10)))
Today, King Trophies is on another rampage to destroy the small village controlled by Alex. Please help his soldiers. At first, there are N individual soldiers, who haven't yet joined together; each of these soldiers is the leader of his/her own group. You have to handle 3 types of operations: 1) Two groups find each...
def union(parents, i, j): ''' Union with under the deepest root ''' parents[i] = j def find(parents, el): ''' Find an element and compress the sets ''' if parents[el] == el: return el leader = find(parents, parents[el]) parents[el] = leader return leader def solve(n, xss): res = [] ...
Tom gives a number N to Roy and ask him to tell the total number of even divisors of the number N. Help Roy to answer the question of Tom. INPUT: First line contains the number of testcases T, followed by T lines each containing an integer N. OUTPUT: For each testcase, print the required answer in a singlr line. ...
def div(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) for _ in xrange(input()): x= div(input()) print len([1 for i in x if i%2==0])
Today grasshopper Jimmy Jumper is very hungry and his friend is notorious. Jimmy's friend puts an insect infront of him at a distance d. Jimmy can jump only a finite no of steps in each turn. Jimmy is initially at position 0. He can now jump 1 step to reach position 1 then jump 2 steps to reach position 3 then jump 4 s...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' from math import sqrt t=input() while t>0: t-=1 n=input() a=0 b=1 while(a<n): a+=b b*=2 if n==a: print"YES" else: print"NO"
From the divine land of heaven came to earth a fruit known as Magic fruit.Unfortunately the fruit was found by two friends X and Y. After lot of fighting,they came to the conclusion that they will share the fruit if and only if when they can divide it into two even weighing parts without wasting any part of fruit. Give...
n=int(raw_input()) if(n==2 or n==0): print "NO" elif(n%2==0): print "YES" else: print "NO"
Today Oz is playing a new game. He has an array arr[] of N distinct integers . In each turn he is will follow two actions - 1) He select a random number from arr[]. Say value of this element is X. 2) He will remove X from arr[]. if X-1 is present in arr[] then he will remove it. if X+1 is present in arr[] then he will...
from math import ceil def getCnt(n): return int(round(float(n)/float(2))) for t in xrange(input()): L =input() cnt = 0 ar = sorted(map(int,raw_input().split(' '))) #print 'ar', ar if not ar : continue elif L == 1: print 1 continue i = 1 seq_len = 1 while i < L: #print i,ar[i-1],ar[i] i...
Professor Hatim is researching the sexual behavior of a rare species of lizard. He assumes that they feature two different genders and that they only interact with lizard of the opposite gender. Each lizard has a integer printed on their back. Given the details of lizard interactions, decide whether the experiment sup...
for _ in range(int(raw_input())): n,m=map(int,raw_input().split()) a=[[] for i in range(n)] color=[0]*n def bipartite_visit(v,clr): color[v]=clr for i in range(len(a[v])): if color[a[v][i]]==color[v]: return 0 elif color[a[v][i]]==0: ...
Sherlock rolls a N faced die M times. He adds all the numbers he gets on all throws. What is the probability that he has a sum of K. A N faced die has all numbers from 1 to N written on it and each has equal probability of arriving when dice is thrown. Input First line T, the number of testcases. Each testcase co...
import sys f = sys.stdin dp = [0] * (51) for i in range(0,51) : dp[i] = [0] * (2501) def solve(n,m,k) : if m == 0 and k == 0 : return 1 if m <= 0 : return 0 if k <= 0 : return 0 if dp[m][k] != -1 : return dp[m][k] dp[m][k] = 0 for i in range(1,n+1) : dp[m][k] += solve(n,m-1,k-i) return dp[m][k] ...
There is a street by the name of colorful street in the Pretty Town. The residents of the house have decided that they will paint their houses in either Pink, Orange or Yellow color and not other. They have also decided that no two adjacent houses will have the same color. For house i, i-1 and i+1 are the neighbors and...
import sys def find_cost(): testcases = int(sys.stdin.readline()) output = [] for x in range(testcases): num_of_houses = int(sys.stdin.readline()) cost_of_color = cost_table(num_of_houses) dp = [[0 for i in range(3)] for i in range(num_of_houses)] for i in range(3): ...
Xenny had N cubes. Each cube had six faces and each face had a Latin character on each of it's sides. Xenny's friend Asdoc had an interesting activity in mind. He gave Xenny a string S and asked him to use the cubes to form that string. Xenny being a very lazy person, just wanted to randomly roll the cubes and then ar...
MOD=1000000007 n,k =map(int, raw_input().split()) c=[] for i in range(n): c.append(raw_input().split()) s=raw_input() def choose(l,chosen): cnt=0 if l==k: return 1 for i in range(n): if not (chosen & (1<<i)): chosen |=1<<i ...
There are two persons, numbered 0 and 1, and a variable x whose initial value is 0. The two persons now play a game. The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N): * Person S_i does one of the following: * Replace x with x \oplus A_i, where \oplus represents bitwise X...
#include <bits/stdc++.h> using namespace std; typedef long long i64; const int MAX = 1e6 + 10; const int MOD = 1e9 + 7; const int oo = 1e9; int main(){ ios::sync_with_stdio(false); cin.tie(0); #define endl '\n' int T; cin >> T; while(T--){ int n; cin >> n; vector<i64> A(n); for(int i = 0; i <n; i++)cin >> A...
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown. We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this ...
n, k = map(int, input().split()) p = list(map(int, input().split())) s = sum(p[:k]) m = s for i in range(1, n-k+1): s = s-p[i-1]+p[i+k-1] if s > m: m = s print((m+k)/2)
Takahashi is going to set a 3-character password. How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)? Constraints * 1 \leq N \leq 9 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the number of possibl...
#include<bits/stdc++.h> using namespace std; int a; int main() { cin>>a; cout<<a*a*a; }
The beauty of a sequence a of length n is defined as a_1 \oplus \cdots \oplus a_n, where \oplus denotes the bitwise exclusive or (XOR). You are given a sequence A of length N. Snuke will insert zero or more partitions in A to divide it into some number of non-empty contiguous subsequences. There are 2^{N-1} possible ...
import java.util.*; public class Main { public static void main(String[] args) { long MOD = (long)Math.pow(10, 9) + 7; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int[] b = new int[n + 1]; b...
You are given an integer N that has exactly four digits in base ten. How many times does `2` occur in the base-ten representation of N? Constraints * 1000 \leq N \leq 9999 Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 1222 Output 3 Input 34...
#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int cnt = 0; for(int i=0;i<s.length();i++){ if(s[i]=='2'){ cnt++; } } cout<<cnt; }
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`. You will appoint one of the N people as the leader, then command the rest of the...
N = input() s = input() #累積和 前処理 Eの数を集計 count = s.count('E') ans = count #左端1番目からリーダーをずらしながらチェック。 for ch in s: if ch == 'E': count -= 1 ans = min(count,ans) else: count += 1 print(ans)
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10. Given an integer N, determine whether it is a Harshad number. Constraints * 1?N?10^8 * N is an integer. Input Input is given from Standard Input in the following format: N Output...
#2019/09/26 N = input() print("Yes" if int(N) % sum(map(int, N)) == 0 else "No")
Fennec and Snuke are playing a board game. On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the g...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; vector<int> mp[maxn]; int n, sz[maxn], dep[maxn], fa[maxn]; int dfs(int u, int f, int d){ dep[u] = d; fa[u] = f; sz[u] = 1; for(auto &v:mp[u])if(v != f){ int ret = dfs(v, u, d + 1); sz[u] += ret; } return s...
Snuke has decided to play a game using cards. He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written. He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of...
N = int(input()) A_arr = [int(x) for x in input().split()] A_set = set(A_arr) ans = len(A_set) if ans%2 == 0: ans -= 1 print(ans)
Two circles A, B are given on a two-dimensional plane. The coordinate of the center and radius of circle A is (x_A, y_A) and r_A respectively. The coordinate of the center and radius of circle B is (x_B, y_B) and r_B respectively. These two circles have no intersection inside. Here, we consider a set of circles S that ...
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZER...
Create a program that outputs the surface area S of a square cone with a height of h, with a square with one side x as the base. However, assume that the line segment connecting the apex and the center of the base is orthogonal to the base. Also, x and h are positive integers less than or equal to 100. Input Given mu...
#include <iostream> #include <cmath> #include <cstdio> using namespace std; int main() { int x, h; while (cin >> x >> h) { if (x == 0 && h == 0) break; printf("%.6lf\n", x * x + hypot(x / 2.0, h) * x * 2.0); } }
I decided to play rock-paper-scissors with a group of five good friends. Rock-paper-scissors has three hands: goo, choki, and par. If the game between goo and choki is a match between goo and choki, goo is "winning" and choki is "losing". , Par and Goo have the rule that Par is "winning" and Goo is "losing". If everyon...
#include<iostream> using namespace std; int main(){ int h[5]; int f[4]; while(1){ for(int i=0;i<4;i++) f[i]=0; for(int i=0;i<5;i++){ cin>>h[i]; if(h[i]==0) break; f[h[i]]=1; } if(h[0]==0) break; int x[2], cnt=0; for(int i=1;i<4;i++){ if(f[i]==1) x[cnt++]=i; ...
A project is underway to build a new viewing tower in Bange town called “Bange Hills Tower” whose selling point will be the gorgeous view of the entire main keep of Wakamatsu Castle from top to bottom. Therefore, the view line from the top of the tower must reach the bottom of the keep without being hindered by any of ...
#include <bits/stdc++.h> using namespace std; int main(){ int n; double t; cin>>n>>t; double a[n]; for(int i=0;i<n;i++){ double x,h; cin>>x>>h; a[i]=h/x; if(a[i]>=a[0]){ a[0]=a[i]; } } printf("%lf", a[0]*t); return 0; } ...
You are a craftsman who makes dumplings. Now you are about to skewer the dumplings. The dumplings are arranged in a square divided into N rows vertically and M columns horizontally. Each square contains one dumpling. Each dumpling has one of the colors red (R), green (G), and white (W). You can take dumplings from thr...
#include <bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; char s[5000][5000]; int dp[5000][2][2]; int n,m; int solve(int x,int y){ memset(dp,0,sizeof(dp)); for(int i=y;i<m;i++){ int j=x-(i-y); if(j<0)break; rep(k,2)rep(l,2){ if(j+2<n&&s[j][i]=='R'&&s[j+1][i]=='G'&&s[j+2][i]=='W'&...
Once upon a time, there was a traveler. He plans to travel using stagecoaches (horse wagons). His starting point and destination are fixed, but he cannot determine his route. Your job in this problem is to write a program which determines the route for him. There are several cities in the country, and a road network ...
#include <cstdio> #include <vector> using namespace std; #define INF 2000000000 #define pb push_back int N,M,P,a,b; int t[10]; struct edge { int to; double cost; edge(int to,double cost):to(to),cost(cost){} }; vector<edge> g[40]; double dp[40][1<<8]; double rec(int v,int bit) { if(dp[v][bit]!=-1)return dp[v][bit]; ...
Given an undirected weighted graph G, you should find one of spanning trees specified as follows. The graph G is an ordered pair (V, E), where V is a set of vertices {v1, v2, ... , vn} and E is a set of undirected edges {e1, e2, ... , em}. Each edge e ∈ E has its weight w(e). A spanning tree T is a tree (a connected ...
#include <bits/stdc++.h> #define rep(i, a, n) for(int i = a; i < n; i++) #define REP(i, n) rep(i, 0, n) #define repb(i, a, b) for(int i = a; i >= b; i--) #define all(a) a.begin(), a.end() #define int long long #define chmax(x, y) x = max(x, y) #define chmin(x, y) x = min(x, y) using namespace std; typedef pair<int, int...
At University A, there were many mistakes in entering IDs. Therefore, University A decided to issue a new ID to prevent typos. There is a way to check if the new ID is correct to prevent typos. ・ Calculate the sum of all digits. ・ However, the number of even-numbered digits is doubled, with the rightmost digit as th...
#include <stdio.h> #include <vector> using namespace std; #define PB push_back const int N=1e5+10; int two(int n){ n<<=1; return n/10+n%10; } int main(){ int a[10][2],n,m,temp; bool f=true,mul; vector<int> v; char c[N]; scanf("%d",&n); scanf("%s",c); scanf("%d",&m); while(m--){ ...
<!-- Problem F --> Flipping Colors You are given an undirected complete graph. Every pair of the nodes in the graph is connected by an edge, colored either red or black. Each edge is associated with an integer value called penalty. By repeating certain operations on the given graph, a "spanning tree" should be for...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define REP(i,n) for(int i=0,_n=(int)(n);i<_n;++i) #define ALL(v) (v).begin(),(v).end() #define CLR(t,v) memset(t,(v),sizeof(t)) template<class T1,class T2>ostream& operator<<(ostream& os,const pair<T1,T2>&a){return os<<"("<<a.first<<","<<a.second<< "...
In the Bitwise Kingdom, located somewhere in the universe, there are exactly 2N citizens living and each of them has a unique identification string that represents his or her class in the society. An identification string is a binary string of length N which consists of characters ‘0’ or ‘1’. The order of classes is de...
#include <string> #include <vector> #include <cstring> #include <iostream> #include <queue> #include <map> #include <set> #include <algorithm> #include <cstdlib> #include <cmath> #include <cctype> #include <bitset> #define vi vector < int > #define mod 1000000007 #define inf 987654321 #define dinf -inf #define lo long ...
ICP city has an express company whose trucks run from the crossing S to the crossing T. The president of the company is feeling upset because all the roads in the city are one-way, and are severely congested. So, he planned to improve the maximum flow (edge disjoint paths) from the crossing S to the crossing T by rever...
#include <cstdio> #include <algorithm> #include <map> #include <queue> #define REP(i,n) for(int i=0; i<(int)(n); i++) #define f first #define s second #define mp make_pair using namespace std; typedef vector<vector<int> > G; int flow(G &g, int s, int d){ int n = g.size(); int ans = 0; while(true){ vector...
Once upon a time, in a fantasy world far, far away, monsters dug caves and dungeons for adventurers. They put some obstacles in their caves so it becomes more difficult and more exciting for the adventurers to reach the goal. One day, Emils, one of the monsters in the caves, had a question about the caves. How many pa...
#include <cstdio> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloa...
Ciel, an idol whose appearance and behavior are similar to a fox, is participating in a rehearsal for the live concert which takes place in a few days. To become a top idol, a large amount of effort is required! The live stage can be expressed as a two-dimensional surface. The live stage has N spotlights to illuminate...
#include <bits/stdc++.h> using namespace std; #define fi first #define se second #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #define mmax(x,y) (x>y?x:y) #define mmin(x,y) (x<y?x:y) #define maxch(x,y) x=mmax...
F: Exactly --Kitsuchiri - problem Chisato Aizu, who is in the second year of Wakagamatsu High School, feels sorry if the sequence is not "tight". According to Mr. Aizu, a "tight" sequence is a sequence that is even in length and symmetrical. That is, for a sequence S of length N (N is an even number), the sequence S...
#include<iostream> #include<vector> #include<cassert> #include<string> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cmath> #include<stack> #include<queue> #include<set> #include<map> #include<tuple> #include<numeric> using namespace std; typedef pair<int,int> pii; typedef long long ll; typedef ll in...
Fox Jiro is one of the staffs of the ACM-ICPC 2018 Asia Yokohama Regional Contest and is responsible for designing the network for the venue of the contest. His network consists of $N$ computers, which are connected by $M$ cables. The $i$-th cable connects the $a_i$-th computer and the $b_i$-th computer, and it carries...
//#pragma GCC optimize ("O3") //#pragma GCC target ("avx") #include <stdio.h> #include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> #include <cstdio> #include <ctime> #include <assert.h> #include <chrono> #include <random> #include <numeric> #include <set> #include <deque> #include ...
Problem Ghosts line up in a straight line from left to right with $ N $ people. At first, the $ i $ th ghost from the left is facing left if $ U_i $ is'L', and facing right if it is'R'. They are so timid that I don't want to see scary ghosts as much as possible. You can instruct each ghost to look back. It's scary t...
#include<iostream> #include<algorithm> using namespace std; //Dinic O(EV^2) #include<algorithm> #include<utility> #include<vector> #include<queue> #include<limits> template<typename T> struct MF{ vector<vector<pair<pair<int,int>,T> > >G; vector<int>level,iter; MF(int n_=0):G(n_),level(n_),iter(n_){} void add_edge(i...
For a given polygon g, computes the area of the polygon. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of g. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints ...
#include <iostream> #include <cmath> #include <complex> #include <tuple> #include <vector> using namespace std; using vec = complex<double>; using line = pair<vec,vec>; using polygon = vector<vec>; const double eps = 0.0000001; double inner_product(vec u,vec v){ return real(u*conj(v)); } double cross_product(vec ...
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and rotate specified elements by a list of the following operation: * rotate($b, m, e$): For each integer $k$ ($0 \leq k < (e - b)$), move element $b + k$ to the place of element $b + ((k + (e - m)) \mod (e - b))$. Constraints * $1...
#include<bits/stdc++.h> using namespace std ; int main() { int n; cin >> n ; int v[n]; int i; for(i=0;i<n;i++) { cin >> v[i] ; } int q ; cin >> q ; while(q--) { int a,b,c; cin >> a >>b>>c; rotate(v+a,v+b,v+c); } for(i=0;i<n;i++) { ...
One day Chini while digging his ancestral farmland found the 2 boxes. He opened the 1st box, it was empty while in the second, there was 3 piles of gold coins. Whenever he chooses a pile of Y coins (y ≥ 1) from 2nd box, the coins in the 1st box increases by Y but only one gold coin gets reduced from the pile in the 2n...
def index(a): m=0 ind=0 for i in range(len(a)): if a[i]>m: m=a[i] ind=i return ind t=input() while(t>0): t-=1 a=map(int,raw_input().split()) n=input() count=0 for i in range(n): k=index(a) if a[k]>=1: count+=a[k] ...
You have a list of N numbers. You are deleting D numbers from the list. Print the minimum sum that can be obtained by adding the remaining numbers after deleting exactly D numbers from the list.  Input The first line will contain an integer T representing the number of test cases. Each test case will begin with two s...
for i in range(input()): test1 = map(int,raw_input().split()) test2 = map(int,raw_input().split()) test2.sort(reverse=True) test3 = test2[test1[1]:len(test2)] count = 0 for x in test3: count += x print count
Given three integers x, m and n. Evaluate (1 + x + x^ 2 + .. + x^ m) (mod n) Input First line of the input contains a single integer T representing number of test cases that follow. For next T lines, each line contains three space separated integers x, m and n. Output Output exactly T lines each containing the...
t=int(raw_input()) for _ in range(t): x,m,n=map(int,raw_input().split()) if n==1: print 0 elif x==1: print (m+1)%n else: b = (x-1)*n ans=pow(x,m+1,b) ans-=1 ans%=b ans/=x-1 print ans
Haku Kale now wants to loot in a global scale. For that he needs the help of some underground gang leaders. But the problem is, he does not know the name of any gang leader. After a deep research, he got the name of gang leaders in an encrypted form. After spending months in decrypting it, he found the way to decrypt t...
t=input() while t>0: n=input() B=[] for i in xrange(n): A=raw_input() A=sorted(A) B.append(A[len(A)/2]) print "".join(B) t=t-1
Petr, Nikita G. and Nikita are the most influential music critics in Saint-Petersburg. They have recently downloaded their favorite band's new album and going to listen to it. Nikita claims that the songs of entire album should be listened strictly in the same order as they are given, because there is the secret messag...
def expectation(n): exp = 0.0 for i in range(1, n + 1): exp += 1.0 / float(i) print(exp * n) t = input() for i in range(0, t): n = input() expectation(n)
Oh, no! Chef’s in trouble. He’s got himself stuck in a cave (we don’t know how) and is looking for a way out. The bigger problem is that he needs to get his tractor out of the cave (don't ask why Chef owns a tractor!). He currently faces a large block of height N cells and length N cells, and needs to get his tractor a...
# cook your code here for _ in range(int(raw_input())): n,h=map(int,raw_input().split()) a=[0]*(n+2) for i in range(n): l,r=map(int,raw_input().split()) a[l+1]+=1 a[r+2]-=1 for i in range(1,n+1): a[i]=a[i]+a[i-1] for i in range(n+1): a[i]=a[i]+a[i-1] print...
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m. The wildcard character '*' in the string s (if any) can be replace...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } long long mod = (long long)1e9 + 7; void solve() { long long n, m; cin >> n >> m; string s, t; cin >> s >> t; long long ps1 = 0, ps2 = n - 1, pt1 = 0, pt2 = m - 1; long l...
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected su...
#include <bits/stdc++.h> using namespace std; vector<vector<int>> g; vector<bool> isMy; set<int> other; vector<bool> used; int find(int v) { if (used[v]) return -1; if (isMy[v]) return v; used[v] = true; for (int x : g[v]) { int val = find(x); if (val != -1) return val; } return -1; } int main() { ...
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≤ a_{2}, a_{n} ≤ a_{n-1} and a_{i} ≤ max(a_{i-1}, ...
#include <bits/stdc++.h> using namespace std; const int M = 201, mod = 998244353; int dp[M][2], ndp[M][2]; void modAdd(int &a, int b) { a += b; if (a >= mod) a -= mod; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; memset(dp, 0, sizeof(dp)); dp[0][1] =...
King Kog got annoyed of the usual laxity of his knights — they can break into his hall without prior notice! Thus, the King decided to build a reception with a queue where each knight chooses in advance the time when he will come and how long the visit will take. The knights are served in the order of the recorded time...
#include <bits/stdc++.h> using namespace std; const int N = 300005; const int M = 1000007; struct Node { long long sum, suf; Node Merge(const Node& nd) { Node ret; ret.sum = sum + nd.sum; ret.suf = max(suf + nd.sum, nd.suf); return ret; } }; int q; int tt[N], dd[N]; int add[M]; Node T[M << 2]; voi...
The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of...
#include <bits/stdc++.h> using namespace std; template <class T, size_t n> ostream &operator<<(ostream &os, array<T, n> V) { os << "["; for (auto vv : V) os << vv << ","; return os << "]"; } template <class L, class R> ostream &operator<<(ostream &os, pair<L, R> P) { return os << "(" << P.first << "," << P.seco...
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
import java.io.IOException; import java.util.*; import java.util.Map.Entry; public class Codechef2{ static FasterScanner in = new FasterScanner(); public static void main(String[] args) throws Exception { int n = in.nextInt(); int [] arr = in.nextIntArray(n); ArrayList<Integer> al = new ArrayList<>(); int ...
You are given a set of points x_1, x_2, ..., x_n on the number line. Two points i and j can be matched with each other if the following conditions hold: * neither i nor j is matched with any other point; * |x_i - x_j| ≥ z. What is the maximum number of pairs of points you can match with each other? Input T...
import java.util.Arrays; import java.util.Scanner; public class Main2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int z = scanner.nextInt(); int [] arr = new int[n+1]; for (int i = 1; i <= n; i++) { ...
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one. There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centime...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 500; long long dp[MAXN][MAXN], a[MAXN], n, m; long long calc(long long l, long long r) { if (r < 0 || l < 0 || r >= n || l >= n) return 1; long long& val = dp[l][r]; if (val != -1) return val; if (l >= r) return val = 1; long long mn_ind = l...
You are given two integers b and w. You have a chessboard of size 10^9 × 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white. Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) { int b, w, s = 2; cin >> b >> w; swap(b, w); if (b > w) swap(b, w), s = 3; if (b * 3 + 1 < w) { cout << "NO" << endl; continue; } cout << "YES" << endl; for (int i ...
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (...
#include <bits/stdc++.h> using namespace std; set<pair<long long, pair<long long, long long> > > st; set<pair<long long, pair<long long, long long> > >::iterator it; set<pair<long long, long long> > sl; set<pair<long long, long long> >::iterator kt; long long x[300005], y[300005], siz[300005], parent[300005], z[300005]...
This is an easier version of the problem. In this version, n ≤ 2000. There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even. You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove...
#include <bits/stdc++.h> using namespace std; struct Point { int x, y, z; int idx; Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {} bool operator<(const Point& XD) const { if (x != XD.x) return x < XD.x; if (y != XD.y) return y < XD.y; return z < XD.z; } Point operator-(const Point& ...
Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge. n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridg...
import java.awt.event.MouseAdapter; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run(); } static int groups = 0; static int[] fa; static int[] sz; ...
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands. The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them ...
import java.util.*; public class Solution { public static void main(String args[]) { Scanner s= new Scanner(System.in); int t=s.nextInt(); while(t>0) { int a=s.nextInt(); int b=s.nextInt(); int c=s.nextInt(); int flag=0; ...
Guy-Manuel and Thomas are planning 144 trips around the world. You are given a simple weighted undirected connected graph with n vertexes and m edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 3 which passes t...
#include <bits/stdc++.h> using namespace std; const int N = 100005; const int S = 405; struct edge { int to, next, v; } e[N * 2]; int head[N], tot, n, m; int dep[N], v[N]; int vis[N], flg[N]; int nd, tr[S][35]; int trr[S][S]; map<long long, int> mp; long long sta[S]; void add(int x, int y, int v) { e[++tot] = (edge...
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realiz...
import java.io.*; import java.util.*; public class Main { public static int lower_bound(int[] A, int low, int high, int x) { if (A[low] >= x) { return low; } else if (A[high] < x) { return high + 1; } while (low <= high) { int mid = (low + high) / 2; if (A[mid] < x) { low = mid + 1; } else ...
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
def main(): T = int(input()) for t in range(T): n,a,b,c,d = list(map(int,input().split())) pos = True if((a-b)*n>(c+d)): pos = False elif((a-b)*n < (c-d)) and ((c-d)-(a-b)*n) > 2*b*n: pos = False print("YES") if pos else print("NO") ...
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so. Input The first line of the input contains a single integer t (1≤ t ≤...
from sys import stdin,stdout lis=lambda:list(map(int,input().split())) Ma=lambda:map(int,input().split()) inte=lambda:int(input()) st=lambda:input() import math from collections import Counter for i in range(inte()): n,x=Ma() a=lis() o=0;e=0 for i in a: if i%2==0: e+=1 else:o...
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects can be any letter from the first 20 lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problems independen...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int T, n; char a[N], b[N]; int to[25], fa[25]; bool dag[1 << 20]; int find(int x) { return x == fa[x] ? x : find(fa[x]); } int main() { cin >> T; while (T--) { cin >> n >> (a + 1) >> (b + 1); for (int i = (1); i <= (20); ++i) fa[i] = i, to...
Let a_1, …, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated). The weight of a is defined as the maximum number of elements you can remove. You must answer q independent queries...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class Task5 { int[] tree; int[] lazy; int[] max; int n...
Mr. Chanek has an orchard structured as a rooted ternary tree with N vertices numbered from 1 to N. The root of the tree is vertex 1. P_i denotes the parent of vertex i, for (2 ≤ i ≤ N). Interestingly, the height of the tree is not greater than 10. Height of a tree is defined to be the largest distance from the root to...
#include <bits/stdc++.h> using namespace std; int n, q, ans[50005], sum[50005], a[50005], p[50005], x[50005], cont, pos, us[50005]; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> q; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 2; i <= n; i++) cin >> p[i]; for (int i = 0; i <...
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the...
#include <bits/stdc++.h> std::ifstream fin("input.txt"); std::ofstream fout("output.txt"); int n, value; int x[200005], a[200005], freq[105]; bool foundSolution; void readInput() { std::cin >> n; for (int i = 0; i < n; i++) std::cin >> x[i]; } bool sortCond(std::pair<int, int> a, std::pair<int, int> b) { return a...
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle. Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need...
import sys def solve(): sys.stdin.readline() n, m = map(int,sys.stdin.readline().split()) dudes = [] for i in range(m): r, c = map(int,sys.stdin.readline().split()) dudes.append((c,r)) dudes.sort() dudes.reverse() cells = [] while dudes: if not cells or cells[-1][0]!=dudes[-1][0]: cells.append(dudes[-...
You have a board represented as a grid with 2 × n cells. The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black. You have w white dominoes (2 × 1 tiles, both cells are colored in white) and b black dominoes (2 × 1 tiles, both cells are col...
for _ in range(int(input())): n,k1,k2=[int(x) for x in input().split()] w,b=[int(x) for x in input().split()] if k1>k2: if w<=k2+((k1-k2)//2) and b<=n-k1+((k1-k2)//2): print("YES") else: print("NO") else: if w<=k1+((k2-k1)//2) and b<=n-k2+((k2-k1)//2): print("YES") else: ...
This is an interactive problem. This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4. Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polyc...
import java.util.*; import java.io.*; public class F1{ private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main (String[] args) throws IOException { String nt[...
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on o...
#include <bits/stdc++.h> using namespace std; long long x1, x2, a, b; int main() { cin >> x1 >> x2 >> a >> b; long long dx = x1 - x2; if (a <= 0 && 0 <= b) { if (-b <= dx && dx <= -a) { puts("FIRST"); cout << x1 - dx << endl; } else puts("DRAW"); return 0; } if (dx * a > 0) { ...
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation...
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to d. You are given string s, consisting ...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; int exp(int x, int n) { int ret = 1; while (n) { if (n & 1) ret = 1LL * ret * x % mod; x = 1LL * x * x % mod; n >>= 1; } return ret; } int inv(int x) { return exp(x, mod - 2); } int po[400010], invp[400010]; int N, D; string S, T...
You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integer...
#include <bits/stdc++.h> using namespace std; int n, m, ans, cnt, tot, flag, s; int dist[20][20], deg[20], mp[20], dp[1 << 16], vis[20]; void solve() { int i, j, k, t; for (i = 1; i <= n; i++) dist[i][i] = 0; for (k = 1; k <= n; k++) { for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { dist[i...
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote...
#include <bits/stdc++.h> const long long inf = 1e9; const long double eps = 1e-6; const long long N = 1e6; const long long M = 1e6; using namespace std; void ret(string s) { cout << s; exit(0); } string s; int a[100][100], b, ans = 0; int mx, mn, len = 0, pos, n, k, h; bool u[1000]; int main() { cin >> n >> k; ...
Emuskald was hired to design an artificial waterfall according to the latest trends in landscape architecture. A modern artificial waterfall consists of multiple horizontal panels affixed to a wide flat wall. The water flows down the top of the wall from panel to panel until it reaches the bottom of the wall. The wall...
#include <bits/stdc++.h> using namespace std; const int MAX = int(1e5) + 10; const int oo = 1000000005; struct line { int h, l, r, dp; set<int> ptr; line() {} line(int h, int l, int r) : h(h), l(l), r(r), dp(-1) {} bool operator<(const line &B) const { if (h != B.h) return h < B.h; return r < B.r; }...