input
stringlengths
29
13k
output
stringlengths
9
73.4k
Panda has become a scientist recently. In his laboratory, there are infinite number of chambers where a chamber number K is connected to a chamber number K-1. The numbering of chambers start from 0. Initially, X number of particles are present in the chamber number 0. The number of particles present in chamber K is ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' mx, mod = 1000013, 1000003 arr = [0]*mx arr[0] = 1 for i in xrange(1, mx): arr[i] = i * arr[i-1] arr[i] %= mod tc = int(raw_input()) while tc>0: tc = tc - 1 ...
Oz and nakul have N robots, and they want to assign a distinct integer to each robot so that they can easily identify them. Also robots have already expressed their preferences to Oz and nakul. The k-th robot wants an integer between 1 and MAX[k], inclusive. Oz and nakul must obey the preferences of all their robots. N...
import collections import math def numberOfWaysToMark(): N=int(raw_input()) maxList=[int(v) for v in raw_input().strip().split()] maxList.sort() ways=1 for x in range(N): if maxList[x]<x+1: return 0 else: ways*=(maxList[x]-x) return ways%1000000007 for t...
The ATM machine of State Bank of Patiala on Thapar Campus has a flaw in it and it takes a lot of time to complete a transaction. This machine is quite different from other's as it needed no card. Only thing it required is customer's unique ATM PIN and then his/her password. The Bank found out that the ATM PIN validatio...
def check(a,l): for i in range(0, l-1): x = len(a[i]) j = i+1 if(len(a[j])>=x and a[i]==a[j][0:(x)]): return 1 return 0 t=int(raw_input()) while(t>0): t = t - 1 n = int(raw_input()) a = [] while(n>0): n -= 1 a.append(raw_input()) a.sort() if check(a,len(a))==1: print('NO') else: print('YE...
You are given two arrays each with N elements. Elements of each arrays follow a particular generator dependent on factors a,b and c . You have to choose on element from both the arrays such that if you chose i^th element from one array and j^th element from another array then i should not be equal to j and sum of the ...
a, b, c = map(int, raw_input().split()) n = int(raw_input()) aa = (a*b*c + a*b + a*c) % 1000000007 bb = (a*b*c + a*b + b*c) % 1000000007 p = a*c ma1 ,ma2 = p, 1000000007 ia1 = ia2 = 0 for i in xrange(1, n): C = p * aa % 1000000007 if C < ma2: if C < ma1: ma2 = ma1 ia2 = ia1 ...
Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N. Now, he will choose one square and place the piece on that square. Then, he will make the following move some n...
n,k=map(int,input().split()) p=list(map(int,input().split())) c=list(map(int,input().split())) for i in range(n): p[i]-=1 ans=max(c) for i in range(n): f=i r=0 l=[] while True: f=p[f] l.append(c[f]) r+=c[f] if f==i: break t=0 for j in range(len(l))...
Given is an integer sequence A_1, ..., A_N of length N. We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen. Find the maximum possible sum of the chosen elements. Here \lfloor x \rfloor denotes the greatest integer not greater than x. ...
import java.util.Scanner; public class Main { public static void main(String[] args) { //No MLE! Scanner input = new Scanner(System.in); int N = input.nextInt(); long[][] dp; long[] arr = new long[N]; for (int i = 0; i < N; i++) { arr[i] = input.nextLong(); } if (N%2==0) { dp = new long[N/2][2];...
N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green. The person numbered i says: * "In front of me, exactly A_i people are wearing hats with the same color as mine." Assuming that all these statements are correct, find the number of p...
import java.util.Scanner; public class Main { public static void main(String[] args) { 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(); } long MOD = 1_000_000_007; ...
There are N points in a D-dimensional space. The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}). The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}. How many pairs (i, j) (i < j) are there such ...
def distance(a, b): cont = 0 for k in xrange(len(a)): cont += (a[k] - b[k]) * (a[k] - b[k]) return cont ** 0.5 n, t = map(int, raw_input().split()) ar = [] for i in xrange(n): ar.append(map(int, raw_input().split())) cont = 0 for k in xrange(n): for l in xrange(k + 1, n): if distance(ar[k], ar[l]) == int(d...
Snuke has R red balls and B blue balls. He distributes them into K boxes, so that no box is empty and no two boxes are identical. Compute the maximum possible value of K. Formally speaking, let's number the boxes 1 through K. If Box i contains r_i red balls and b_i blue balls, the following conditions must be satisfie...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef double db; typedef string str; typedef pair<int,int> pi; typedef pair<ll,ll> pl; typedef pair<db,db> pd; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<db> vd; typedef vector<str> vs; typedef v...
There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order. (Assume that the positive x-axis points right, and the positive y-axis points up.) Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4). ...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x1 = sc.nextInt(); int y1 = sc.nextInt(); int x2 = sc.nextInt(); int y2 = sc.nextInt(); int x3 = x2 - (y2 - y1); int y3 = y2 + (x2 - x1); int x4 = x3 ...
In Japan, people make offerings called hina arare, colorful crackers, on March 3. We have a bag that contains N hina arare. (From here, we call them arare.) It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow. We have ...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<char> s(n); string ans = "Three"; for (auto& e: s) { cin >> e; if (e == 'Y') ans = "Four"; } cout << ans << endl; }
A + B balls are arranged in a row. The leftmost A balls are colored red, and the rightmost B balls are colored blue. You perform the following operation: * First, you choose two integers s, t such that 1 \leq s, t \leq A + B. * Then, you repeat the following step A + B times: In each step, you remove the first ball o...
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize("Ofast") #include<iostream> #include<cstdio> #include<cstring> #define ll long long #define p 1000000007 using namespace std; namespace ywy{ int c[4044][4044],f[4044][4044],g[4044][4044]; inline void pre(int n){ c[0][0]=1;for(register int i=1;i<=n...
You are given two positive integers A and B. Compare the magnitudes of these numbers. Constraints * 1 ≤ A, B ≤ 10^{100} * Neither A nor B begins with a `0`. Input Input is given from Standard Input in the following format: A B Output Print `GREATER` if A>B, `LESS` if A<B and `EQUAL` if A=B. Examples Input 3...
import java.util.*; import java.math.BigInteger; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger A = sc.nextBigInteger(); BigInteger B = sc.nextBigInteger(); if(A.compareTo(B) > 0){ System.out.println("GREATER"); }else if(A.compareTo(B)...
Takahashi found an integer sequence (A_1,A_2,...,A_N) with N terms. Since it was too heavy to carry, he decided to compress it into a single integer. The compression takes place in N-1 steps, each of which shorten the length of the sequence by 1. Let S be a string describing the steps, and the sequence on which the i-...
#include <bits/stdc++.h> // #include <boost/multiprecision/cpp_int.hpp> #define int long long #define inf 1000000007 #define pa pair<int,int> #define ll long long #define pal pair<double,double> #define ppap pair<pa,int> #define PI 3.14159265358979323846 #define paa pair<int,char> #define mp make...
Write a program which reverses a given string str. Input str (the size of str ≤ 20) is given in a line. Output Print the reversed str in a line. Example Input w32nimda Output admin23w
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input = scan.next(); for(int i = input.length() - 1; i > -1; i--) { System.out.print(input.charAt(i)); } System.out.println(); ...
The athletics competition 200M semi-final three races were held. Eight players (24 players in total) will participate in each group. A total of eight players, including the top two players in each group and the top two players from all the players in each group who are third or lower, will advance to the final. Create...
#define _USE_MATH_DEFINES #include <iostream> #include <algorithm> #include <functional> #include <vector> #include <cstdio> #include <cstring> #include <cmath> #include <cfloat> #include <map> #include <queue> #include <stack> #include <list> #include <string> #include <set> using namespace std; int main(){ map<dou...
Welcome to PC Koshien, players. Physical condition management is important to participate in the event. It is said that at the turn of the season when the temperature fluctuates greatly, it puts a strain on the body and it is easy to catch a cold. The day you should be careful about is the day when the difference betwe...
#include <iostream> using namespace std; int main() { int x,y,i; for(i=0;i<7;i++){ cin>>x>>y; x=x-y; if(x<0) x=x-0; cout<<x<<endl; } return 0; }
problem There are n cards with numbers from 1 to n. First, make a pile of cards by stacking them in order so that the top is the number 1 card, the second from the top is the number 2 card, ..., and the bottom is the number n card. <image> Sort the cards by performing the following operation called "shuffle (x, y)...
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <sstream> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <stack> #include <map> #include <set> #include <numeric> #include <cctype> #include <tuple> #include <iterator> #include <bit...
Yanagi is a high school student, and she is called "Hime" by her boyfriend who is a ninja fanboy. She likes picture books very much, so she often writes picture books by herself. She always asks you to make her picture book as an assistant. Today, you got asked to help her with making a comic. She sometimes reads her ...
#include <bits/stdc++.h> using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) int const INF = 1<<29; struct frame { int fx, fy; int tx, ty; int id; frame(int fx, int fy, int tx, int ty, int id) : fx(fx), fy(fy), tx(tx), ty(ty), id(id) {} }; inline bool cm...
There is a flat island whose shape is a perfect square. On this island, there are three habitants whose names are IC, PC, and ACM Every day, one jewel is dropped from the heaven. Just as the jewel touches the ground, IC, PC, and ACM leave their houses simultaneously, run with the same speed, and then a person who first...
import java.util.*; import java.awt.geom.*; import static java.lang.Math.*; public class Main { final Scanner sc = new Scanner(System.in); public static void main(String[] args) { new Main(); } Main(){ new AOJ1213(); // System.out.println(Line2D.relativeCCW(0, 0, 0, 2, -1, 0)); } class AOJ1213{ Point2D[...
Example Input 1+2*3+4 11 Output M
#include <iostream> #include <stack> #include <queue> using namespace std; int main() { stack<int> stk; // input string str; int result; cin >> str >> result; // calc M pattern int mresult = 0; int n; for (int i = 0; i < (int)str.size(); i++) { switch (str[i]) { c...
Problem Select 3 grid points from the closed rectangular section surrounded by points (0,0), (n-1,0), (0, m-1), (n-1, m-1) and make a triangle. make. At this time, the absolute difference between the number of triangles containing the point (x1, y1) but not the point (x2, y2) and the number of triangles containing the...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const double EPS=1e-10,pi=M_PI; typedef complex<double> P; double cross(const P& a, const P& b) {return imag(conj(a)*b);} double dot(const P& a, const P& b) {return real(conj(a)*b);} bool cmp(P a, P b) { double at=atan2(a.imag(),a.real()),at2=atan2(b...
Shun and his professor are studying Lisp and S-expressions. Shun is in Tokyo in order to make a presen- tation of their research. His professor cannot go with him because of another work today. He was making final checks for his slides an hour ago. Then, unfortunately, he found some serious mistakes! He called his pro...
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)(n);...
Many cats are kept at the pastry specialty store Stray Cats. The number of cats was so large that the staff at this store, Nozomi, had trouble feeding. Even if you put food in several places, the cats are greedy and will go to the nearest food, and many cats will concentrate in one food container. For rare reasons, you...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define SIZE 1005 struct Info{ bool operator<(const struct Info &arg) const{ return x < arg.x; ...
Example Input 3 1 0 1 Output 18
#include <iostream> #include <cstdio> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <cstring> #include <functional> #include <cmath> #include <complex> using namespace std; #define rep(i,n) for(int i=0;i<(n);++i) #define rep1(i,n) for(in...
H --N and K Consider a narrowly-sense monotonically increasing sequence of integers greater than or equal to 1 and N, in which no matter which two different numbers are taken from the elements of the sequence, the other does not divide one. Let L be the maximum length of such a sequence, and consider such a sequence (...
#include <iostream> #include <vector> #include <array> #include <list> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <tuple> #include <bitset> #include <memory> #include <cmath> #include <algorithm> #include ...
Kuru Kuru Door Round and round door The ICPC (Intelligent Circular Perfect Cleaner), a fully automatic circular vacuum cleaner developed by ACM (Automatic Cleaning Machine) in 2011, has a function to automatically start during the day and clean dust in places where you have passed. In addition, this ICPC also has a f...
import java.awt.*; import java.awt.geom.Ellipse2D; import java.io.*; import java.util.*; import java.util.List; /** * AIZU ONLINE JUDGE * 2705 Kuru Kuru Door * 2018/02/11 */ public class Main { class Graphics2D { void draw(Shape s) { } void setColor(Color c) { } } s...
F: Multiplication is fun --Multiplication Is Interesting - story Namba, a high school boy, is thinking of giving her a few lines on her birthday. She is a girl who loves multiplication, so Namba wants to give her a sequence that will allow her to enjoy multiplication as much as possible. However, when the calculation...
from decimal import * import sys import copy def main(): getcontext().prec = 1000 input = sys.stdin.readline n, k = input().split() n = int(n) k = Decimal(k) a = [Decimal(input()) for i in range(n)] if Decimal(0) in a: print(n) sys.exit() if k == Decimal(0): prin...
E: Red Black Balloons Story Homura-chan's dream comes true. It means ICPC Asia regional contest 20xx will be held in Sapporo! Homura-chan has been working hard for the preparation. And finally, it's the previous day of the contest. Homura-chan started to stock balloons to be delivered to contestants who get accepted....
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define Rep(i,sta,n) for(int i=sta;i<n;i++) const int mod=1000000007; int dp[70][70][6100]; void solve(){ int n,k;cin>>n>>k; vector<int> ra(n+1); vector<int> rr(k+1); vector<int> rb(k+1); vector<int> a(n); vecto...
This is a reactive problem. Problem statement There are $ 200 $ non-negative integers of $ 1000 $ bits, $ a_1, \ ldots, a_ {100}, b_1, \ ldots, b_ {100} $. Alice confirms $ a_1, \ ldots, a_ {100} $ and leaves a note $ X $ for $ 3000 $ bits for Charlie. Bob checks $ b_1, \ ldots, b_ {100} $ and leaves a note $ Y $ f...
import java.util.Scanner; import java.util.SplittableRandom; public class Main { static Scanner sc = new Scanner(System.in); static int[][] idx = new int[30][500]; static SplittableRandom rnd = new SplittableRandom(42); public static void main(String[] args) { String person = sc.next(); int[] pos = new int[1...
A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V...
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <cmath> #include <cstring> #include <utility> #include <numeric> using namespace std; struct Edge{ int to, capacity, revIndex; }; vector<bool> used; int findPass(vector<vector<Edge>>& edge, int node, int t, int flow){ if(n...
The Head Chef has been playing with Fibonacci numbers for long . He has learnt several tricks related to Fibonacci numbers . Now he wants to test his chefs in the skills . A fibonacci number is defined by the recurrence : f(n) = f(n-1) + f(n-2) for n > 2 and f(1) = 0 and f(2) = 1 . Given a number A , determine if...
import sys arr=sys.stdin.read().split() N=int(arr[0]) nos=[] nos1=[] k=0 for i in range(0,N): k+=1 nos.append(int(arr[k])) nos1.append(int(arr[k])) nos1.sort() def bin_search(arr,start,end,x): mid=(start+end)/2 if(end<start): return -1 if(arr[mid]==x): return mid if(arr[mid]>x): return bin_search(arr,...
Chef loves research! Now he is looking for subarray of maximal length with non-zero product. Chef has an array A with N elements: A1, A2, ..., AN. Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj. Product of subarray Aij is product of all its elements (from ith to jth). Input First li...
n=input() s=map(int,raw_input().split()) l=j=0 a=[0]*n for i in s: if i==0: l=0 else: l+=1 a[j]=l j+=1 print max(a)
Chef Shifu and Chef Po are participating in the Greatest Dumpling Fight of 2012. Of course, Masterchef Oogway has formed the rules of the fight. There is a long horizontal rope of infinite length with a center point P. Initially both Chef Shifu and Chef Po will stand on the center P of the rope facing each other. Don...
import fractions import sys tc = int(raw_input()) f = fractions.gcd while tc: tc-=1 a,b,c,d,k = map(int,sys.stdin.readline().split()) g1 = f(a,b) g2 = f(c,d) lcm = (g1*g2)/f(g1,g2) mx = k/lcm print 2*mx+1
Chef Al Gorithm was reading a book about climate and oceans when he encountered the word “glaciological”. He thought it was quite curious, because it has the following interesting property: For every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ 1. Chef Al was happ...
#top down dp # def function(b,i,j,matrix): # if i>=j: # return 0 # if b[j]-b[i]<=k: # return 0 # if matrix[i][j]!=-1: # return matrix[i][j] # #matrix[i][j]=min(b[i]+matrix[i+1][j],matrix[i][j-1]+b[j]-b[i]-k) # m1=b[i]+function(b,i+1,j,matrix) # m2=b[j]-b[i]-k+function(b,i,j-1,matrix) # matrix[i][j]=min(m1,...
This morning Chef wants to jump a little. In a few minutes he will arrive at the point 0. Then he will perform a lot of jumps in such a sequence: 1-jump, 2-jump, 3-jump, 1-jump, 2-jump, 3-jump, 1-jump, and so on. 1-jump means that if Chef is at the point x, he will jump to the point x+1. 2-jump means that if Chef is a...
t=(int)(raw_input()) k=t//3 if((t%3==0)|((t%3==1)&(k%2==0))): print 'yes' else: print 'no'
Starting at the top left corner of an N*M grid and facing towards the right, you keep walking one square at a time in the direction you are facing. If you reach the boundary of the grid or if the next square you are about to visit has already been visited, you turn right. You stop when all the squares in the grid have ...
# cook your code here T = int(raw_input()) for i in range(T): (n,m) = map(int,raw_input().split()) if n<m: if n%2==0: print "L" else: print "R" elif m<n: if m%2==0: print "U" else: print "D" else: if n%2==0: ...
Polycarp likes numbers that are divisible by 3. He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Poly...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; const int mod = 1e9 + 7; int dp[N][3]; string str; int solve(int idx, int m) { if (idx == str.size()) return m == 0; int &ret = dp[idx][m]; if (~ret) return ret; if (m == 0) return ret = solve(idx + 1, (str[idx] - '0') % 3) + 1; return ret =...
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order. You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as...
n=int(input()) a=list(map(int,input().split())) b=[] for _ in range(n-1): if a[_+1]<=a[_]*2: b.append(1) else: b.append(0) b.append(1); s=0; c=[] for i in range(n): if b[i]==1: s+=1 c.append(s) else: s=0 if c[len(c)-1]==max(c) and c.count(max(c))==1: print(max...
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
n=int(input()) if n<11 or n>21: print(0) elif n==20: print(15) else: print(4)
You are given a matrix of size n × n filled with lowercase English letters. You can change no more than k letters in this matrix. Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is f...
#include <bits/stdc++.h> using namespace std; const long long MAX = 2005; const long long INF = 1e9 + 5; char grid[MAX][MAX]; long long dp[MAX][MAX]; auto solve(long long n, long long k) -> string { auto inside = [&](long long row, long long col) { return (row < n and row >= 0 and col < n and col >= 0); }; fo...
You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways t...
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.InputMismatchException; import java.util.LinkedList; /** * @author thesparkboy * */ public class A2 { static long mod = 998244353; static LinkedList<Integer> a...
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t...
#include <bits/stdc++.h> using namespace std; int a[28]; bool check(string s) { for (int i = 0; i < s.size() / 2; i++) if (s[i] != s[s.size() - i - 1]) return false; return true; } int main() { string s; cin >> s; for (auto i : s) a[i - 'a']++; int mx = 0; for (auto i : a) mx = max(i, mx); if (s.siz...
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse2") using namespace std; int solve() { map<int, vector<pair<long long, long long> > > m; int n; cin >> n; vector<long long> a(n + 1); for (int i = 1; i < n + 1; i++) cin >> a[i]; for (int i = 1...
You are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h. In each spot, if a house has height a, you will gain a^2 dollars fro...
#include <bits/stdc++.h> using namespace std; const int N = 100010; const int mod = (int)1e9 + 7; using namespace std; vector<int> c[52]; int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, h, m; cin >> n >> h >> m; int l, r, x; for (int i = 1; i <= m; i++) { cin >> l >> r ...
You have given integers a, b, p, and q. Let f(x) = abs(sin(p/q π x)). Find minimum possible integer x that maximizes f(x) where a ≤ x ≤ b. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case con...
#include <bits/stdc++.h> using namespace std; long long mod_sub(long long a, long long b, long long p) { if (a >= b) return a - b; return p + a - b; } tuple<long long, long long> closest_under(long long p, long long q, long long n, long long T); tuple<long long, long long> ...
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; long long int n; cin >> n; string s; long long int b[10] = {0}; cin >> s; for (long long int i = 0; i < n; i++) { if (s[i] == 'L') { for (long long int j = 0; j < 1...
You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The ...
#include <bits/stdc++.h> using namespace std; const int N = 505; long long dp_hor[2][N][N], dp_vert[2][N][N]; vector<pair<int, int>> cost_hor[N][N], cost_vert[N][N]; long long inf = 1e18; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m, k; cin >> n >> m >> k; for (int i = 1; i <= k; i++) { int ...
There are n football teams in the world. The Main Football Organization (MFO) wants to host at most m games. MFO wants the i-th game to be played between the teams a_i and b_i in one of the k stadiums. Let s_{ij} be the numbers of games the i-th team played in the j-th stadium. MFO does not want a team to have much...
#include <bits/stdc++.h> using namespace std; const int N = 410, K = 5e3 + 10; struct Edge { int u, v; long long cap, flow; int id; Edge() {} Edge(int u, int v, long long cap, int id) : u(u), v(v), cap(cap), flow(0), id(id) {} }; struct Dinic { int N; vector<Edge> E; vector<vector<int>> g; vecto...
You are fed up with your messy room, so you decided to clean it up. Your room is a bracket sequence s=s_{1}s_{2}... s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'. In one operation you can choose any consecutive substring of s and reverse it. In other words,...
import os, sys, math def solve(seq, k): seq = [ 1 if a == '(' else -1 for a in seq ] size = len(seq) result = [] def rotate(fr, to): assert fr <= to result.append((fr + 1, to + 1)) while fr < to: seq[fr], seq[to] = seq[to], seq[fr] fr += 1 to -= 1 # print(''.join('(' if q > 0 else ')' for q in se...
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; //import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static int MD= 998244353 ; ...
This is the hard version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved. n wise men live in a beautiful city. Some of them know each other. For each of the n! possible permutations p_1, p_2, …, p_n of the wise...
#include <bits/stdc++.h> using namespace std; int n, t; long long c[262144], g[262144][18], p[19][262144], r[385]; char e[18][18]; map<vector<int>, int> m; inline void orFMT(long long *a, int n) { for (int i = 1; i < (1 << n); i <<= 1) for (int j = 0; j < (1 << n); j += (i << 1)) for (int k = 0; k < i; ++k)...
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:...
#include <bits/stdc++.h> using namespace std; const int N = 3e3 + 4; const int INF = 0x3f3f3f3f; int n; int a[N], b[N], pos[N]; bool ok[N][N]; inline int read() { int x = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x...
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r. Input The first line contains one integer t (1 ≤ t ≤ 10000) — the number of tes...
#include <bits/stdc++.h> using namespace std; int main() { long long l, r, x; int sum; cin >> sum; for (int i = 1; i <= sum; ++i) { cin >> l >> r; x = l * 2; if (x <= r) cout << l << " " << x << endl; else cout << "-1 -1\n"; } return 0; }
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
for _ in range(int(input())): n,k=[int(x) for x in input().split()] if n%k==0:print(0) else:print(k-(n%k))
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
def solve(): n,k=map(int,input().split()) if n==1: print(0) return ls=list(map(int,input().split())) ls.sort() res=ls.pop() for i in range(k): if ls: res+=ls.pop() print(res) return for _ in range(int(input())): solve()
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage. There is at most one checkpoint on each stage, and there is always a checkp...
t=int(input()) for _ in range(t): n=int(input()) if n%2==1: print(-1) continue ans=[] tmp=0 for i in range(2,62): if 1<<i&n: ans.append('1') for j in range(i-2): ans.append('0') tmp+=1 for i in range(tmp): ans.append('1') if 2&n: ans.append('1') print(len(an...
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better. It is known that Nanako loves consistency so much. On th...
#include <bits/stdc++.h> using namespace std; #define int long long const int maxn = 2e5; pair <int, int> t[4 * maxn + 5]; int sum[4 * maxn + 5]; int a[maxn]; void push(int v, int l, int r) { if (t[v].first == -1) return; if (l == r - 1) { sum[v] = t[v].second; t[v] = {-1, -1}; return; } t[2 * v] = max(t[...
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules: * The empty sequence is balanced. * If [a_1,…,a_n] and [b_1,…, b_m] are balanced, then their concatenation [a_1,…,a_n,b_1,…,b_m] is balanced. * If x is a positive integer and [a_1,…,a_n] is balanced, then ...
#include <bits/stdc++.h> using i64 = int64_t; using u64 = uint64_t; using u32 = uint32_t; void gg() { std::cout << "NO\n"; std::exit(0); } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; std::vector<int> a(2 * n), b(2 * n); std::vector<int> xa(...
You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-n...
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<long long,int> pli; typedef unsigned int ui; #define l(x) ch[x].l #define r(x) ch[x].r #define ls x<<1 #define rs x<<1|1 #define pb push_back #define fi first #define se second const int Inf=0x3f3f3f3f; const int inf=0xcfcfcfcf; const int ...
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo th...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class C159 { public static void main(String[] args) throws Exception { BufferedReader input = new BufferedReader(new InputStream...
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem. You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ...
#include <bits/stdc++.h> const int N = 2010; const double pi = acos(-1), zero = 1e-6; int n, sum, lx, ly, f[N][N], w[N][N]; bool vis[N][N]; void work(int x, int y) { if (!w[x][y] || vis[x][y]) return; sum++; vis[x][y] = true; if (x > lx || (x == lx && y > ly)) { lx = x; ly = y; } work(x - 1, y); w...
Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. L...
n=input() print 5 if 3==n else [i for i in range(1,31,2) if i*i+1>=n*2][0]
Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the ...
#include <bits/stdc++.h> using namespace std; long long a[] = {1, 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, ...
You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center o...
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize("Ofast") template <class T> inline T rd() { T x = 0; long long f = 1; char c = getchar(); while (c > '9' || c < '0') f = c == '-' ? -1 : 1, c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar...
Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some ...
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 10; vector<int> G[N]; int n, m, degi[N], dego[N], drif; vector<vector<int> > mat; void Tsort() { queue<int> q; for (int i = 0; i < drif + 1; i++) { dego[i] = G[i].size(); for (int j = 0; j < G[i].size(); j++) degi[G[i][j]]++; } int total ...
There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint ...
#include <bits/stdc++.h> long long int mod = 1e9 + 7; using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int ans = -1, n, i; cin >> n; string s; cin >> s; for (i = 0; i < n - 1; i++) { if (s[i] == 'R' && s[i + 1] == 'L') { cout << (i + 1) << " " ...
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangeme...
n=input() lst=map(int,raw_input().split()) ans=[] c=0 ans=0 def cm(lst): dp=[] n=len(lst) ans=[] c=0 for i in range(n-1,-1,-1): while len(ans)>0 and lst[i]>ans[-1][0]: c=max(c+1,ans[-1][1]) ans.pop() dp.append(c) ans.append((lst[i],c)) c=0 #print ans return max(dp)...
Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat d...
#include <bits/stdc++.h> using namespace std; int n, m, k, a, i; int main() { cin >> n >> m >> k; for (i = 0; i < n; i++) { cin >> a; if (a == 1) m--; else if (a == 2 && k > 0) k--; else m--; } if (m >= 0) cout << 0; else cout << -m; }
You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using t...
import java.util.Scanner; public class strfolding { public static void main(String args[]) { Scanner sc=new Scanner(System.in); StringBuffer str=new StringBuffer(sc.nextLine()); int ans=1; for(int i=0;i<str.length();i++) { char ch=str.charAt(i); ...
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors. The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CoderStrike2014A { static String find(int min, int max, int curMin, int curMax, int required){ if(curMin<min || curMax>max) return "Incorrect"; if(curMin>min) required--; if(curM...
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings s and t both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string s as quickly as possible. Initially he has empty string, and in one second he can append...
#include <bits/stdc++.h> using namespace std; long long N; char s[100005]; int M, D, A[3000005][4]; struct Mat { long long A[4][4]; Mat() { memset(A, 0, sizeof(A)); } Mat operator*(const Mat& b) { Mat c; for (int i = 0; i <= 3; i++) for (int j = 0; j <= 3; j++) { c.A[i][j] = (1ll << 60); ...
You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj. Input The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105). The second line contains n space-separated integers ai (1 ≤ a...
import java.io.*; import java.util.*; public class Main { static HashMap<Integer,Integer> hm; static int[] last; static final int max = 2000005; public static void main( String args[] ) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int array[] = new int[n]; last = new int[max]; ...
Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a p...
#include <bits/stdc++.h> using namespace std; long long a[105], b[105], w[105][105], e[105][105]; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } void ok(int n, int m, long long k) { printf("YES\n%I64d\n", k); for (int i = 1; i <= n; i++) printf("%I64d%c", a[i] % k + k, " \n"[i == n]); f...
Polycarp invented a new way to encode strings. Let's assume that we have string T, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in T with its pair letter if there is a pair...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; vector<int> ans; string s, t; int n, m; bool f[N][26]; void solve(int a, int b) { string str; str.clear(); for (char c : t) { if (c - 'a' == a) str += c; else if (c - 'a' == b) str += c; else str += '.'; } str +...
This task is very simple. Given a string S of length n and q queries each query is on the format i j k which means sort the substring consisting of the characters from i to j in non-decreasing order if k = 1 or in non-increasing order if k = 0. Output the final string after applying the queries. Input The first line...
#include <bits/stdc++.h> using namespace std; struct ST { int sum[4 * 100000 + 2]; int lazy[4 * 100000 + 2]; ST() { for (int i = 0; i < 4 * 100000 + 2; i++) sum[i] = 0, lazy[i] = -1; } void propagate(int node, int l, int r) { if (lazy[node] == -1) return; for (int i = 0; i < 2; i++) { lazy[2...
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string. More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and ...
#include <bits/stdc++.h> using namespace std; constexpr int MAXN = 100000; char s1[MAXN + 2], s2[MAXN + 2], ans[MAXN + 2]; char neither(char a, char b) { if (a > b) swap(a, b); char x = 'a'; if (a == x) x++; if (b == x) x++; return x; } int main() { int n, t; cin >> n >> t >> s1 >> s2; t = n - t; for ...
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a, b[n + 1]; memset(b, 0, sizeof b); for (int i = 0; i < n; i++) { cin >> a; b[a] = b[a - 1] + 1; } cout << n - *max_element(b, b + n + 1); return 0; }
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only. The distance between two letters is defined as the difference between their positions in the alphabet. For example, <image>, and <image>. Also, the distance between two nice strings is defined as t...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ...
#include <bits/stdc++.h> using namespace std; struct node { int l, r, id; long long ans; } maps[200005]; bool cmp(const node& a, const node& b) { if (a.l == b.l) return a.r > b.r; return a.l < b.l; } bool cmp2(const node& a, const node& b) { return a.id < b.id; } int ans[200005], X[200005 * 2]; int find(int a, ...
The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Tayl...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * // TODO Comment */ public class CF678B { /** Class for buffered reading int and double values */ static class Reader { static BufferedReader reader...
Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Min...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHel...
You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi w...
#include <bits/stdc++.h> using namespace std; int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; int i, n, a; cin >> n; set<int, greater<int>> s; for (i = 0; i < n; i++) cin >> a, s.insert(a); while (1) { int x = *s.begin(); while (x and s.count(x)) x /= 2; if (!x) break;...
This is an interactive problem. In the interaction section below you will see the information about flushing the output. In this problem, you will be playing a game with Hongcow. How lucky of you! Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and col...
#include <bits/stdc++.h> using namespace std; long long bigmod(long long b, long long p) { if (p == 0) return 1; long long my = bigmod(b, p / 2); my *= my; my %= 1000000007; if (p & 1) my *= b, my %= 1000000007; return my; } int setb(int n, int pos) { return n = n | (1 << pos); } int resb(int n, int pos) { ...
Olya likes milk very much. She drinks k cartons of milk each day if she has at least k and drinks all of them if she doesn't. But there's an issue — expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge c...
import java.util.*; import java.io.*; import java.text.DecimalFormat; public class Main{ final long mod = (int)1e9+7, IINF = (long)1e19; final int MAX = (int)1e6+1, MX = (int)1e7+1, INF = (int)1e9, root = 3; DecimalFormat df = new DecimalFormat("0.0000000000000"); double eps = 1e-9, pi = 3.14159265358...
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?). A group of soldiers is effective if and only if their names...
import java.util.*; import java.io.*; /** * Created by sail on 3/18/17 12:13 PM. * Project: Algorithm. */ public class C { FastScanner in; PrintWriter out; private class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedRea...
In his spare time Vladik estimates beauty of the flags. Every flag could be represented as the matrix n × m which consists of positive integers. Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set the...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper...
You have an array f of n functions.The function fi(x) (1 ≤ i ≤ n) is characterized by parameters: x1, x2, y1, a, b, y2 and take values: * y1, if x ≤ x1. * a·x + b, if x1 < x ≤ x2. * y2, if x > x2. There are m queries. Each query is determined by numbers l, r and x. For a query with number i (1 ≤ i ≤ m), y...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; long long mod = 1e9; struct seg { int l, r, mid; long long sum = 0; seg *ch[2] = {NULL, NULL}; void add(seg *prev, int pos, int val) { if (l == r) { sum = prev->sum + val; return; } if (pos <= mid) { ch[1] = prev-...
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them. Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr...
#include <bits/stdc++.h> using namespace std; int Set(int N, int pos) { return N = N | (1 << pos); } int reset(int N, int pos) { return N = N & ~(1 << pos); } bool check(int N, int pos) { return (bool)(N & (1 << pos)); } bool vowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } int mai...
Evlampiy has found one more cool application to process photos. However the application has certain limitations. Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible. Evlampiy already k...
#include <bits/stdc++.h> using namespace std; int n, m, a[300005]; int tree[1200005]; int Erfen(int l, int r, int lim) { int now = l; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] - a[now] <= lim) l = mid; else r = mid - 1; } return l; } void Insert(int x, int l, int r, int pos)...
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating." The class can be represented as a matrix with n rows and m col...
import bisect def list_output(s): print(' '.join(map(str, s))) def list_input(s='int'): if s == 'int': return list(map(int, input().split())) elif s == 'float': return list(map(float, input().split())) return list(map(str, input().split())) n, m = map(int, input().split())...
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc. Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ...
def f(s): return s.lower().replace('1', 'l').replace('0', 'o').replace('i', 'l') s = f(input()) n = int(input()) l = {f(input()) for _ in range(n)} print('No' if s in l else 'Yes')
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: ...
""" ________ _____________ ______ ___ __ \____ ____ __ \__(_)__ _______ ___ / __ /_/ /_ / / /_ /_/ /_ /__ | / / __ `/_ / _ ____/_ /_/ /_ _, _/_ / __ |/ // /_/ /_ / /_/ _\__, / /_/ |_| /_/ _____/ \__,_/ /_/ /____/ https://github.com/Cheran-Senthil/PyRival Copyright (c) ...
You're given a tree with n vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. Input The first line contains an integer n (1 ≤ n ≤ 10^5) denoting the size of the tree. The next n - 1 lines contai...
// package codeForces; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.io.*; import java.math.*; import java.text.*; public class CutEmAll { static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); static int...
Again a simple task from Oz! He has given you two strings STR1 and STR2. Each character of both strings is from the set {A, B, C, D, E, F, G, H, I, J}. You can perform 3 types of conversions on string STR1 : Replace a character(except 'J') by next character from the set. i.e "ABE" to "ACE" Replace a character(excep...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def solution(s1, s2, i): if i == len(s2): return 0 mop = abs(s2[i] - s1[i]) + solution(s1, s2, i + 1) for x in xrange(i + 1, len(s1)): s1[i], s1[x] = s1[x], s1[i] mop = min(mop...
Our hero - Maga has been working on a research related to Pascal’s Triangle for about a month. He has recently found a new problematic thing for his research. He has to calculate a big number. But he is very busy. Could you do it for him? You are given a binomial as this: (a * x + b * y)^n. You have to find the binomi...
import sys f = sys.stdin mod = 1000000007 def inv(x,y): res = 1 while y: if y%2: res = res*x%mod y/=2 x=x*x%mod return res a,b,n,k = [int(x) for x in f.readline().split()] num = 1 deno = 1 for i in range(1,n+1): num = num*i%mod for i in range(1,k+1): deno = deno*i%mod num = num*a%mod for i in range(1...
Abhimanyu simply drew two triangles, as shown in the picture below- He says this, Level 1 Triangles. Then he drew two more triangles, as shown in the picture below- He says this, Level 2 Triangles. Similarly he defined Level 3, 4, 5, ..., N Triangles. You simply need to tell him total no. of triangles in Level N Tria...
tests=input() while(tests>0): n=input() print n*8+(n-1)*6 tests=tests-1
After a furious battle Pirate Jack won a battle against Captain Luthur. Pirate Jack found a golden chest from Luthur's treasures. But the problem is that Luthur's coders have locked this chest. You have found the function which Luthurs Coders wrote to lock this chest: void hack(string s) { for(int i = s.length()-1...
word = raw_input() for i in word: c = -(ord(i))-1 print c,
Recently Oz has found a magical string consisting of single digit "1". After experimenting on the string, Oz found a weird magical property of the string that is whenever he touches the string then each digit "1" of string changed to digit "0" and each digit "0" of string changed to "01". Oz found this property intere...
t = int(raw_input()) iterations = 0 while iterations < t: iterations += 1 zeros=0 ones=1 n = int(raw_input()) for i in range(n): nzeros = ones; nzeros = nzeros + zeros; ones = zeros; zeros = nzeros; print ones,zeros