input
stringlengths
29
13k
output
stringlengths
9
73.4k
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
def gcd(a, b): if a == 0: return b return gcd(b % a, a) a, b,n = map(int,input().split(" ")) while True: n -= gcd(a, n) if n < 0: print("1") break n -= gcd(b,n) if n < 0: print("0") break
The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2...
#include <bits/stdc++.h> using namespace std; long long k; long long check(long long x, int tag) { long long res = 0; for (int i = 1; i <= x; i = i * 10) { if (tag) res += (x - i + 1) * (x - i + 2) / 2; else res += (x - i + 1); } return res; } long long bs(long long l, long long r, int tag) ...
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1...
#### s=raw_input() n=len(s) P = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67, 71,73,79,83,89,97,101,103,107,109,113, 127,131,137,139,149,151,157,163,167,173, 179,181,191,193,197,199,211,223,227,229, 233,239,241,251,257,263,269,271,277,281, 283,293,307,311,313,317,331,337,347,349, 353,...
Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion...
import re import sys s=sys.stdin.readline() result = re.findall('<(\w)>|<(/\w)>',s) indent = 0 for match in result: if (match[1]==''): print ' '*indent+'<'+match[0]+">" indent = indent+2 else: indent = indent-2 print ' '*indent + '<'+match[1]+">"
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r × c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomei...
#include <bits/stdc++.h> using namespace std; long long int MOD = 1e9 + 7; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int t, r, c; cin >> t; while (t--) { cin >> r >> c; vector<string> v(r); for (long long int i(0), ThkMk(r); i < ThkMk; ++i) cin >> v[i]; ...
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he sh...
/* javac d.java && java d */ import java.io.*; import java.util.*; public class d { public static void main(String[] args) { new d(); } FS in = new FS(); PrintWriter out = new PrintWriter(System.out); int n, m, k; d() { n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); int roads = (4 * n * m - 2 ...
Given 2 integers u and v, find the shortest array such that [bitwise-xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of its elements is u, and the sum of its elements is v. Input The only line contains 2 integers u and v (0 ≤ u,v ≤ 10^{18}). Output If there's no array that satisfies the condition, print "...
#include <bits/stdc++.h> using namespace std; const double pi = 3.141592653589; long long int mod = 1000000007; int main() { int t = 1; while (t--) { long long int u, v, x; cin >> u >> v; x = (v - u) / 2; if (u + v == 0) { cout << 0; } else if (u == v) { cout << 1 << endl; cout...
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (∀) and existential (∃). You can read more about them here. The universa...
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class Graph { static class Reader { final private int BUFFER_SIZE = 1 << 16; private Da...
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1. A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit...
import java.util.Scanner; public class Codeforces1366C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt() ; for(int tt =0 ; tt <t ;tt++) { int n = sc.nextInt() , m = sc.nextInt(); int a[][] = new int[n][m]; for(int i = 0 ; i < n ; i++) { fo...
Joker returns to Gotham City to execute another evil plan. In Gotham City, there are N street junctions (numbered from 1 to N) and M streets (numbered from 1 to M). Each street connects two distinct junctions, and two junctions are connected by at most one street. For his evil plan, Joker needs to use an odd number of...
#include <bits/stdc++.h> using namespace std; int n, m, q, rb, a, b, ndw; int kr[200011][2]; int rep[200011]; int roz[200011]; int odl[200011]; int bip[200011]; int rlb[2000000][4]; int odp[200011]; int fin(int x, int &gl) { gl ^= odl[x]; while (x != rep[x]) { x = rep[x]; gl ^= odl[x]; } return x; } voi...
There is a road with length l meters. The start of the road has coordinate 0, the end of the road has coordinate l. There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end ...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, l; cin >> n >> l; double t[n + 2], t1[n + 2], a[n + 2]; for (int i = 1; i <= n; i++) { cin >> a[i]; } t[0] = (double)0; t1[n + 1] = (double)0; a[0] = (double)0; a[n + 1] = (do...
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string s_1s_2… s_n of length n. 1 represents an apple and 0 represents an orange. Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguo...
#include <bits/stdc++.h> using namespace std; const long long N = 1e6 + 5; long long n, ans, sum, a[N]; char s[N]; inline long long read() { long long ret = 0, f = 0; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = 1; c = getchar(); } while (isdigit(c)) { ret = ret * 10 + c - 48; c...
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute: * move north from cell (i, j) to (i, j + 1); * move east from cell (i, j) to (i + 1, j); * move south from cell (i, j) to (i, j - 1); * move wes...
for _ in range(int(input())): n,m=[int(x) for x in input().split()] print(n+m+max(0,abs(m-n)-1))
You are given two binary square matrices a and b of size n × n. A matrix is called binary if each of its elements is equal to 0 or 1. You can do the following operations on the matrix a arbitrary number of times (0 or more): * vertical xor. You choose the number j (1 ≤ j ≤ n) and for all i (1 ≤ i ≤ n) do the follow...
import java.util.Scanner; public class F { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testCase = Integer.parseInt(sc.nextLine()); for(int i=0;i<testCase;i++){ int size = Integer.parseInt(sc.nextLine()); int[][] A = new int[siz...
Kostya is extremely busy: he is renovating his house! He needs to hand wallpaper, assemble furniture throw away trash. Kostya is buying tiles for bathroom today. He is standing in front of a large square stand with tiles in a shop. The stand is a square of n × n cells, each cell of which contains a small tile with col...
/*Lucky_Glass*/ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; inline int rin(int &r) { int b = 1, c = getchar(); r = 0; while( c < '0' || '9' < c ) b = c == '-' ? -1 : b, c = getchar(); while( '0' <= c && c <= '9' ) r = (r * 10) + (c ^ '0'), c = getchar(); return r *= b; } const in...
Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins. The city consists of n halls and m one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int n,m,k; cin >> n >> m >> k; vector<int> v[n+1]; for(int i=1;i<=m;i++) { int a,b; cin >> a >> b; v[a].push_back(b); } vector<ll> x(k+1,0);...
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string s and cut out som...
/* ID: nik3daz1 LANG: JAVA TASK: XXXX */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintStream out = System.out; //CODING TAIM String s = sc.next(); ...
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
import java.util.Scanner; public class Ishu { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n,i,t,k; long moves=0; int[] a=new int[100000]; n=scan.nextInt(); for(i=0;i<n;++i) a[i]=scan.nextInt(); for(k=0;k<n-1;++k) { if(a[k]>0) { moves+=a[k]; t=(int)(Math....
Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: * add x y — on the sheet of paper Bob mar...
//package sandbox; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class P19D5 { InputStream is; PrintWriter out; String INPUT = ""; static class Query { char type;...
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes. An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph. A bridge is such an edge of an undirected graph, that when removed inc...
#include <bits/stdc++.h> using namespace std; const int N = 110000; int x[N], y[N], vis[N], a[N]; vector<int> con[N]; map<int, int> flow[N], sum[N]; int dfs(int u) { if (vis[u]) return 0; vis[u] = 1; int ret = 1; for (int v : con[u]) { int d = dfs(v); ret += d; flow[v][u] = d; flow[u][v] = -d; ...
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And ye...
#coding=utf-8 import math y1,y2,yw,xb,yb,r = map(float,raw_input().split()) yw -= r y1,y2 = 2*yw-y2,2*yw-y1 if y2 - y1 < 2*r: print -1 exit(0) xa = 0 ya = y2-r k = (yb-ya)/xb rr = (xb*ya-xb*y1)/math.sqrt((yb-ya)**2+xb**2) if rr < r: print -1 exit(0) xw = (xb*yw-xb*ya)/(yb-ya) print "%.10lf"%xw
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in th...
import java.util.*; import java.io.*; public class Main implements Runnable { class Point implements Comparable<Point>{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Point b){ ...
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav. Input The first line contains integer n (1 ≤ n ≤ 100) — the numb...
import java.util.*; public class TwoNeighbourDistinct { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner (System.in); int n = in.nextInt(); int[] numCount= new int [1001]; int max=0; for (int i = ...
A substring of a string is a contiguous subsequence of that string. So, string bca is substring of string abcabc, but string cc is not. A repeating block is a string formed by concatenating some string with itself. So, string abcabc is a repeating block, but strings abcabd, ababab are not. You've got a sequence of La...
#include <bits/stdc++.h> using namespace std; int N; char S[2000005]; unsigned long long p[2000005], a[2000005]; unsigned long long get(int l, int r) { return a[r] - a[l - 1] * p[r - l + 1]; } void makehash() { for (int i = 1; i <= N; i++) a[i] = a[i - 1] * 31415927 + S[i]; } int lcp(int l1, int r1, int l2, int r2) {...
Mad scientist Mike has constructed a rooted tree, which consists of n vertices. Each vertex is a reservoir which can be either empty or filled with water. The vertices of the tree are numbered from 1 to n with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of this...
import java.util.*; import java.io.*; public class WaterTree implements Runnable { static ArrayList<Integer>[] graph; public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new WaterTree(), "spargeltarzan", 1L<< 29); thread.start(); thread.join(); ...
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: 1. Find any continuous subsequence (substring) of three characters of string q, which does...
#include <bits/stdc++.h> using namespace std; int main() { char str[100000 + 11]; int ant[3][100000 + 11]; int m; int l, r; scanf("%s", str + 1); ant[0][0] = ant[1][0] = ant[2][0] = 0; for (int i = 1; str[i]; i++) { if (str[i] == 'x') { ant[0][i] = ant[0][i - 1] + 1; ant[1][i] = ant[1][i -...
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble num...
#include <bits/stdc++.h> using namespace std; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, -1, 0, 1}; const int dx8[] = {-1, 0, 1, 0, 1, 1, -1, -1}; const int dy8[] = {0, -1, 0, 1, 1, -1, 1, -1}; long long min(long long a, long long b) { if (a < b) return a; return b; } vector<pair<int, int>> arr; vector<ve...
Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). A...
import java.util.*; import java.math.*; public class Main { public static void main(String args[]) { BigInteger f[]=new BigInteger[605]; f[0]=BigInteger.ONE; for(int i=1;i<=600;i++) f[i]=f[i-1].multiply(BigInteger.valueOf(12)); Scanner in=new Scanner(System.in); BigInteger n=in.nextBigInteger(); for(int ...
This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements: * each vertex of each triangle is one of the polygon vertex; * each side of the polygon must be the side of exactly one triangle; * t...
#include <bits/stdc++.h> using namespace std; const int MN = 211; struct Point { long long x, y; Point(long long x = 0, long long y = 0) : x(x), y(y) {} Point operator+(Point a) { return Point(x + a.x, y + a.y); } Point operator-(Point a) { return Point(x - a.x, y - a.y); } Point operator*(long long k) { retu...
Vasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into n × m squares and decided to plant a forest there. Vasya will plant nm trees of all different heights from 1 to nm. For his forest to look more natural he wants any two trees growing in the side n...
#include <bits/stdc++.h> using namespace std; const int INF = (1 << 30) - 1; const int DIRX[] = {-1, 0, 0, 1, -1, -1, 1, 1}, DIRY[] = {0, -1, 1, 0, -1, 1, -1, 1}; const double ERR = 1e-9, PI = (2 * acos(0.0)); template <class T> inline T MIN(T a, T b) { return ((a < b) ? a : b); } template <class T> inline ...
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that su...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class InterestingArray { private static int[] segmentTree; private static int[] num; private static final int MAX_BITS = 30; private static ...
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't. First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that: * D...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.PrintStream; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import ...
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom. A bar of chocolate can be presented as an n × n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are ...
#include <bits/stdc++.h> using namespace std; long long int inline ipow(long long int a, long long int b, long long int m) { long long int val = 1; a %= m; while (b) { if (b & 01) val = (val * a) % m; b >>= 1; a = (a * a) % m; }; return val % m; } long long int inline ipow(long long int a, long lo...
You are given an infinite periodic array a0, a1, ..., an - 1, ... with the period of length n. Formally, <image>. A periodic subarray (l, s) (0 ≤ l < n, 1 ≤ s < n) of array a is an infinite periodic array with a period of length s that is a subsegment of array a, starting with position l. A periodic subarray (l, s) is...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1000000; int A[MAX_N], N, C[MAX_N], G[MAX_N]; bool U[MAX_N]; long long ans; inline int inc(int v) { return (v + 1 == N) ? 0 : (v + 1); } inline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int main() { int i, j, g, l, r, mx, len; long long a...
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise. However, all is not...
#include <bits/stdc++.h> using namespace std; int n, ans, tmp, is[2]; char s[100001], pr; int main() { scanf("%d", &n); scanf("%s\n", s); ++ans; pr = s[0]; tmp = 1; for (int i = (1); i < (n); ++i) { if (s[i - 1] == s[i]) ++tmp; else { is[s[i - 1] - '0'] = max(is[s[i - 1] - '0'], tmp); ...
There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece. If students work at different paces,...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; long long dp[2][202][1002] = {0}; long long data[202] = {0}; long long Ans = 0; int N, K; int main() { scanf("%d %d", &N, &K); for (register int i = 1; i <= N; i++) scanf("%I64d", &data[i]); sort(data + 1, data + N + 1); dp[0][0][0] = ...
Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them. It is known that the forest consists of n trees...
#include <bits/stdc++.h> using namespace std; const int N = 400000 + 5; const int INF = 1e9 + 7; int ht[N]; vector<pair<int, int> > adj[N]; int ans[N]; int lis[N], lds[N]; int fl[N], fr[N]; int grp[N], freq[N]; inline int findlis(int l, int r, int v) { int mid; while (l < r) { mid = (l + r) >> 1; if (v <= l...
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (co...
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); double[][] glasses = new double[n][n]; for(int i=0;i<t;i++){ glasses[0][0] += 1; for(int j=0;j<n-1;j++){ for(int k=0;k<=j;k++){ ...
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends...
#include <bits/stdc++.h> using namespace std; struct Tt { int time, pro, num; }; Tt ts[1000 + 123]; int main() { memset(ts, -1, sizeof(ts)); int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { int l, r, t, c; scanf("%d%d%d%d", &l, &r, &t, &c); for (int j = l; j <= r; ++j) { if (ts...
Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has n decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet. There is a legend near the display, t...
#include <bits/stdc++.h> using namespace std; int IN() { int x = 0, f = 0, ch; for (; (ch = getchar()) < '0' || ch > '9';) f = (ch == '-'); for (; ch >= '0' && ch <= '9'; (ch = getchar())) x = x * 10 + ch - '0'; return f ? -x : x; } int N; long long Pow[25]; char A[25], B[25], s[25][25]; bool Equ(long long a, l...
There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that <image>, where <image> is bitwise xor operation (see notes for explanation). <image> Immediately, Mehrdad d...
n,x = map(int, input().split(' ')) a = list(map(int, input().split(' '))) cs = {} for v in a: cs[v] = cs.get(v, 0) + 1 t = 0 if x == 0: for c in cs.values(): t += c * (c - 1) // 2 print (t) else: for v in a: t += cs.get(x ^ v, 0) print(t // 2)
Artsem is on vacation and wants to buy souvenirs for his two teammates. There are n souvenir shops along the street. In i-th shop Artsem can buy one souvenir for ai dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least p...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; struct edge { int nxt, to, id; } e[N * 3]; int fir[N]; int n, m, a[N], tab[19][N], key[N << 2]; int ans[N * 3]; inline void addedge(int x, int y, int id) { static int cnt = 0; e[++cnt] = (edge){fir[x], y, id}; fir[x] = cnt; } inline void Build...
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as...
#include <bits/stdc++.h> using namespace std; long long MOD = 1e9 + 7; long long INF = LLONG_MAX / 4; vector<string> &split(const std::string &s, char delim, vector<string> &e) { stringstream ss(s); string item; while (getline(ss, item, delim)) e.push_back(item); return e; } long long Pow(long long a, long long...
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills. And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with t...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const double eps = 1e-11; const int inf = 0x7FFFFFFF; template <class T> inline void checkmin(T &a, T b) { if (b < a) a = b; } template <class T> inline void checkmax(T &a, T b) { if (b > a) a = b; } template <class T> inline T sqr(T x) { ...
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c). Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5, M = 101; int n, q, c, result[N], cum[M][M], x[N], y[N], s[N]; struct Query { int t, x1, y1, x2, y2, i; bool operator<(Query a) const { return t < a.t; } } query[N]; void doStuff(int t) { memset(cum, 0, sizeof cum); for (int i = 0; i < n; ++i) ...
Nagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school. Hogwarts' entrance can be imagined as a straight line (x-axis) from 1 to 105. Nagini is launching various snakes at the Hogwarts entrance. Each snake lands ...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") using namespace std; const int N = 100005; int n, q, Min1[N], Min2[N], opt, l, r, k; int main() { scanf("%d", &q); n = 1e5; for (int i = 1; i <= n; i++) Min...
A long time ago in some country in Asia were civil wars. Each of n cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city. Road making was difficult, so the country had few roads, exactly n - 1. Also you could reach any city from any other city going ...
import java.io.*; import java.util.*; public class CF87D { static final boolean _DEBUG = true; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(BufferedReader _br) { br = _br; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new St...
You are given a matrix f with 4 rows and n columns. Each element of the matrix is either an asterisk (*) or a dot (.). You may perform the following operation arbitrary number of times: choose a square submatrix of f with size k × k (where 1 ≤ k ≤ 4) and replace each element of the chosen submatrix with a dot. Choosin...
#include <bits/stdc++.h> using namespace std; constexpr long long MOD = 1e9 + 7; const long long INF = 1e10; int n; int b[1010], a[10]; long long dp[1010][1 << 12]; int clear(int s, int row, int k) { for (int i = 0; i < k; ++i) { for (int j = row; j < row + k; ++j) { s &= ~(1 << (4 * i + j)); } } re...
A positive integer is called a 2-3-integer, if it is equal to 2x·3y for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print the number...
import sys from math import * from fractions import gcd readints=lambda:map(int, input().strip('\n').split()) l,r=readints() maxn=2*(10**9) twos=set() i=2 while i<=maxn: twos.add(i) i*=2 threes=set() i=3 while i<=maxn: threes.add(i) i*=3 nums=set() nums.add(1) for x in twos: for y in threes: ...
You are given a rooted tree. Let's denote d(x) as depth of node x: depth of the root is 1, depth of any other node x is d(y) + 1, where y is a parent of x. The tree has the following property: every node x with d(x) = i has exactly ai children. Maximum possible depth of a node is n, and an = 0. We define fk as the nu...
#include <bits/stdc++.h> using namespace std; const int N = 5005; const long long P = 1e9 + 7; int n, f[N][N * 2]; long long a[N], b[N], cnt[N]; int main() { cin >> n; cnt[1] = 1; for (int i = (1); i <= (n - 1); i++) { scanf("%lld", &a[i]); cnt[i + 1] = cnt[i] * a[i] % P, b[i] = a[i] * a[i] % P; } for...
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_...
a=input() b=a[::-1] c=0 if a!=b: print(len(a)) while a==b: a=a[:0]+a[(0+1):] b=a[::-1] if a!=b: print(len(a)) else: print(c) break
The fraction 1/89 can be described as sum of n floating point numbers, where n tends to infinity. 1/89 = 0.0 + 0.01 + ....... If we consider these numbers as elements in a float array named “Numbers” (index starting from 0) then kth number in this sequence is defined by (for k>2) ( Numbers[k-1]+(Numbers[k-2]/10) )/...
l = [ ] l.append(0) l.append(1) a = 0 b = 1 cnt = 2 while cnt<=100: c = a+b l.append(c) a = b b = c cnt += 1 t = input() for i in range(t): n = input() n += 1 print "0."+"0"*(n-1)+str(l[n-1])
Bholu the Pandit on this New Year wanted to divide his Cuboidal Packaging block into cubes. But he loves uniformity so he asks you to divide it such a way that all the cubes are of same size and volume of individual cube is as large as possible. Note: He will utilize whole volume i.e volume of cuboid before dividing i...
def gcd(a, b): if b == 0: return a else: return gcd(b, a%b) def main(): test_cases = int(raw_input()) for _ in xrange(test_cases): L, B, H = raw_input().split() l, b, h = int(L), int(B), int(H) Volume = l*b*h possible_dim = gcd(l,gcd(b,h)) number = Volume/(possible_dim**3) print int(possible_dim...
Poornimites are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of addition problem so that edu...
n=input() for i in range(0,n): x,y=(i for i in raw_input().split()) l=len(x) carry=0 count=0 for j in range(0,l): if(int(x[j])+int(y[j])+carry>=10): count+=1 carry=int((int(x[j])+int(y[j])+carry)/10) if count==0: print "No carry operation" elif count==1: print "1 carry operation" else: print count...
Subodh is having N branches, where each branches have positive integral student. A minimize operation is performed on the branch such that all of them are reduced by the minimum number student in a branch. Suppose we have 5 branches and all of them have below students in a branch. 5 2 4 2 6 Then in one minimize oper...
n=int(raw_input()) a=sorted(map(int,raw_input().split())) print n v=a[0] i=1 while (i<n): while (i<n and a[i]==v): i+=1 if (i<n): v=a[i] i+=1 print n-i+1
Bitoholic is an inhabitant of the planet Neo in a galaxy far far away. Their civilization is studies an advanced form of mathematics. However, rules of calculus are a bit different there. On his planet, integration and differentiation techniques are called alpha and beta operations respectively and are defined as: alp...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=int(raw_input()) for i in range(1,t+1): n,p,u,r,s=map(int,raw_input().split()) for j in range(0,n): if p+r<=u: p=p+r elif p-s>=0: p=p-s else: p=p print 'Case #%d...
Given two numbers A and B. Find the value of pair (P,Q) such that A ≤ P < Q ≤ B value of P AND Q is maximum where AND is a binary operator. Refer to this link for more information about AND operator : http://en.wikipedia.org/wiki/Bitwise_operation#AND Input: First line of input contains number of test cases T. Each t...
for _ in xrange(input()): a,b=map(int,raw_input().split()) if b-a+1<3: print a&b elif b&1: print b&(b-1) else: print (b-1)&(b-2)
The time is 1st January 20000014 Gazu is depressed with his life as he thinks there is nothing unique about him. One day he meets a travelling coder, Gazu tells him why he is depressed, to which coder replies “Everyone is one in a zillion my brother”. The coder explained it like this. Considering every man and woman m...
import math t = input() for i in range(t): n = input() val = 1+n/30 print int(2**val)
Aparna recently created a random number generator and now she wants Harsh to check if it works fine. She gives Harsh an array containing N numbers generated from this random number generator of hers, and two integers K and P. If the given array contains more than or equal to K numbers in the range X-P to X+P (both inc...
T = int(raw_input()) for t in range(T): (N, K, P) = map (int, str(raw_input()).split()) nums = sorted (map (int, str(raw_input()).split())) for I in range(N-K+1): fail = False if nums[I+K-1] - nums[I] <= 2 * P: fail = True break if fail: print "NO" else: print "YES"
My flatmate, Sayan, went to the game show called Takeshi's castle.It is a game show in which you need to pass different game challenges to enter the final. Now the most famous round of all of them is the "skipping stones".In the game you need to go from one end of a small puddle to the other end of it stepping on ston...
n, L, D = [int(i) for i in raw_input().split(" ")] p = [float(x) for x in raw_input().split(" ")] p.append(1) p.insert(0, 1) d = [int(x) for x in raw_input().split(" ")] d.insert(0,0) last = d[len(d) - 1] d.append(D) pthen = [0]*len(d) pthen[0] = 1 for x in range(0, len(d)): for y in range(x+1, len(d)): if d[y] ...
X and Y are sitting beside a footpath on a bench on Marine Drive having a look at the beautiful sea. (Anyone from Mumbai here ?). X is a top coder who studies at DA-IICT. His friend Y studies at some local college from Mumbai. X always wants to show off his coding prowess so he asks puzzles to Y and Y (being not so i...
def mul(A,B): a,b,c,d,e,f,g,h=A[0][0],A[0][1],A[1][0],A[1][1],B[0][0],B[0][1],B[1][0],B[1][1] return [[(a*e+b*g)%mod,(a*f+b*h)%mod],[(e*c+d*g)%mod,(c*f+d*h)%mod]] def findNthPower(M ,n): if( n == 1 ): return M; R = findNthPower ( M , n/2 ); #a,b,c,d=R[0][0],R[0][1],R[1][0],R[1][1] R = mul(R,R) ...
Let us denote by f(x, m) the remainder of the Euclidean division of x by m. Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M). Find \displaystyle{\sum_{i=1}^N A_i}. Constraints * 1 \leq N \leq 10^{10} * 0 \leq X < M \leq 10^5 * All values in input are ...
n,x,m=map(int,input().split()) yj=[x] lps=0 for i in range(n): an=(yj[i]**2)%m if an in yj: lps=yj.index(an) break yj.append(an) blp=yj[:lps] lp=yj[lps:] ans=sum(blp)+sum(lp)*((n-len(blp))//len(lp))+sum(lp[:(n-len(blp))%len(lp)]) print(ans)
Takahashi wants to be a member of some web service. He tried to register himself with the ID S, which turned out to be already used by another user. Thus, he decides to register using a string obtained by appending one character at the end of S as his ID. He is now trying to register with the ID T. Determine whether...
s = input() t = input() print('Yes') if t[:-1] == s else print('No')
Niwango has N cards, numbered 1,2,\ldots,N. He will now arrange these cards in a row. Niwango wants to know if there is a way to arrange the cards while satisfying all the N conditions below. To help him, determine whether such a way exists. If the answer is yes, also find the lexicographically smallest such arrangeme...
#include "bits/stdc++.h" using namespace std; pair<int, int> INF = { -1000000000, -1 }; class SegmentTree { private: vector<pair<int, int> > Node; public: SegmentTree(vector<int>& V) : Node(V.size() * 2, INF) { for (int i = 0; i < V.size(); i++) { Node[i + V.size()] = { V[i], i }; } for (int i = V.size() -...
There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000. Among them, some K consecutive stones are painted black, and the others are painted white. Additionally, we know that the stone at coordinate X is painted black. Print all coordi...
K, X = map(int, input().split()) ans = list(range(X-K+1,X+K,1)) print(*ans)
Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i. He wrote an integer X on the blackboard, then performed the following operation N times: * Choose one element from S and remove it. * Let x be the number written on the blackboard now, and y be the integer removed from S. Repla...
#include <algorithm> #include <iostream> #include <set> #include <string> #include <utility> #include <vector> const long long M = 1000000000 + 7; int main() { int n, x; std::cin >> n >> x; std::vector<int> s(n); for (auto &a : s) std::cin >> a; std::sort(s.begin(), s.end()); long long f[x + 1]; fo...
You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it. Constraints * The length of S is 2 or 3. * S consists of lowercase English letters. Input Input is given from Standard Input i...
S = input() if len(S) == 2: print(S) if len(S) == 3: print(S[2]+S[1]+S[0])
In "Takahashi-ya", a ramen restaurant, basically they have one menu: "ramen", but N kinds of toppings are also offered. When a customer orders a bowl of ramen, for each kind of topping, he/she can choose whether to put it on top of his/her ramen or not. There is no limit on the number of toppings, and it is allowed to ...
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> using namespace std; const int N=3005; typedef long long ll; int power_mod(int a,int b,ll mod) { int ans=1; while (b) { if (b&1) ans=(ll)ans*a%mod; b>>=1; a=(ll)a*a%mod; } return ans; } int n; ll mod; int C[N][N],S[...
Ringo has a string S. He can perform the following N kinds of operations any number of times in any order. * Operation i: For each of the characters from the L_i-th through the R_i-th characters in S, replace it with its succeeding letter in the English alphabet. (That is, replace `a` with `b`, replace `b` with `c` a...
#include <iostream> #include <string> #include <vector> using namespace std; string S; int Q, l[100009], r[100009], a[100009], b[100009], col[100009], cntw; bool used[100009], flag; vector<pair<int, int>>D; vector<int>X[100009], V[100009]; int dfs(int pos) { int sum = 0; used[pos] = true; for (int i = 0; i < X[pos]...
You are given a string S of length N consisting of `(` and `)`. Your task is to insert some number of `(` and `)` into S to obtain a correct bracket sequence. Here, a correct bracket sequence is defined as follows: * `()` is a correct bracket sequence. * If X is a correct bracket sequence, the concatenation of `(`, X ...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String S = sc.next(); String ans = ""; int d = 0; for (int i = 0; i < N; i++) { if (S.charAt(i) == '(') { ans = ans + "("; d++; ...
Joisino is about to compete in the final round of a certain programming competition. In this contest, there are N problems, numbered 1 through N. Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N). In this contest, a contestant will first select some number of problems to solve. Then, the contestant...
#include <bits/stdc++.h> const int MAXN = 300005; using namespace std; using lint = long long; using pi = pair<lint, lint>; int n; lint a[MAXN], s[MAXN], d1[MAXN], d2[MAXN]; lint rep[MAXN]; struct cht{ vector<pi> v; void clear(){ v.clear(); } bool bad(pi x, pi y, pi z){ return (x.second - y.second) * (z.first - ...
Let x be a string of length at least 1. We will call x a good string, if for any string y and any integer k (k \geq 2), the string obtained by concatenating k copies of y is different from x. For example, `a`, `bbc` and `cdcdc` are good strings, while `aa`, `bbbb` and `cdcdcd` are not. Let w be a string of length at l...
#include <bits/stdc++.h> using namespace std; int A[2][500005]; string S[2]; void Z(int x){ A[x][0] = S[x].size(); int i=1,j=0; while(i<S[x].size()){ while(i+j<S[x].size() && S[x][j]==S[x][i+j])j++; A[x][i]=j; if(j==0){ i++; continue; } int k = 1; while(i+k<S[x].size() && k+A[x][k]<j) A[x][i+k]=A[x][k...
Your task is to develop a tiny little part of spreadsheet software. Write a program which adds up columns and rows of given table as shown in the following figure: <image> Input The input consists of several datasets. Each dataset consists of: n (the size of row and column of the given table) 1st row of the tab...
while True: n = int(input()) if not n: break mat = [] for _ in range(n): lst = list(map(int, input().split())) lst.append(sum(lst)) mat.append(lst) sum_lst = [] for i in range(len(mat[0])): s = 0 for j in range(n): s += mat[j][i] sum_lst.append(s) mat.append(sum_lst) ...
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an ope...
#include <cstring> #include <iostream> #include <algorithm> using namespace std; int n; int field[21][21]; int getFarthest(int p) { int res = 0; for (int i = 1; i <= n; i++) { if (field[p][i]) { field[i][p] = 0; res = max(res, field[p][i] + getFarthest(i)); } } return res; } int main () { while (cin >>...
Exclusive OR (XOR) is an operation on two binary numbers $ x $ and $ y $ (0 or 1) that produces 0 if $ x = y $ and $ 1 $ if $ x \ ne y $. This operation is represented by the symbol $ \ oplus $. From the definition: $ 0 \ oplus 0 = 0 $, $ 0 \ oplus 1 = 1 $, $ 1 \ oplus 0 = 1 $, $ 1 \ oplus 1 = 0 $. Exclusive OR on two...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct Node{ size_t cnt; Node *p,*l,*r; Node():cnt(0){p=l=r=nullptr;} Node(Node* p):cnt...
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory. The sludge is produced in a rectangular solid shaped tank whose size is N × N × 2. Let coordinate of two corner points of tank be (-N/2, -N/...
/* * Author: Dumbear * Created Time: 2011/8/31 14:29:36 * File Name: H.cpp */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; #define out(v) cerr << #v << ": " << (v) << endl #define SZ(v) ((int)(v).size()) con...
Long long ago, there lived a wizard who invented a lot of "magical patterns." In a room where one of his magical patterns is drawn on the floor, anyone can use magic by casting magic spells! The set of spells usable in the room depends on the drawn magical pattern. Your task is to compute, for each given magical patter...
#include <bits/stdc++.h> using namespace std; typedef long long int ll; const int INF = 1000000000; #define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++) #define rep(i,n) REP(i, 0, n) struct Edge { int from, to; string spell; Edge(int f, int t, string s) :from(f), to(t), spell(s){} }; int main(){ c...
Two experienced climbers are planning a first-ever attempt: they start at two points of the equal altitudes on a mountain range, move back and forth on a single route keeping their altitudes equal, and finally meet with each other at a point on the route. A wise man told them that if a route has no point lower than the...
#include<iostream> #include<sstream> #include<vector> #include<set> #include<map> #include<queue> #include<algorithm> #include<numeric> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<cassert> #define rep(i,n) for(int i=0;i<n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair ...
Hint * One grid may be filled more than once * Even if it can be represented by one line segment such as '1', it may be represented by two or more line segments. Sample Input 1 Formula for Sample Input 1. Sample Input 2 Sample Input 2 formula. Another character may get inside the smallest rectangle that covers one...
#define _CRT_SECURE_NO_WARNINGS #include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #define rep(i,n) f...
In this problem, you are required to write a program that enumerates all chord names for given tones. We suppose an ordinary scale that consists of the following 12 tones: C, C# , D, D# , E, F, F# , G, G# , A, A# , B Two adjacent tones are different by a half step; the right one is higher. Hence, for example, the to...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; //Reading a Chord public class Main{ boolean ok(boolean[] a, boolean[] b){ for(int i=0;i<12;i++)if(a[i]!=b[i])return false; return true; } void run(){ Scanner sc = new Scanner(System.in); String[] tones = {"C","C#","D","D#","E",...
Wind Corridor is a covered passageway where strong wind is always blowing. It is a long corridor of width W, and there are several pillars in it. Each pillar is a right prism and its face is a polygon (not necessarily convex). In this problem, we consider two-dimensional space where the positive x-axis points the east...
#include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <climits> #include <ctime> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <set> #include <map> #include <iostream> #include <deque> #include <complex> #include <string> #include <iomanip>...
You are a student looking for a job. Today you had an employment examination for an IT company. They asked you to write an efficient program to perform several operations. First, they showed you an N \times N square matrix and a list of operations. All operations but one modify the matrix, and the last operation output...
#include <bits/stdc++.h> using namespace std; #define dump(n) cout<<"# "<<#n<<'='<<(n)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp make_pair #define mt make...
Company trip Problem Statement Your company has n employees. For a group of m employees (a_i, b_i), a_i is the boss of b_i. When employee x is the actual boss of employee y, it means that at least one of the following holds. * x is y's boss. * There is an employee z who is the actual boss of y, and x is the boss o...
#include <map> #include <algorithm> #include <iostream> #define REP(i,n) for(int i=0; i<(int)(n); i++) #include <queue> #include <set> #include <cstdio> inline int getInt(){ int s; scanf("%d", &s); return s; } using namespace std; bool one(double x){ return x + 1e-9 > 1.0; } int main(){ const int n = getInt(); ...
A: A-Z Cat / A-Z Cat story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. It's so cute. Aizu Nyan was asked by her friend Joy to take care of her cat. It is a rare cat called A-Z cat. Aizunyan named the A-Z cat he had entrus...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); int len = 0; for(int i=0;i<s.length;i++) { if (len % 2 == 0 && s[i] == 'A' || len % 2 == 1 && s[i] == 'Z') { len++; } } len /= 2; if ...
problem There are many $ N $ colored balls of different weights in the queue. The queue is in ascending order from the beginning: $ 1,2,3, \ dots, N-1, N, 1,2,3, \ dots, N-1, N, 1,2,3, \ dots $ The balls are lined up, followed by the balls of color $ N $, followed by the balls of color $ 1 $. Balls of the same color w...
#include <cstdio> #include <algorithm> using namespace std; static int N,M; static struct { int count; int weight; } counts[1000]; static int max_weight=0,min_weight=100; int main(){ scanf("%d%d",&N,&M); for(int i=0;i<N;i++) scanf("%d",&counts[i].weight); bool all_equals; int weight=0; ...
Dutch treat You have organized a party to pray for the good performance of the ICPC 2019 Yokohama Regional Domestic Qualifiers. There are N participants in this party. Since it costs M yen in total to hold this party, we decided to collect M / N yen from each of the N participants. Since M is divisible by N, there is...
#include<iostream> #include<algorithm> using namespace std; int N,M; int main() { while(cin>>N>>M,N) { int ans=0; for(int i=0;i<N;i++) { int A;cin>>A; ans+=min(A,M/N); } cout<<ans<<endl; } }
F: Substring decomposition problem Given the two strings S and T and the integer k. Considering consecutive substrings of length k or more of T, determine if S can be constructed by concatenating them. Where the string s = s_1 s_2 ... s_n is a contiguous substring s [l, r] = s_l s_ {l + 1} ... s_r (1 \ leq l \ leq r...
#include <iostream> #include <string> #include <cstdlib> #include <cmath> #include <vector> #include <map> #include <set> #include <algorithm> #include <queue> #include <stack> #include <functional> #include <bitset> #include <assert.h> using namespace std; typedef long long ll; typedef vector<ll> vl; typedef vector<vl...
You have 4 bags A, B, C and D each of which includes N coins (there are totally 4N coins). Values of the coins in each bag are ai, bi, ci and di respectively. Find the number of combinations that result when you choose one coin from each bag (totally 4 coins) in such a way that the total value of the coins is V. You s...
#pragma region kyomukyomupurin /** * author : 𝒌𝒚𝒐𝒎𝒖𝒌𝒚𝒐𝒎𝒖𝒑𝒖𝒓𝒊𝒏 * created : 2020-04-24 14:15:54 **/ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <deque> #include <iomanip> #include <iostream> #include ...
Multiplication of Big Integers Given two integers $A$ and $B$, compute the product, $A \times B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the product in a line. Constraints * $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$ Sample Input 1 5 8 Sample Ou...
s = input().split() print(int(s[0]) * int(s[1]))
Oh my God!!! Someone is trying to break into Thapar University's Database and steal sensitive research information. It is now up to us to stop this attack. Fortunately our defense mechanisms have traced the attacks to their source. The fastest way to stop the attacks is to disable the source. So all we need to do is to...
def process(S): S = map(lambda x: ord(x), S) return chr(sum(S) / len(S)) def main(): T = int(raw_input()) for t in xrange(T): S = raw_input().split()[0] # WTF ?? print process(S) main()
Tomya is a girl. She loves Chef Ciel very much. Today, too, Tomya is going to Ciel's restaurant. Of course, Tomya would like to go to Ciel's restaurant as soon as possible. Therefore Tomya uses one of the shortest paths from Tomya's house to Ciel's restaurant. On the other hand, Tomya is boring now to use the same pa...
NumOfTests = int(raw_input()) for test in range(NumOfTests): N, M = map(lambda s: int(s), raw_input().split()) # n: min_distance, is_visited, num_of_paths D = {} # paths {vertex: [(neighb_vertex, length), ...], ...} P = {} for i in range(1, N+1): D[i]=[float("inf"), None, 0] P[...
Simple Factorial You are asked to calculate factorials of some small positive integers. Input   Input Tips: An integer T, denoting the number of testcases, followed by T lines, each containing a single integer N.   Output For each integer N given at input, output a single line the value of N! If you have multiple...
import math test = int(raw_input()) for i in xrange(test): num = int(raw_input()) fact = math.factorial(num) print fact
This is a very easy warm-up problem. You are given a string. Your task is to determine whether number of occurrences of some character in the string is equal to the sum of the numbers of occurrences of other characters in the string.  Input The first line of the input contains an integer T denoting the number of test...
for _ in range(int(raw_input())): s=raw_input() l=len(s) ans=0 for each in s: if s.count(each)==l/2: ans=1 break if l%2: ans=0 if ans: print "YES" else: print "NO"
You are given a permutation of natural integers from 1 to N, inclusive. Initially, the permutation is 1, 2, 3, ..., N. You are also given M pairs of integers, where the i-th is (Li Ri). In a single turn you can choose any of these pairs (let's say with the index j) and arbitrarily shuffle the elements of our permutatio...
intv_new = [] def bsearch(lo, hi, key): global intv_new mid = 0 while hi >= lo: mid = (hi + lo)/2 if key[0] < intv_new[mid][0]: hi = mid-1 elif key[1] > intv_new[mid][1]: lo = mid+1 elif key[0] >= intv_new[mid][0] and key[1] <= intv_new[mid][1]: return True return False t = input() while t != 0: ...
Chef and his little brother are playing with sticks. They have total N sticks. Length of i-th stick is Ai. Chef asks his brother to choose any four sticks and to make a rectangle with those sticks its sides. Chef warns his brother to not to break any of the sticks, he has to use sticks as a whole. Also, he wants that ...
import sys T=int(raw_input()) for i in range(T): n=int(raw_input()) a=raw_input().split() a=[int(x) for x in a] a.sort() b=tuple(a) if n<=3: print "-1" continue A=0 B=0 C=0 D=0 possible1=False possible2=False next=0 for j in range(n+1): if j==n: break A=b[-j] B=b[-(j+1)] if A==B: next=j...
This is an interactive problem. Vasya and Vitya play a game. Vasya thought of two integers a and b from 1 to n and Vitya tries to guess them. Each round he tells Vasya two numbers x and y from 1 to n. If both x=a and y=b then Vitya wins. Else Vasya must say one of the three phrases: 1. x is less than a; 2. y is...
#include <bits/stdc++.h> using namespace std; long long n, cnt; long long xx, yy; int kerd(long long a, long long b) { cnt++; a = n - a + 1, b = n - b + 1; cout.flush() << a << " " << b << "\n"; int ans; cin >> ans; return ans; } void solve(long long kx, long long ky, long long nx, long long ny, long long s...
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely. Lesha knows that today he can study for at most a hours, and he will have b hours to study tomorro...
#include <bits/stdc++.h> using namespace std; void show(vector<long long int> &a) { cout << a.size() << endl; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; } int main() { long long int a, b; cin >> a >> b; vector<long long int> v1, v2; long long int k = 0; for (; (k + 1) * (k + 2...
There are n children numbered from 1 to n in a kindergarten. Kindergarten teacher gave a_i (1 ≤ a_i ≤ n) candies to the i-th child. Children were seated in a row in order from 1 to n from left to right and started eating candies. While the i-th child was eating candies, he calculated two numbers l_i and r_i — the num...
''' the max element would have 0 0 i both l,r ''' from collections import defaultdict def f(l,r): cnts=defaultdict(list) lmax=[0]*len(l) rmax=[0]*len(l) for i in range(len(l)): cnts[l[i]+r[i]].append(i) mx=len(l) ans=[0]*(len(l)) for i in sorted(cnts): # print(lmax,rmax) ...
Try guessing the statement from this picture: <image> You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d. Input The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases. Each test case contains one integer d (0 ≤ d ≤ 10^3). ...
import decimal from math import* decimal.Context(prec=20) c=int(input()) for i in range(c): n=int(input()) n=decimal.Decimal(n) if n*n - 4*n < 0: print('N') elif n*n - 4*n == 0: print('Y '+ str(int(n/2))+ '.000000000 ' + str(int(n/2))+ '.000000000') else: x1=((n - de...
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences. A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting c...
n = int(input()) a = dict() b = dict() for i in range(n): s = input() k = 0 max_k = 0 op = True for j in s: if j == '(': k += 1 else: k -= 1 if k < max_k: max_k = k if k < 0: op = False if op == False and max...