input
stringlengths
29
13k
output
stringlengths
9
73.4k
There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X. You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required. * Choose...
N = int(input()) A = [0] + [int(input()) for i in range(N)] if A[1] != 0: print(-1) quit() ans = 0 for i, a in enumerate(A[1:], 1): pre_a = A[i-1] if a - pre_a >= 2: print(-1) quit() elif a > pre_a: ans += 1 else: ans += a print(ans)
In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowe...
#include <iostream> #include <cassert> #include <climits> #include <bitset> #include <stack> #include <queue> #include <iomanip> #include <limits> #include <string> #include <cmath> #include <set> #include <map> #include <math.h> #include <algorithm> #include <vector> #include <string.h> #include <tuple> using namespa...
There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two se...
#include<bits/stdc++.h> using namespace std; #define M 100005 vector<int>edge[M]; int Get_sg(int x,int pre){ int res=0; for(int i=0;i<edge[x].size();i++) if(edge[x][i]!=pre)res^=(Get_sg(edge[x][i],x)+1); return res; } int main(){ int n; scanf("%d",&n); for(int i=1;i<n;i++){ int x,y; scanf("%d%d",&x,&y); e...
There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How ...
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> using namespace std; typedef long long ll; const int N=100010,Mo=1000000007; ll f[N],s[N]; inline ll gi() { ll x=0,o=1; char ch=getchar(); while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar(); if(ch=='-') o=-1,ch=get...
Sigma and Sugim are playing a game. The game is played on a graph with N vertices numbered 1 through N. The graph has N-1 red edges and N-1 blue edges, and the N-1 edges in each color forms a tree. The red edges are represented by pairs of integers (a_i, b_i), and the blue edges are represented by pairs of integers (c...
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<queue> using namespace std; const int N=2e5+10; struct Tree { struct edge{int next,to;}a[N<<1]; int head[N],cnt; void link(int x,int y) { a[++cnt]=(edge){head[x],y};head[x]=cnt; a[++cnt]=(edge){h...
The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square wit...
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(true){ int n=sc.nextInt(); if(n==0){ break; } int[][] map=new int[n][n]; boolean[][] flag=new boolean[n][n]; int x=n/2; int y=n/2+1; map[y][x]=1; flag[y][x]=...
The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the followin...
import java.io.IOException; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { Scanner scanner = new Scanner(System.in); while (true) { int w = scanner.nextI...
The Onogawa Expedition is planning to conduct a survey of the Aizu nature reserve. The expedition planner wants to take the shortest possible route from the start to end point of the survey, while the expedition has to go around the coast of the Lake of Onogawa en route. The expedition walks along the coast of the lake...
#include <bits/stdc++.h> using namespace std; const double EPS = 1e-8, PI = acos(-1); inline bool eq(double a, double b) { return fabs(b - a) < EPS; } struct Point { double x, y; Point() {} Point(double x, double y) : x(x), y(y) {} Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }...
Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same dept...
#include <cstdlib> #include <iostream> #include <memory> #include <vector> using namespace std; struct node_t { shared_ptr<node_t> left, right; node_t():left(nullptr), right(nullptr) {} }; shared_ptr<node_t> parse(string::const_iterator &it) { shared_ptr<node_t> p(new node_t()); ++it; // '(' if(*it == '(') p->...
Hexwamp is a strange swamp, paved with regular hexagonal dimples. Hexerpents crawling in this area are serpents adapted to the environment, consisting of a chain of regular hexagonal sections. Each section fits in one dimple. Hexerpents crawl moving some of their sections from the dimples they are in to adjacent ones....
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; //Hexerpents of Hexwamp public class Main{ int[][] dir = {{0,-1},{1,-1},{1,0},{0,1},{-1,1},{-1,0}}; class Snake{ int x, y; String s; pub...
Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> ...
#include <iostream> #include <cstdio> #include <vector> using namespace std; #define rep(i, b) for( int i = 0; i < b; i++ ) int main(){ int n, w; while( cin >> n >> w, n ){ int num = (101 % w == 0) ? num = 101/w : num = 101/w+1; vector<double> hist(num); fill( hist.begin(), hist.end(), 0 ); double max = 0; ...
You are involved in the development of a certain game. The game is for players to explore randomly generated dungeons. There are n rooms in the dungeon generated by this game, and they are numbered from 0 to n-1. The rooms are connected by a passage. There are m passages connecting rooms. The passage can go in either ...
#include<bits/stdc++.h> using namespace std; typedef long long int64; typedef pair< int64, int64 > Pi; struct edge { int to, cost; }; const int64 INF = 1LL << 60; struct BinaryIndexedTree { vector< int > data; BinaryIndexedTree(int sz) { data.assign(++sz, 0); } int Query(int k) { int ret = 0; ...
This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection s...
#include<bits/stdc++.h> using namespace std; struct point{ int x,y; }; int main(int argc, char *argv[]){ int n, w, h; cin >> n; for (int r = 0; r < n; r++) { point p[7][2];//min, max map<char, int> matrial; cin >> h >> w; char grid[h][w]; for (int i = 0; i < h; i++) { for (int j = 0...
In the year 21xx, human beings are proliferating across the galaxy. Since the end of the last century, thousands of pioneer spaceships have been launched in order to discover new habitation planets. The Presitener is one of those spaceships, heading toward the Andromeda galaxy. After a long, long cruise in the hypersp...
#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);...
You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the ve...
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <iomanip> using namespace std; const int N = 111; const double eps = 1e-10; int n, m, pos[N]; double v[N][N], val[N], dist[N][N]; double get_r(int i, int j) { double up = 0.0; double dow...
Let G be a connected undirected graph where N vertices of G are labeled by numbers from 1 to N. G is simple, i.e. G has no self loops or parallel edges. Let P be a particle walking on vertices of G. At the beginning, P is on the vertex 1. In each step, P moves to one of the adjacent vertices. When there are multiple a...
#include <bits/stdc++.h> #define INF 1000000007 #define MP make_pair #define FI first #define SE second #define PB push_back #define VI vector<int> const double EPS = 1e-9, PI = acos(-1.0); using namespace std; typedef long long LL; typedef pair <int, int> P; const int NUM = 100010; int n, m, goal; bool g[10][10]; doub...
Sunuke-kun's dictionary contains the words s1, ..., sn, which consist of n lowercase letters. This satisfies s1 <... <sn when compared in lexicographical order. Unfortunately, some characters are faint and unreadable. Unreadable characters are represented by?. Find out how many ways to restore the dictionary by replaci...
#include <cstdio> #include <iostream> #include <vector> #include <algorithm> #define rep(i,n) for(int i = 0; i < n; ++i) using namespace std; long long mod=1000000007; long long dp[22][60][60]; char str[60][22]; long long solve(int a,int b,int c){ if(~dp[a][b][c])return dp[a][b][c]; if(b+1==c&&!str[b][a])return dp[a]...
Example Input 4 Durett 7 Gayles 3 Facenda 6 Daughtery 0 1 + Mccourtney 2 Output Mccourtney is not working now. Durett is working hard now.
#include<bits/stdc++.h> using namespace std; #define pb push_back #define ll unsigned long long #define pii pair<int,int> #define uu first #define vv second #define INF 1000000000 #define V 38 map<string,int>ma; map<string,pii>ma1; struct Person { string name; int matha; int kobe; }; bool operator<(Pe...
E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to l...
#include <bits/stdc++.h> using namespace std; int main(void){ int n,a,b,c; cin>>n>>a>>b>>c; cout<<n-(a+b-c)<<endl; }
Problem Given the string $ S $ of length $ N $. Process the following query $ Q $ times. Query Let $ S [L: R] $ be a character string consisting of $ S $ from the $ L $ character to the $ R $ character (including both ends). Represent $ S [L: R] $ as $ AXBXCX (1 \ leq | A |, | B |, | C |, | X |) $ using the appropria...
// #include<bits/stdc++.h> using namespace std; typedef long long LL; #ifdef BTK #define DEBUG if(1) #else #define CIN_ONLY if(1) #define DEBUG if(0) #endif #define ALL(v) (v).begin(),(v).end() #define REC(ret, ...) std::function<ret (__VA_ARGS__)> template <typename T>inline bool chmin(T &l, T r){bool a = l>r; if (a)l...
<image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segm...
// // 凸多角形の切断 // // verified: // AOJ Course CGL_4_C Convex Polygon - Convex Cut // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=jp // /* 問題例 ・AOJ 2385 ・AOJ 2160 */ #include <iostream> #include <vector> #include <cmath> #include <iomanip> #include <algorithm> using namespace...
For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previ...
#include <algorithm> #include <iostream> #include <ostream> void print_array(const int a[], int n) { for (int i = 0; i < n; ++i) { if (i > 0) std::cout << " "; std::cout << a[i]; } std::cout << std::endl; } int main(int argc, char *argv[]) { int n; std::cin >> n; int a[10]; for (int i = 0;...
Problem Statement Past In the year of 2048, the Virtual Reality Massively Multiplayer Online Role-Playing Game (VRMMORPG), Code Art Online (CAO), is released. With the Chef Gear, a virtual reality helmet that stimulates the user's five senses via their brain, players can experience and control their in-game characters ...
for _ in xrange(input()): r,c = map(int,raw_input().split()) a = [list(raw_input()) for _ in range(r)] tot = 0 for i in range(r): for j in range(c): if a[i][j] != '^': continue L = 0 for k in range(i-1,-1,-1): if a[k][j] == '#':...
In CycleLand Jack and Jenny are two friends.They want to go CycleSchool By a cycle ( Assume that they live in same house) . Distance between CycleSchool and their house is n units. Jack and jenny both like Jelly . They decided to play a game who will win the game ,get a chance to sit with jelly in school. Rules of game...
# python3 def optimal(n): if(n >= 5): res = 5 elif(n < 5 and n >= 3): res = 3 elif(n < 3 and n >= 1): res = 1 elif(n < 1): return -1 return res if __name__ == "__main__": count = -1 l = [] test = int(raw_input()) while(test): n = int(raw_inpu...
The Gray code (see wikipedia for more details) is a well-known concept. One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation. In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every tw...
import sys def main(): s = sys.stdin.readline n = int(s()) if n>=135: print "Yes" return nums = map(int, s().split()) for i in xrange(n): for j in xrange(i+1,n): for k in xrange(j+1,n): for l in xrange(k+1, n): if nums[i]^nums[...
Tug of war is a sport that directly puts two teams against each other in a test of strength. During school days, both Chef Shifu and Chef Po were champions of tug of war. On behalf of restaurant's anniversary, Chef Shifu and Chef Po have decided to conduct a tug of war game for their customers. Master Chef Oogway h...
import sys mod= 100000000000007 a=[0]*10004 a[0]=1 a[1]=0 for j in xrange(2,10002): a[j]=(j-1)*(2*a[j-1]+3*a[j-2])/(j+1) for j in xrange(0,10002): a[j]=(a[j]+a[j+1]) c=[0]*10004 c[0]=1 for j in xrange(0,10001): c[j+1]=2*(2*j+1)*c[j]/(j+2) t=int(sys.stdin.readline()) while t: t-=1 n,k=map(int,sys.stdin.read...
Chef likes trees a lot. Today he has an infinte full binary tree (each node has exactly two childs) with special properties. Chef's tree has the following special properties : Each node of the tree is either colored red or black. Root of the tree is black intially. Both childs of a red colored node are black and both ...
Q = int(raw_input()) flag = False while Q != 0: s = raw_input() s = s.split() q = s[0] if q != 'Qi': x = int(s[1]) y = int(s[2]) n = 0 start = 'b' while True: if x > y: x /= 2 n += 1 if start == 'b': ...
A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points: Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However...
# cook your code here import string testcases, KEY = map(str, raw_input().split()) KEYUP = string.swapcase(KEY) Dic = {'_':' '} Lower = string.ascii_lowercase Upper = string.ascii_uppercase for i in xrange(len(KEY)) : Dic[Lower[i]] = KEY[i] Dic[Upper[i]] = KEYUP[i] #print Dic for tester in xrange(int(testcase...
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedOutputStrea...
A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths k-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly k vertices. You are given a tree with n vertices. For each k from...
#include <bits/stdc++.h> using namespace std; int N, SQRT_N = 1000; int U, V; vector<int> Adj[100005]; int Parent[100005]; vector<int> Ord; int dp[100005], mxch[100005]; int Ans[100005]; void DFS(int Q) { for (int i : Adj[Q]) if (i != Parent[Q]) { Parent[i] = Q; DFS(i); } Ord.push_back(Q); } int...
The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth. For example, the picture below ...
#include <bits/stdc++.h> using namespace std; const int INF = INT_MAX; const long long INFL = LLONG_MAX; const long double pi = acos(-1); int N, K; string result; int cnt; int ask(int a, int b, int c) { cnt++; if (cnt > 60 * N) { cout << "TOO MANY eQUESTIONS" << '\n'; } cout << "? " << a << " " << b << " " ...
The Fair Nut got stacked in planar world. He should solve this task to get out. You are given n rectangles with vertexes in (0, 0), (x_i, 0), (x_i, y_i), (0, y_i). For each rectangle, you are also given a number a_i. Choose some of them that the area of union minus sum of a_i of the chosen ones is maximum. It is guar...
#include <bits/stdc++.h> using namespace std; const int N = (int)1e6 + 15; const long long inf = (long long)9e18; const int MOD = 998244353; const double eps = 1e-10; const double PI = acos(-1); inline double dcmp(double x) { return fabs(x) < eps ? 0 : (x > 0 ? 1 : -1); } struct Node { long long x, y, w; bool opera...
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in...
#include <bits/stdc++.h> using namespace std; int main() { int cnt0 = 0, cnt1 = 1; string s; cin >> s; for (int i = 0; i < s.length(); i++) { if (s[i] == '0') { cnt0++; cout << 3 << " " << cnt0 << endl; if (cnt0 == 4) { cnt0 = 0; } } else { cout << 1 << " " << cnt1 ...
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used...
#include <bits/stdc++.h> using namespace std; int main() { long long w1, h1, w2, h2; cin >> w1 >> h1 >> w2 >> h2; cout << 2 * (w1 + h1 + h2) + 4 << endl; return 0; }
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task. Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even posi...
from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_num(): return int(raw_input()) def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') de...
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
#include <bits/stdc++.h> using namespace std; int main() { int n, i, ans; scanf("%d", &n); ans = n / 2 + 1; printf("%d", ans); for (i = 1; i <= ans; ++i) printf("\n%d 1", i); for (i = 2; i <= n - ans + 1; ++i) printf("\n%d %d", ans, i); }
Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked. At this very moment, CJB, Father of Tokit...
#include <bits/stdc++.h> using namespace std; using ll = long long; template <class t, class u> void chmax(t& first, u second) { if (first < second) first = second; } template <class t, class u> void chmin(t& first, u second) { if (second < first) first = second; } template <class t> using vc = vector<t>; template ...
This is a harder version of the problem. In this version q ≤ 200 000. A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible numb...
#include <bits/stdc++.h> using namespace std; namespace mine { long long qread() { long long ans = 0, f = 1; char c = getchar(); while (c < '0' or c > '9') { if (c == '-') f = -1; c = getchar(); } while ('0' <= c and c <= '9') ans = ans * 10 + c - '0', c = getchar(); return ans * f; } void write(lon...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya was delivered a string s, containing only digits. He needs to find a string that * ...
import sys #sys.stdin = open('in.txt', 'r') s = str(raw_input()) c4, c7 = 0, 0 for it in s: if it == '4': c4 += 1 elif it == '7': c7 += 1 if c4 + c7 == 0: print '-1' else: print '4' if c4 >= c7 else '7'
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed som...
''' @judge CodeForces @id 1251A @name Broken Keyboard @tag Simulation ''' from sys import stdin from itertools import groupby def solve(s): return ''.join(sorted(set(map(lambda p: str(p[0]), filter(lambda p: len(list(p[1])) & 1, groupby(s)))))) input() for line in stdin: print(solve(line.strip()))
Suppose that we have an array of n distinct numbers a_1, a_2, ..., a_n. Let's build a graph on n vertices as follows: for every pair of vertices i < j let's connect i and j with an edge, if a_i < a_j. Let's define weight of the array to be the number of connected components in this graph. For example, weight of array [...
#include <bits/stdc++.h> using namespace std; const int SIZE = 1e6 + 10; int n, q, m; int a[SIZE], xi[SIZE]; int ql, qr, qv, qt; class SegmentTree { public: int size; int lazyTag[SIZE << 2]; struct Node { int v, c; friend Node operator+(Node A, Node B) { Node C; C.v = min(A.v, B.v), C.c = 0; ...
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos) [Æsir - V.](https://soundcloud.com/kivawu/aesir-v) "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 ...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 5000; vector<int> primes; vector<int> expansions[MAX_N + 1]; vector<int> factorials[MAX_N + 1]; vector<int> cnt_factorials(MAX_N + 1); int index_of_prime[MAX_N + 1]; int n; struct Node { int cnt = 0; long long sub_tree_sum = 0; long long sub_tree_cnt...
Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_...
#include <bits/stdc++.h> using namespace std; const int maxN = 1e6 + 11; const long long oo = 1e17 + 11; const long long MOD = 1e9 + 7; const long long base = 41; int tcases = 1; int N, M; int L[maxN], R[maxN]; long long powHash[maxN], res = 0; long long hhh[maxN]; class I_love_char_array { public: int len; char s...
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and a...
#include <bits/stdc++.h> using namespace std; inline int read() { register int x = 0; register int y = 1; register char c = getchar(); while (c < '0' || c > '9') { if (c == '-') y = 0; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + (c ^ 48); c = getchar(); } return y ? x : ...
Oh, no! The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem. You are given two arrays A and B of size...
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; const long double eps = 1e-6; long double sign(long double x) { return (x > 0) - (x < 0); } long long sign(long long x) { return (x > 0) - (x < 0); } int sign(int x) { return (x > 0) - (x < 0); } struct pt { long double x, y; pt() {} pt(long...
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c. Unfortunately, an adversa...
#!/usr/local/bin/python3 """ Given l, r, m, you know that m = n*a + b - c for some l <= a,b,c <= r, and n is an integer. Can you find a,b,c? (any value is fine) Examples l,r,m = 10,20,90 Choose 10 <= a,b,c <= 20 s.t. 90 = n*a + b - c a=10,b=10,c=10,n=9 l,r,m = 8,9,95 Choose 8 <= a,b,c <= 9 try a=...
You are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i ≤ x ≤ r_i holds, belong to the i-th segment. Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset eith...
#include <bits/stdc++.h> using namespace std; const int MAX = 6e3 + 10; int dp[MAX][MAX]; int DP(int i, int j, const vector<vector<int>> &rightOf) { if (i > j) return 0; int &answer = dp[i][j]; if (answer != -1) return answer; int add = 0; for (int r : rightOf[i]) if (r == j) add++; answer = add + DP(i ...
Mark and his crew are sailing across the sea of Aeolus (in Greek mythology Aeolus was the keeper of the winds). They have the map which represents the NxM matrix with land and sea fields and they want to get to the port (the port is considered as sea field). They are in a hurry because the wind there is very strong and...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; bool flg = false; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') flg = true; for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48); return flg ? -x : x; } int n, m, K, T, W; char getn...
You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. T...
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N = 2e5 + 10; const int K = 20; const int INF = 1e9; const int MOD = 998244353; int n; vector<pair<int, int> > adj[2][N]; int trans[2][N], lvl_dist[2][N], dist[2][K][N]; struct elem { int re...
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 ≤ i ≤ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical. Monocarp wants to draw the segments in such a way that they enclose a rectangular...
#include<iostream> #include<bits/stdc++.h> #define int long long int using namespace std; int32_t main() { int t; cin>>t; while(t--) { int a[4]; cin>>a[0]>>a[1]>>a[2]>>a[3]; sort(a, (a+4)); cout<<a[0]*a[2]<<endl; } return 0; }
You are given three integers a, b, k. Find two binary integers x and y (x ≥ y) such that 1. both x and y consist of a zeroes and b ones; 2. x - y (also written in binary form) has exactly k ones. You are not allowed to use leading zeros for x and y. Input The only line contains three integers a, b, and k (...
#tests = int(input()) #for t in range(tests): #n = int(input()) a, b, k = list(map(int, input().split())) if a == 0 and k!=0: print('No') elif k ==0: print('Yes') print('1'*b + '0'*a) print('1'*b + '0'*a) elif b==1 or k > (a+b-2): print('No') else: shift = a+b-2-k print('Yes') ans_1 = ...
There are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 ≤ i ≤ n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn ...
#include<bits/stdc++.h> using namespace std; /* #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> */ /* unordered_map<int,int>mp; mp.reserve(1024); mp.max_load_fact...
You are given a sequence A, where its elements are either in the form + x or -, where x is an integer. For such a sequence S where its elements are either in the form + x or -, define f(S) as follows: * iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through...
MOD = 998244353 def solve(): n = int(input()) ans = 0 arr = [] for i in range(n): a = list(input().split()) if len(a) == 2: arr.append(int(a[1])) else: arr.append(0) for cur in range(n): if arr[cur]: dp = [0] * (n+1) d...
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one p...
#!/usr/bin/env python # -*- coding:utf-8 -*- # def readint(): return int(raw_input()) def readfloat(): return float(raw_input()) def readarray(N, foo): res = [] for _ in xrange(N): res.append(foo()) return res def readlinearray(foo): return map(foo, raw_input().split()) HOUR=0 ...
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surround...
#include <bits/stdc++.h> using namespace std; int main() { long double x1, y1, r1, x2, y2, r2; cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2; long double x = abs(x1 - x2); long double y = abs(y1 - y2); long double d = sqrt(x * x + y * y) - (r1 + r2); if (d > 0) cout << setprecision(15) << (d / 2); else { ...
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can mak...
#include <bits/stdc++.h> using namespace std; long long n, fq[10], mo[3]; int main() { long long i, j, ii, k, sm, e; pair<long long, long long> mxe = {-1e18, -1}; bool bad = 1; scanf("%lld", &n); for (i = 0; i < n; i++) { scanf("%lld", &k); fq[k]++; mo[k % 3]++; } if (!fq[0]) { printf("-1\...
This problem is the most boring one you've ever seen. Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the...
def finddiff(A, other, h): max1 = A[-1] + A[-2] min1 = A[0]+ A[1] min2 = other + A[0] + h max2 = other + A[-1] + h return max(max1,max2) - min(min1,min2) n, h = map(int, raw_input().split()) numbers = map(int, raw_input().split()) savenum = -1 num = numbers[:] numbers.sort() min1 = numbers[-1]+numbers[-2]-num...
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1): <image> Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t. Expression (x xor y...
#include <bits/stdc++.h> using namespace std; long long N, T, ans = 0; int M; long long C[41][41]; long long solve(long long pos, long long len, int level, int L) { if (L < 0 || level < L) return 0; if (len == 1) return 1; if (pos > len / 2) { return (level - 1 >= 0 && L >= 0 ? C[level - 1][L] : 0) + ...
A ladies' shop has recently opened in the city of Ultima Thule. To get ready for the opening, the shop bought n bags. Each bag is characterised by the total weight ai of the items you can put there. The weird thing is, you cannot use these bags to put a set of items with the total weight strictly less than ai. However ...
#include <bits/stdc++.h> using namespace std; complex<double> ca[2100100], ya[2100100], y2[2100100]; double PI = acos(-1.0); int invert(int v, int t) { int r = 0; while (t) { r = (r << 1) | (1 & v); v >>= 1; --t; } return r; } void fft(complex<double> *y, int t, int inv) { int lg = 0, k, v, t2; ...
SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa. She is going to demonstrate this technique. Now SmallR has n dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to n. The cost ...
#include <bits/stdc++.h> using namespace std; int n, m, g, v[10010], s[10010], fri[2010], d[2010][11], w[2010], k[2010], opt[2010]; int S, T, dis[20010], ans, tim; struct info { int v, c; unsigned r; }; unsigned cur[20010]; vector<info> a[20010]; template <typename T> void chkmin(T &x, T y) { x = min(x, y); }...
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of oth...
#include <bits/stdc++.h> using namespace std; int main() { long long n; long long x = 3; cin >> n; while (1) { if (n % x != 0) break; x *= 3; } long long ans = n / x; cout << ans + 1 << endl; return 0; }
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname...
#include <bits/stdc++.h> using namespace std; class DSU { public: int *parent; int elems; DSU(int n) { elems = n; parent = new int[elems]; for (int i = 0; i < elems; ++i) { parent[i] = i; } } ~DSU() { delete[] parent; } int find(int a) { if (a >= elems) return 4000000; int p =...
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees. His new tree consists of n levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level 1, its index is (1, 1). Here is a pseudo code of tree...
#include <bits/stdc++.h> using namespace std; int n, m; int L[150000]; int R[150000]; int used[1000001]; vector<int> a[7001][3]; int main() { cin >> n >> m; L[1] = 1; R[1] = 2; for (int i = 1; i <= 1000000; i++) { used[i] = false; } for (int i = 2; i < 150000; i++) { if (__builtin_popcount(i) == 1) ...
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time pla...
inp = input().split(' ') n = int(inp[0]) x = int(inp[1]) su = 0 inp = input().split(' ') for i in inp: su += int(i) count = 0 while su!=0: count += 1 if su > 0: su += max(-x, -su) else: su += min(x, -su) print(count)
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with ...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); long long n, m; cin >> n >> m; long long mp[n + 1][m + 1], dp1[n + 2][m + 2], dp2[n + 2][m + 2], dp3[n + 2][m + 2], dp4[n + 2][m + 2]; for (long long i = 1; i < n + 1; i++) { f...
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1); char primes[12500002]; void preCal() { memset(primes, 85, sizeof primes); primes[0] = 83; for (int i = 3; i < 10000; i += 2) if (!((primes[i >> 3]) & (1 << (i & 7)))) for (int j = i * i; j < 100000000; j += i) primes[j >> 3] |= 1 ...
There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal. Let's have a try. I have created the following task for Top...
#include <bits/stdc++.h> using namespace std; const int N = 10005, M = 30; using pii = pair<int, int>; int n, bs[N], bnum[N], x[N], y[N], flx[N], fly[N], b[N]; vector<pii> ans, opt; int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; i++) cin >> x[i]; for (int i = 1; i <= n; i++) cin >> ...
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the ne...
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class CF283D1 { private static class Result implements Comparable<Result> { Integer s; Integer t; public Result(final Integer s, final Integer t) { this.s = s; ...
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower le...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast", "inline", "-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") using namespace std; template <typename T> void read(T &x) { x = 0; char ch = getchar(); int fh = 1; while (ch < '0' || ch > '9') { if (ch == '-') fh = -1; ch = getchar(); } w...
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. <image> He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k mess...
def isPalindrome(t): for i in range(len(t)//2): if t[i] != t[len(t)-i-1]: return False return True s = input() k = int(input()) if len(s) % k: print('NO') else: t = len(s)//k for i in range(k): if not isPalindrome(s[i*t: i*t+t]): print('NO') break ...
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
n = int(raw_input()) a = [int(x) for x in raw_input().split()] # s = set() # for e in a: # s.add(e) # a = list(s) # def gcd(x, y): # if y == 0: # return x # else: # return gcd(y, x%y) # def lcm(x,y): # return x * y / gcd(x,y) def factorize(x): while(x % 2 == 0): x /= 2 while(x % 3 == 0): x /= 3 ret...
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
#include <bits/stdc++.h> using namespace std; int cantidad; int y[10000]; int x[10000]; int main() { cin >> cantidad; int area; int tempx; int tempy; for (int i = 0; i < cantidad; i++) { cin >> x[i] >> y[i]; } if (cantidad == 1) { cout << -1; } if (cantidad == 2) { if (x[0] == x[1] || y[0]...
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, t...
n, x1, y1, x2, y2 = map(int,raw_input().split()) SquareDist = [] for i in range (0, n): x,y = map(int,raw_input().split()) D1 = (x-x1)**2 + (y-y1)**2 D2 = (x-x2)**2 + (y-y2)**2 SquareDist.append((D1,D2)) SquareDist.sort() Suffixes = [0] for i in range (0, n): Suffixes.append(max(Suffixes[i], Square...
A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a lengt...
#include <bits/stdc++.h> using namespace std; const int MXN = (int)1e6 + 10; const int INF = (int)1e9 + 7; const long long LINF = (long long)1e18 + 10; const double EPS = (double)1e-9; const double PI = (double)acos(-1.0); int a[MXN]; int n, m, s, d; vector<pair<int, int> > v; int main() { scanf("%d%d%d%d", &n, &m, &...
A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime. You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size. A prime n...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Aviously */ public class Main { public s...
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be...
#include <bits/stdc++.h> using namespace std; double a[100001]; int n; double k; int isbalance(double val) { double inc = 0.0; double dec = 0.0; for (int i = 0; i < n; i++) if (a[i] > val) dec += (a[i] - val); else inc += (val - a[i]); dec -= dec * (k / 100.0); if (dec >= inc) return 0...
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland,...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000003; long long fast_pow(long long x, long long y) { long long ret = 1; for (; y; y >>= 1, x = x * x % MOD) if (y & 1) ret = ret * x % MOD; return ret % MOD; } long long get_inv(long long x) { return fast_pow(x, MOD - 2); } int main() { ...
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations. There are n computers for participants, the i-th of which has power equ...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const int MOD = 1000000007; const int INF = 0x7fffffff; const double eps = 1e-10; const int N = 200005; set<pair<int, int> > com; pair<int, int> soc[N]; int id[N], match[N]; int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 1; i ...
Consider the following grammar: * <expression> ::= <term> | <expression> '+' <term> * <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')' * <number> ::= <pos_digit> | <number> <digit> * <digit> ::= '0' | <pos_digit> * <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'...
#include <bits/stdc++.h> using namespace std; int power(int b, int a = 10) { int res = 1; for (; b; b >>= 1, a = (long long)a * a % 1000000007) if (b & 1) res = (long long)res * a % 1000000007; return res; } struct node { int x, y; node() {} node(int x, int y) : x(x), y(y) {} node(string &s) { x =...
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, ...
#include <bits/stdc++.h> using namespace std; int n, m; char var[12], def[4], buf[1005]; unordered_map<string, int> varId; pair<int, int> operand[5005]; int val[5005][1005]; char op[5005][4]; char mx[1005], mn[1005]; int calc(int id, int idx) { if (op[id][0] == 'X') { return val[operand[id].first][idx] ^ val[oper...
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations. Can you help Heidi estimate each village's population? Input Same as the easy version. Output Output one line per village, in the same order as provided in the ...
#include <bits/stdc++.h> using namespace std; int T, sum, maxx, s[255]; int main() { scanf("%d", &T); while (T--) { sum = maxx = 0; for (int i = 1; i <= 250; i++) scanf("%d", s + i), sum += s[i], maxx = max(s[i], maxx); double aver = sum / 250.0, fang = 0; for (int i = 1; i <= 250; i++) fang +...
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: * Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). * Digits are written one by one in ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Andrei Chugunov */ public class A { BufferedReader br; PrintWriter out; StringTokenizer st; void solve() throws IOException { ...
In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through o...
#include <bits/stdc++.h> using namespace std; template <typename T> T next_int() { T x = 0, p = 1; char ch; do { ch = getchar(); } while (ch <= ' '); if (ch == '-') { p = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); } return p * x;...
Physicist Woll likes to play one relaxing game in between his search of the theory of everything. Game interface consists of a rectangular n × m playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connec...
#include <bits/stdc++.h> int n, m; char a[1111][1111]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) scanf("%s", a[i]); for (int i = 0; i < n; ++i) for (int j = 0; j < m - 1; ++j) if (a[i][j] == '.' && a[i][j + 1] == '.') a[i][j] = a[i][j + 1] = (((i + j) & 1) ? ('0...
What are you doing at the end of the world? Are you busy? Will you save us? <image> Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, f0... ∞. f0 is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to let more people know about i...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.*; public class Q449A { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; String f0 = "What are you doing at the end ...
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lower...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("unroll-loops") using namespace std; int n, m; const int MAXN = 100; int winner[MAXN][MAXN][26]; vector<pair<int, int> > g...
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe...
#include <bits/stdc++.h> using namespace std; int main() { int n, w, m; double x; vector<pair<int, int> > a[50]; int c, k, r, s; cin >> n >> w >> m; x = (double)(n * w) / m; c = 1; k = 1; r = m; for (int i = 0; i < m; ++i) { s = 0; while (n - s >= r) { a[i].push_back(make_pair(c, r)); ...
Arkady's code contains n variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code. He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with...
#include <bits/stdc++.h> using namespace std; struct Node { int next[26]; int cnt; Node() { for (int i = 0; i < 26; i++) { next[i] = -1; } cnt = 0; } }; int main() { int n; cin >> n; vector<Node> trie; trie.emplace_back(); for (int i = 0; i < n; i++) { string s; cin >> s; ...
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were n shamans in total enumerated with integers from...
#include <bits/stdc++.h> using namespace std; void build_sum(int i, int l, int r, long long *nodes, long long *val, long long (*add_fun)(long long, long long)) { if (l == r) { nodes[i] = val[l]; return; } else { build_sum(i * 2, l, (l + r) / 2, nodes, val, add_fun); build_sum(i * 2 + ...
Sherlock and Watson were good friends. They both were solving a mystery. But they got hungry and wanted to eat something. Hence they asked for some candies from Mom. Mom was also clever. She told them to solve a function for her. Function is defined as follows - F(x) = 2^x - 1 She gave number "a" to Shelock and "b"...
def primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) # supposing you want multiple factors repeated n //= d d += 1 if n > 1: primfac.append(n) return primfac def f(x): return pow(2,x)-1 for i in range(int(raw_inpu...
2^N participants (P1 , P2 , P3 .... , P2^N ) have enrolled for a knockout chess tournament. In the first round, each participant P2k-1 is to play against participant P2k, (1 ≤ k ≤ 2^N-1) . Here is an example for k = 4 : Some information about all the participants is known in the form of a triangular matrix A with dim...
import copy n = int(raw_input()) table = [[None for i in range(pow(2,n))] for j in range(pow(2,n))] for i in range(1,pow(2,n)): temp = map(int,raw_input().split()) for j in range(len(temp)): table[i][j] = temp[j] # for _ in range(pow(2,n)-1): # table.append(map(int,raw_input().split())) game = [i for i in range...
A drunk person was moving from one point on the street to another point on the same street. His starting point was between two manholes on that street. He was following a systematic scheme of his movement and had a fix movement repeated after an interval of time. How much time will he take to fall in the manhole and in...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n_test=int(raw_input("")) debug=False for test in range(n_test): inp=raw_input("").split(" ") d=inp[0] D="F" fw,bw,vf,vb,sp=map(int,inp[1:]) spd_s=vf-vb spd_t=vf+vb t0=0 if spd_...
As of now, you helped agent OO7 to find men with different capability values. Now his task is to group up his men and work as a team. He wants to form the groups with minimum 2 men in it. Help him out to find how many such groups are possible. Input - First line contains 'T' test cases followed by 'T' lines containing ...
num=input() groupSize=dict() def gs(n,m): if m<2: return 0 if(m==n): return 1 if n<m: return 0 if (n,m) in groupSize: return groupSize[(n,m)] res=1 for i in range(m,n-1): res+=gs(n-i,i) groupSize[(n,m)]=res return res for _ in range(num): n=input() print gs(n,2)
Little Monty is very fond of Fibonacci numbers and challenges his friend Lopa that he can solve any question regarding the same. Lopa however is jealous and after thinking for a long time came up with a problem. She says given N(the number of fibonacci numbers) one has to count all the multiples of all the fibon...
t=int(input()) while(t>0): count=0 n=int(input()) for i in range(3,n+1): count=int(count+n/i) if (n==1): print(1) elif (n==2): print(4) else: print(int(count+2*n)) t-=1
Many of you know the famous Fibonacci sequence F: F[1] = 1 F[2] = 1 F[i] = F[i - 1] + F[i - 2] for i > 2 Thus each number in sequence is a sum of two previous numbers except two first which are define as 1. You've decided to create you own Fibonacci sequence. It's very similar to the one described above, but the firs...
a,b,n = map(int,raw_input().split()) lis = list(); lis.append(a) lis.append(b) for i in range(2,n): lis.append(lis[i - 1] + lis[i - 2]) print lis[n-1]
Abhishek is a computer science student at the Department of computer science India His teacher recently gave him a single assignment with only a single problem. The problem was simple.He has to find out the min number of single digit prime numbers which when added equals a given number Y. Input: The first line conta...
t = int(raw_input()) prim = [1,2,3,5,7] for i in range(t): n = int(raw_input()) if n<1: print -1 continue dp = []*n sumi = 0 sumi+=n/7 n%=7 if n==1 or n==2 or n==3 or n==5: sumi+=1 elif n: sumi+=2 print sumi
Sandy is given an array of N integers which is a permutation of the first N natural numbers. He can swap any two elements of the array and can make at most K swaps. He needs to tell the largest permutation, in numerical order, could be made? You being sandy's friend help him in doing so. Input Format:- The first line ...
N, K = map(int, raw_input().split()) arr = map(int, raw_input().split()) swaps_made = 0 for i, j in enumerate(sorted(arr, reverse=True)): if j > arr[i]: p = arr.index(j, i) arr[i], arr[p] = arr[p], arr[i] swaps_made += 1 if swaps_made >= K: break print ' '.join(map(str,...
Little Timmy is exceptionally good at math tables, so his maths teacher decided to make things a bit more interesting. His teacher takes two numbers A and B and merges the tables of A and B in sorted order (ascending order), removing the duplicates and thus creates supertable of A and B and asks Little Timmy the Nth nu...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' from fractions import gcd t=input() while t>0: t-=1 a,b,n=map(int,raw_input().split()) c=(a*b)/(gcd(a,b)) l,r=1,1000000000000 while(l<=r): m=(l+r)/2 s=m/a...
Separatist Always finding new ways to destroy the Republic forces by surprise attacks. Now they trapped the Republic fleet near the Abregado system. They have developed a way to communicate through the encrypted message to its fleet around the Abregado system. They wrote a message in a cryptic language, and next to ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' n = input() ans = [] def find(a): f = 0 n = [] l = [] k = [] t = 1 for i in a: f = 0 try: l.index(i) except ValueError: f = 1 if t == 1: l...
There are N piles of stones. The i-th pile has A_i stones. Aoki and Takahashi are about to use them to play the following game: * Starting with Aoki, the two players alternately do the following operation: * Operation: Choose one pile of stones, and remove one or more stones from it. * When a player is unable to do t...
#include <bits/stdc++.h> #define int long long #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() #define pb push_back #define F first #define S second using namespace std; typedef pair<int,int> P; typedef vector<int> ivec; const int MOD=1000000007; int INF=100100100100100; int b...