input
stringlengths
29
13k
output
stringlengths
9
73.4k
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies. On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (...
import java.util.*; public class LifeLine { public static void main(String[] args) { Scanner f = new Scanner(System.in); int n = f.nextInt(); int[] deg = new int[n]; boolean[][] connected = new boolean[n][n]; for (int i = 0; i < n - 1; i++) { int a = f.nextInt() - 1, b = f.nextInt() - 1; connected[a][...
ZS the Coder has a large tree. It can be represented as an undirected connected graph of n vertices numbered from 0 to n - 1 and n - 1 edges between them. There is a single nonzero digit written on each edge. One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive in...
#include <bits/stdc++.h> using namespace std; const long long N = 100005; long long n, m, k, sz[N], mx[N], vis[N], rt, pw[N] = {1}, iv[N] = {0}, ans; vector<pair<long long, long long>> e[N], b; vector<long long> a, c; void exgcd(long long a, long long b, long long &x, long long &y) { if (!b) { x = 1, y = 0; r...
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int maxn = 210; int n, k; vector<int> mp[maxn]; int dp[maxn][maxn]; int tmp[maxn]; void dfs(int rt, int f) { dp[rt][0] = 1; dp[rt][k + 1] = 1; for (int v : mp[rt]) { if (v == f) continue; dfs(v, rt); memset(tmp, 0, sizeof(tmp...
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost. And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 po...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-4; struct Point { double x, y; Point() { x = y = 0; } Point(double xx, double yy) { x = xx, y = yy; } Point operator+(Point b) { return Point(x + b.x, y + b.y); } Point operator-(Point b) { return Point(x - b.x, y - b.y); } double dist() { ...
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two wo...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; struct node { string fi, se, ans; int id; } x[1009]; int n; map<string, int> cntfi, cntse, cnt; bool cmp(node a, node b) { return cntfi[a.fi] > cntfi[b.fi]; } bool cmp_cnt(node a, node b) { return cnt[a.fi] > cnt[b.fi]; } bool cmp_id(node a, ...
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
#include <bits/stdc++.h> using namespace std; class Solution { public: void solve(std::istream& in, std::ostream& out) { int n; in >> n; int ans = n / 2 + n % 2 - 1; out << ans << "\n"; } }; void solve(std::istream& in, std::ostream& out) { out << std::setprecision(12); Solution solution; sol...
You are given a connected weighted graph with n vertices and m edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id i. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the oth...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 2e5 + 10; struct Edge { int u, v, cost, idx; bool operator<(const Edge& rhs) const { return cost < rhs.cost; } } ed[MAX_N]; inline bool cmp_idx(const Edge& lhs, const Edge& rhs) { return lhs.idx < rhs.idx; } map<pair<int, int>, int> ID; int ver[MAX_N...
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1. Arpa can perform two types of operations: * Choose a number and delete it with cost x. * Choose a number and increase it by 1 with cost y. ...
#include <bits/stdc++.h> using namespace std; int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n, x, y, a[500010]; long l...
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows: 1. If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call; 2....
#include <bits/stdc++.h> using namespace std; int arr[132005]; int n, k; int init_cnt = 1; int cnt[132005 << 1]; void init(int l, int r, int p) { if (r - l <= 1) return; int mid = (l + r) >> 1, lch = p << 1, rch = p << 1 | 1; init_cnt += 2; cnt[p] += 2; init(l, mid, lch); init(mid, r, rch); cnt[p] += cnt[...
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. Input The first line contains a s...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; ...
Yesterday was a fair in a supermarket's grocery section. There were n jars with spices on the fair. Before the event the jars were numbered from 1 to n from the left to the right. After the event the jars were moved and the grocer had to sort them by the increasing of the numbers. The grocer has a special machine at h...
#include <bits/stdc++.h> using namespace std; const int N = 200002; vector<vector<pair<int, int> > > ans; vector<vector<int> > cs, twoCs, threeCs; int n, p[N]; int main() { ios::sync_with_stdio(0); cin >> n; for (int i = 1; i <= n; i++) cin >> p[i]; bool mark[N] = {}; for (int i = 1; i <= n; i++) if (!mar...
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno...
#include <bits/stdc++.h> using namespace std; int f[1000000]; int main() { int n; cin >> n; for (int i = 2; i <= n; i++) { if (f[i] == 0) { for (int j = 2 * i; j <= n; j += i) { f[j] = i; } } } int ans = INT_MAX; int val; for (int i = n - f[n] + 1; i <= n; i++) { val = min(...
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
import sys n,m,k=map(int,input().split()) if(k<n): print(k+1,1) sys.exit() k-=n x=n-(k)//(m-1) if(x%2==0): y=k%(m-1)+2 else: y=m-k%(m-1) print(x,y)
Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires n-1 other employees, each of which is assigned a direct superior. If u is a superior of v and v is a superior of w then also u is a superior of w. Additionally, there are no u...
#include <bits/stdc++.h> using namespace std; int n, d; long long dp[3006][3006], c[3006][3006], tmp = 1, ans = 0; const long long mod = 1e9 + 7; vector<int> e[3006]; int dfs(int u, int p = 0) { for (int i = 1; i <= n; i++) dp[u][i] = 1; for (int i = 0; i < e[u].size(); i++) { int v = e[u][i]; dfs(v, u); ...
Balance strings, by definition, are the strings that contain all the characters of the alphabet, from a to z, equal no of times. eg- abcdefghijklmnopqrstuvwxyz is a balanced string, aabb is not. Input: First line contains number of test cases T. Each test case contains a string S which made up of only lowercase charac...
from collections import Counter i=0 N=input() while i<N: st=raw_input() d=Counter([j for j in st]) if len(d)==26 and len(set(d.values()))==1: print 'Yes' else: print 'No' i+=1
Tom is solving an IQ quiz in which he is stuck in a question which says that there are two circles whose center coordinates and radius are given. Now Tom has to find whether the two circles overlap, do not overlap or are tangential with each other. Help Tom in solving the problem. Input: The input to the problem wil...
import math def centredist(x1, y1, x2, y2): return math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); x1, y1, r1 = map(int, raw_input().split()); x2, y2, r2 = map(int, raw_input().split()); d = centredist(x1, y1, x2, y2); if(d == (r1 + r2)): print "T"; elif(d < (r1 + r2)): print "Y"; else: print "N";
Emma is fond of prime numbers. Emma’s teacher gave her an interesting problem to solve. The problem is as follows: The teacher gave Emma 2 positive integers x and y(x ≤ y). She asked Emma to find the sum of all the prime numbers between x and y(x and y inclusive). The teacher gave Emma a few such pairs to calculate t...
def mysieve(n): for i in xrange(2, n): if i * i <= n and not prime[i]: for j in xrange(i * i, n, i): prime[j] = 1 def comp(): for i in xrange(2, n): if not prime[i]: pre[i] = pre[i-1] + i else: pre[i] = pre[i - 1] n = 1000001 prime ...
Dean is watching movie while his younger brother Sam comes and says that he is having difficulty in solving a problem given for homework by his math teacher. Now his older brother Dean who is good in programming asks him to tell the question. Sam replies according to question he has to enter n inputs plus an additional...
''' # 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,m=map(int,raw_input().split()) l=[int(i) for i in raw_input().split()] if m in l: print "1" else: print"0"
Lets call a string which is composed of only 4 and 7 a Lucky String. For example, 47, 444, 44744 are all Lucky Strings of length 2, 3 and 5 respectively, while 45, 767 are not Lucky Strings. Now, consider a sorted list of all the Lucky Strings that can be formed where the sorting is done by the following rule: A stri...
def count(n): i=0 n+=1 while(n!=0): n/=2 i+=1 return i-1 k=int(raw_input()) while(k>0): a="" k-=1 n=int(raw_input()) c=count(n) lb=(2**c)-1 ub=lb*2 while(lb<ub): mid=(lb+ub)/2 if(n>mid): a+="7" lb=mid+1 else: a+="4" ub=mid print a
Navi is at the Beer Bar where he has ordered N beers. After seeing his love with the beers, Bar's Manager has decided to make as much money as they can by asking Navi to pay K * i^3 Rupees for the i^th beer. But Navi has only M Rupees in his purse. So you are required to lent him some money so that he can still be abl...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = input() while(t>0): n,k,m = map(int,raw_input().split()) sum = (n*(n+1))/2 sum*=sum sum*=k if(sum>m): print sum-m else: print 0 t-=1
Anurag is posed with a very serious problem. He will be in London during the summers from days [ a,b ] for an internship. But he also wants to attend the ACM-ICPC World Finals with his team to be held in Thailand during [ c,d ] days. The opening ceremony for the World Finals will be held on c day. He found out that it ...
t=input() while t: t-=1 a,b,c,d,S = map(int, raw_input().split()) if c<=a or (a+S)>c: print 'STAY IN LONDON' elif (b+S)<c: # print (b-a+1) print b else: x = c-S if a<=x<=b: # print (x-a+1) print x else: print 'STAY IN LONDON'
Harry has been tracking Draco Malfoy throughtout the year on the Marauder's Map. But suddenly one day, Harry could not locate Draco on the map. Now he decides to search the entire map. But since the Marauder's map is of the entire Hogwarts school, it will take Harry a lot of time to search Malfoy. So he decides to loo...
from sys import stdin def area(): for t in xrange(input()): n = input() a = [] b = [] for j in xrange(n): x,y = map(int,raw_input().split()) a.append(x) b.append(y) t1 = min(a) t2 = max(a) t3 = min(b) t4 = max(b) ...
In the race for the best Internet browser, there's now a new contender for it, this browser is called the: "The Semantic Mind-Reader!" After its promo on the world wide web, everyone's been desperately waiting for the browser to be released. And why shouldn't they be curious about it, after all, it's the new project of...
t=input() vovels=['a','e','i','o','u'] for i in range(0,t): inputstr=raw_input() inputlen=len(inputstr) reqstr=inputstr[4:inputlen-3] reqlist=list(reqstr) count=0 for i in range(0,len(reqlist)): if(reqlist[i] in vovels): count=count...
Xynazog was playing a game. He needed to score k points and he could play at most N moves and at least 1 move. In each move, he could get [0,k] points. Note: the number of points gained is always an integer. Xynazog's friend PowerShell challenged Xenny to find the number of ways in which he could score k points in exa...
import math t=input() while t>0: n,k=map(int,raw_input().split()) print math.factorial(k+n-1)/(math.factorial(k)*math.factorial(n-1)) t=t-1
Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second. The other child is now at coordinate B, and she can travel the distance of W per second. He can catch ...
a,v=map(int, input().split()) b,w=map(int, input().split()) t=int(input()) dist=abs(b-a) dist2=(v-w)*t if dist>dist2: print("NO") else: print("YES")
In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}. You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.) To make the paymen...
import java.io.*; import java.util.*; public class Main { static void solve() { String tmp = ns(); tmp = "0"+tmp; int n = tmp.length(); char s[] = tmp.toCharArray(); reverse(s); long dp[][] = new long[n+1][2]; fill(dp, inf); dp[0][0] = 0; for(int i=0;i<n;i++) { int now = s[i] - '0';//今見ている桁の数 ...
Takahashi will do a tap dance. The dance is described by a string S where each character is `L`, `R`, `U`, or `D`. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character. S is said to be easily playable if and onl...
#include <iostream> using namespace std; int main(){ string s; cin>>s; for(int i=0;i<s.size();i++){ if(i%2==0 && s[i]=='L'){ cout<<"No"<<endl; return 0; } if(i%2==1 && s[i]=='R'){ cout<<"No"<<endl; return 0; } } cout<<"Yes"<<endl; }
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written. Let A_i be the integer written on the i-th card. Your objective is to guess A_1, A_2, ..., A_N correctly. You know the following facts: * For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number. You ar...
N, M = map(int,input().split()) par = [i for i in range(N+1)] size = [1 for _ in range(N+1)] def find(x): if par[x] == x: return x else: par[x] = find(par[x]) return par[x] def unite(x,y): x = find(x) y = find(y) if x == y: return 1 par[x] = y size[y] += siz...
Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise. There are N...
#include <bits/stdc++.h> using namespace std; long long solve(long long l, int n, vector<long long> &x, vector<long long> &y) { long long ret = 0; vector<long long> cumx(n+1, 0), cumy(n+1, 0); for (int i = 0; i < n; i++) { cumx[i+1] = cumx[i] + x[i]; cumy[i+1] = cumy[i] + y[i]; } fo...
Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 ...
#include<stdio.h> int num[4]; int main() { int n,d1,d2; scanf("%d%d%d",&n,&d1,&d2); int num1=0,num2=0; while((d1&1)==0) { num1++; d1>>=1; } while((d2&1)==0) { num2++; d2>>=1; } for(int i=0;i<(n<<1);i++) { for(int j=0;j<(n<<1);j++) { int tp1,tp2; if(num1&1) { tp1=((i>>(num1>>1))&1); ...
There are N positive integers written on a blackboard: A_1, ..., A_N. Snuke can perform the following operation when all integers on the blackboard are even: * Replace each integer X on the blackboard by X divided by 2. Find the maximum possible number of operations that Snuke can perform. Constraints * 1 \leq N...
input() a = list(map(int, input().split())) ans = 0 while all(i%2 == 0 for i in a): a = [n/2 for n in a] ans += 1 print(ans)
Joisino is planning on touring Takahashi Town. The town is divided into square sections by north-south and east-west lines. We will refer to the section that is the x-th from the west and the y-th from the north as (x,y). Joisino thinks that a touring plan is good if it satisfies the following conditions: * Let (p,q)...
#include<bits/stdc++.h> #define mod 1000000007 #define reg register #define maxn 2000006 using namespace std; int inv[maxn], fac[maxn], ifac[maxn], X1, X2, X3, X4, X5, X6, Y1, Y2, Y3, Y4, Y5, Y6; int f[maxn], g[maxn], ans; int inc(int x, int y){ return x + y >= mod ? x + y - mod : x + y; } int C(int x, int y){ ...
There are N integers written on a blackboard. The i-th integer is A_i. Takahashi and Aoki will arrange these integers in a row, as follows: * First, Takahashi will arrange the integers as he wishes. * Then, Aoki will repeatedly swap two adjacent integers that are coprime, as many times as he wishes. We will assume...
#include <cstdio> #include <algorithm> #include <vector> #include <set> int N, a[2001], G[2001][2001], q[2002], ue[2002], ref[2002], v[2001], L, d[2001]; std::vector < int > E[2001]; int gcd(int a, int b) { int r; while (b) { r = a % b; a = b; b = r; } return a; } int main() { scanf("%d", &N); for (int i =...
Gorillas in Kyoto University are good at math. They are currently trying to solve problems to find the value of an expression that contains two functions, `_` , `^`. Each of these functions takes two input values. `_` function returns the smaller of the two input values and `^` function returns the larger. Gorillas kno...
#include <cstdio> #include <algorithm> #include <stack> #include <queue> #include <deque> #include <vector> #include <string> #include <string.h> #include <cstdlib> #include <ctime> #include <cmath> #include <map> #include <set> #include <iostream> #include <sstream> #include <numeric> #include <cctype> #include <bitse...
Hit n nails one by one at the coordinates P1 (x1, y1), P2 (x2, y2), P3 (x3, y3), ..., Pn (xn, yn) on the flat plate, and put them on the rubber band ring. Surround it with a single rubber band so that all the nails fit inside. At this time, the rubber bands must not intersect. Create a program that reads the coordinat...
import java.util.*; class Main { Scanner sc = new Scanner(System.in); public void run() { while(sc.hasNext()){ int n=sc.nextInt(); if(n==0)break; P[] ps=new P[n]; for(int i=0;i<n;i++){ String[] str=sc.next().split(","); ps[i]=new P(Double.parseDouble(str[0]),Double.parseDouble(str[1])); } ...
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro'...
import java.util.Arrays; import java.util.Scanner; public class Main { final int INF = 1<<28; int solve(final int s, final int e, final int[][] map, final int n){ boolean[] used = new boolean[n]; int d[] = new int[n]; Arrays.fill(d, INF); d[s] = 0; while(true){ int u=-1; for(int v=0; v<n; ++v){...
The supercomputer system L in the PCK Research Institute performs a variety of calculations upon request from external institutes, companies, universities and other entities. To use the L system, you have to reserve operation time by specifying the start and end time. No two reservation periods are allowed to overlap e...
#include <bits/stdc++.h> using namespace std; int main() { int l,r,n; cin >> l >> r >> n; int d[1111]; memset(d,0,sizeof(d)); for(int i=0; i<n; i++) { int x,y; cin >> x >> y; for(int j=x; j<y; j++) d[j]=1; } for(int i=l; i<r; i++) { if(d[i]) { cout << 1 << endl; return 0; ...
The Kingdom of JOIOI is a rectangular grid of $H \times W$ cells. In the Kingdom of JOIOI, in order to improve efficiency of administrative institutions, the country will be divided into two regions called "JOI" and "IOI." Since we do not want to divide it in a complicated way, the division must satisfy the following ...
#include <iostream> #include <algorithm> #define INF 1001001001001001001 using namespace std; typedef long long ll; ll H,W,a_max,a_min; ll ary[2010][2010],lma[2010][2010],lmi[2010][2010],rma[2010][2010],rmi[2010][2010],dp[2][2010]; inline ll amax(ll a,ll b){ if(abs(a)>(INF/2)) a=0; if(abs(b)>(INF/2)) b=0; return m...
Mr. Denjiro is a science teacher. Today he has just received a specially ordered water tank that will certainly be useful for his innovative experiments on water flow. <image> --- Figure 1: The water tank The size of the tank is 100cm (Width) * 50cm (Height) * 30cm (Depth) (see Figure 1). For the experiments, he fits...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using vll = vector<ll>; using vvll = vector<vll>; using P = pair<int, int>; const double eps = 1e-8; const ll MOD = 1000000007; const int INF = INT_MAX / 2; const ll LINF = LLONG_MAX / 2; template<typenam...
Let’s play a stone removing game. Initially, n stones are arranged on a circle and numbered 1, ... , n clockwise (Figure 1). You are also given two numbers k and m. From this state, remove stones one by one following the rules explained below, until only one remains. In step 1, remove stone m. In step 2, locate the k-...
#include <iostream> #include <vector> using namespace std; int main () { int n, k, m; while (cin >> n >> k >> m, (n || m || k)) { vector<int> v(n); for (int i = 1; i <= n; i++) { v[i - 1] = i; } m--; while (v.size() > 1) { v.erase(v.begin() + m);...
Ambiguous Encoding A friend of yours is designing an encoding scheme of a set of characters into a set of variable length bit sequences. You are asked to check whether the encoding is ambiguous or not. In an encoding scheme, characters are given distinct bit sequences of possibly different lengths as their codes. A ch...
#include <bits/stdc++.h> using namespace std; using Pi = pair < int, int >; using IPi = pair < int , Pi >; constexpr int INF = (1 << 30) - 1; void chmin(int &a, int b) { a = min(a, b); } int main() { int N; int dp[1005][20]; string S[1005]; priority_queue < IPi, vector < IPi > , grea...
Scores of Final Examination I am a junior high school teacher. The final examination has just finished, and I have all the students' scores of all the subjects. I want to know the highest total score among the students, but it is not an easy task as the student scores are listed separately for each subject. I would li...
#include<bits/stdc++.h> using namespace std; int main(){ int n,m; cin >> n >> m; while(n!=0){ vector<int> sub(n,0); for(int j = 0;j<m;j++){ for(int i = 0;i<n;i++){ int a; cin >> a; sub.at(i) += a; } } s...
You are an officer of the Department of Land and Transport in Oykot City. The department has a plan to build a subway network in the city central of Oykot. In the plan, n subway lines are built, and each line has two or more stations. Because of technical problems, a rail track between two stations should be straight ...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-12; int n; int[] s; P[][] ps; int mask=(1>...
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to quickly solve popular puzzles and train your instantaneous power. Today's challenge is a puzzle of colorful tiles lined up and erasing them well. In the initial st...
#include<iostream> #include<map> #include<cassert> #include<cstdlib> #include<algorithm> #include<vector> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) typedef long long ll; typedef pair<int,int> pii; const int N = 500; char m[N][N+1]; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0...
Usoperanto is an artificial spoken language designed and regulated by Usoperanto Academy. The academy is now in study to establish Strict Usoperanto, a variation of the language intended for formal documents. In Usoperanto, each word can modify at most one other word, and modifiers are always put before modifiees. For...
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define pll pair<LL, LL> #define pii pair<int, int> #define X first #define Y second #define MAXN 1000010//1e3 #define lson l, mid, (rt << 1) #define rson mid + 1, r, (rt << 1 | 1) const double eps = 1e-10; int n; vector<int> roo...
Nathan O. Davis is running a company. His company owns a web service which has a lot of users. So his office is full of servers, routers and messy LAN cables. He is now very puzzling over the messy cables, because they are causing many kinds of problems. For example, staff working at the company often trip over a cabl...
#include<bits/stdc++.h> using namespace std; #define int long long typedef pair<int,int>pint; typedef vector<int>vint; typedef vector<pint>vpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n)...
Problem statement There is a village called Biwako, which consists of $ N $ islets floating on the lake. Biwako Village has a simple bridge with $ N-1 $ books. The islands are numbered from $ 0 $ to $ N-1 $, and the bridges are numbered from $ 0 $ to $ N-2 $. The $ i $ bridge directly connects the $ i + 1 $ island and...
#include<bits/stdc++.h> using namespace std; #define int long long typedef pair<int,int>pint; typedef vector<int>vint; typedef vector<pint>vpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n)...
As an English learner, sometimes you cannot remember the entire spelling of English words perfectly, but you can only remember their prefixes and suffixes. For example, you may want to use a word which begins with 'appr' and ends with 'iate', but forget the middle part of the word. It may be 'appreciate', 'appropriate'...
#include<bits/stdc++.h> using namespace std; #define lp(i,n) for(int i=0;i<(int)n;i++) template<unsigned mod> struct RollingHash{ vector<unsigned> hashed,power; inline unsigned mul(unsigned a,unsigned b) const{ unsigned long long x = (unsigned long long)a*b; unsigned xh=unsigned(x>>32),xl=(unsigned)x,d,m;...
Problem Den, the phone number of Ukunikia Co., Ltd., enters a very long phone number into the phone every day. One day, too tired, Den came up with a surprising idea. "Isn't it even a little easier if you rearrange the arrangement of the buttons on the phone ?!" The phone has squares evenly spaced at $ 3 \ times 3 $,...
#include <bits/stdc++.h> using namespace std; using ll = 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 fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
<image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT ...
x0,y0,x1,y1 = map(int, input().split()) p0=complex(x0,y0) p1=complex(x1,y1) q = int(input()) CCW = {1: 'COUNTER_CLOCKWISE', -1: 'CLOCKWISE', 2: 'ONLINE_BACK', -2: 'ONLINE_FRONT', 0: 'ON_SEGMENT',} def dot(a, b): return a.real * b.real + a.imag * b.imag def cross(a, b): return a.real *...
For given three integers $a, b, c$, print the minimum value and the maximum value. Constraints * $-1,000,000,000 \leq a, b, c \leq 1,000,000,000$ Input The input is given in the following format. $a \; b \; c\;$ Three integers $a, b, c$ are given in a line. Output Print the minimum and maximum values separate...
#include <bits/stdc++.h> using namespace std; int main() { int a[3]; cin>>a[0]>>a[1]>>a[2]; sort(a+0,a+3); cout<<a[0]<<" "<<a[2]<<endl; return 0; }
Problem description As a holiday gift, Tojo received a probability problem. The problem read as follows Consider an N by M grid. Rows are numbered 1 to N, from top to bottom. Columns are numbered 1 to M, from left to right. You are initially at cell (1, 1) and want to go to cell (N, M). From any cell you can move to th...
t=int(raw_input()) while(t>0): t-=1 n,m=[int(i) for i in raw_input().split()] print ("%.6f" % (n+m-1))
Chef likes playing with strings. The most interesting game are named "CHEF in string". The move of the game consists of the following: Chef takes a subsequence of string's letters that form the word "CHEF" and then he removes that symbols. The goal of the game is to make the maximal number of moves. Please, help Chef a...
chef = raw_input() def find_index(chef, index): c1,h1,e1,f1 = index c = chef.find('C', c1+1) if c<0: return None h = chef.find('H', max(c+1, h1+1)) if h<0: return None e = chef.find('E', max(h+1, e1+1)) if e<0: return None f = chef.find('F', max(e+1, f1+1)) i...
Lots of geeky customers visit our chef's restaurant everyday. So, when asked to fill the feedback form, these customers represent the feedback using a binary string (i.e a string that contains only characters '0' and '1'. Now since chef is not that great in deciphering binary strings, he has decided the following crit...
# your code goes here t=int(raw_input()) while t>0: s=str(raw_input()) f1=s.find('010') f2=s.find('101') if f1>-1 and f2>-1: print "Good" elif (f1 > -1 and f2== -1) or (f1==-1 and f2 > -1): print "Good" else: print "Bad" t=t-1
Chef likes arrays a lot. Today, he found an array A consisting of N positive integers. Let L denote the sorted (in non-increasing order) list of size N*(N+1)/2 containing the sums of all possible contiguous subarrays of A. Chef is interested in finding the first K elements from the list L. Can you help him in accomplis...
import math import heapq def parseIntList(str): return [long(x) for x in str.split()] def printBS(li): if len(li) is 0: print else: for i in range(len(li)-1): print li[i], print li[-1] n,k=parseIntList(raw_input()) li=parseIntList(raw_input()) s=0 for i in range(n): s+=li[i] hp=[[-s,1,n]] res=[] st={tuple(...
Note: For Turbo C++, select "Text" as your language   Problem Description: In IIIT we use password system to unlock the lab doors and only Mtech students are given the password for these labs. Password system comprises of n*n keypad where n is odd. One day Ashish saw an Mtech student using the password. He figured out ...
n=input() d=[] for i in range(n): v=[] s=input() for i in range(s): c=[] b='' b=raw_input() for i in b.split(): c.append(int(i)) v.append(list(c)) d.append(v) w=[] for i in range(len(d)): if d[i][len(d[i])/2][0]==d[i][len(d[i])/2][-1]: if d...
There are given n men and n women. Each woman ranks all men in order of her preference (her first choice, her second choice, and so on). Similarly, each man sorts all women according to his preference. The goal is to arrange n marriages in such a way that if a man m prefers some woman w more than his wife, and w prefer...
from sys import stdin from cStringIO import StringIO def main(): inp = iter(StringIO(stdin.read())).next t = int(inp()) for _ in xrange(t): n = int(inp()) w = {} m = {} freem = set([`i+1` for i in xrange(n)]) freew = set([`i+1` for i in xrange(n)]) mproposed ...
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; using namespace std; struct BigInt { BigInt(int64_t initValue = 0) { *this = initValue; } BigInt(const std::vector<int>& s, int sign) { this->s = s; this->sign = sign; } const BigInt& operator=(int64_t value) { sign = value < 0 ? -1 : 1; uint64_t abs...
Recently Vasya found a golden ticket — a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. No...
n = int(input()) s = input() arr = list() arr.append(int(s[0])) summ = arr[0] bigflg = False for i in range(1,len(s)): arr.append(int(s[i])) summ+=arr[i] for i in range(2,len(s)+1): if summ % i == 0: amount = summ / i sm = 0 flg = True for j in range(len(arr)): sm...
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k. Help Vasya! Find such points (if it's possible). If there are multiple solutio...
#include <bits/stdc++.h> inline int read() { char ch = getchar(); int ret = 0, f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } for (; ch >= '0' && ch <= '9'; ch = getchar()) ret = ret * 10 + ch - '0'; return ret * f; } using namespace std; const int INF = 1 << 30; int ...
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5. Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents — n riders. Each resident (including taxi drivers) of Palo...
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.ma...
You are given an angle ang. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon. <image> If there are several answers, print the minimal one. It is guarantied t...
import math t=int(input()) for e in range(t): n=int(input()) g=math.gcd(n,180) p=n//g q=180//g if n==180 or n==0: print(-1) else: if p==q-1: print(2*q) else: print(q)
Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g...
import sys MOD = 10**9+7 def mult(A,B): n = len(A) C = [] for x in range(n): c = [0]*n for z in range(n): b = B[x][z] a = A[z] for y in range(n): c[y] += a[y]*b for y in range(n): c[y]%=MOD C.append(c) retu...
Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one. Vasya drew several distinct points with integer coordinates on a plane and then drew an...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 7; pair<long long, long long> p[MAXN]; int n, res = 0; bool cw(pair<long long, long long> a, pair<long long, long long> b, pair<long long, long long> c) { return (b.first - a.first) * (c.second - b.second) - (c.first - b.first) ...
Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be: * A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer. * The [bitwis...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int n; vector<int> cur, keep, basis; void ins(int x) { int now = x; for (int i : basis) { x = min(x, x ^ i); } if (x > 0) { keep.push_back(now); basis.push_back(x); for (int i = (int)basis.size() - 1; i > 0; i--) { if...
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und...
import java.util.*; public class Main { public static class Pair implements Comparable<Pair> { long d; int g; Pair(long d,int g) { this.d=d; this.g=g; } public int compareTo(Pair p) { return (int)this.d-(int)p.d; } } public...
You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k ≥ 0, calculate the expression s_k = f(x) + f(y) ⋅ 2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e...
#include <bits/stdc++.h> using namespace std; int prime(long long int n) { for (long long int i = 2; i < n; i++) { if (n % i == 0) { return 0; } } return 1; } int sgn(long long int n) { if (n > 0) { return 1; } else { return -1; } } long long int max_digit(long long int n) { long lon...
Bob Bubblestrong just got a new job as security guard. Bob is now responsible for safety of a collection of warehouses, each containing the most valuable Bubble Cup assets - the high-quality bubbles. His task is to detect thieves inside the warehouses and call the police. Looking from the sky, each warehouse has a sha...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const long double PI = acosl(-1); mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct point { long double x, y; point() {} point(long double x, long double y) : x(x), y(y) {} long double kampas() { return atan2l(...
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
import math t=eval(input()) while t>0: a,b,c,d,k=map(int,input().split()) x=math.ceil(a/c) y=k-x flag=0 if y*d<b or y<0: flag=1 if flag==1: print(-1) else: print(x,y) t-=1
The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text. Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters)...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 7; int dat[maxn]; int minv[maxn << 2]; int maxv[maxn << 2]; int addv[maxn << 2]; char s[maxn]; void inline pushdown(int o) { if (!addv[o]) return; addv[(o << 1)] += addv[o]; addv[(o << 1 | 1)] += addv[o]; minv[(o << 1)] += addv[o]; minv[(o <...
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
def func(n): x = input() ans = 0 l_counter = x.count('L') r_counter = x.count('R') y = 0 - l_counter z = 0 + r_counter for i in range(y,z+1): ans += 1 print(ans) n = int(input()) func(n)
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo...
for tc in range(int(input())): n,m=map(int, input().split()) a=b=m m=0 fl=1 for tccc in range(n): t,l,h=map(int, input().split()) a-=(t-m) b+=(t-m) m=t if a<l: a=l if b>h: b=h if a>b: fl=0 print("YES") i...
The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal...
'''input 4 5 1 2 1 2 2 6 1 2 2 1 2 2 5 1 2 1 2 3 3 10 10 10 ''' import sys import math from collections import Counter debug = 1 readln = sys.stdin.readline #sys.setrecursionlimit(1000000) def write(s): sys.stdout.write(str(s)) def writeln(s): sys.stdout.write(str(s)) sys.stdout.write('\n') def readint...
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria. Initially, on day 1, there is one bacterium with mass 1. Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass m/2 each. For example, a ba...
import sys stdin = sys.stdin ns = lambda: stdin.readline().rstrip() ni = lambda: int(stdin.readline().rstrip()) nm = lambda: map(int, stdin.readline().split()) nl = lambda: list(map(int, stdin.readline().split())) def solve(): n = ni() da = n.bit_length() - 1 print(da) n -= da + 1 f = [0]*da ...
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
#include <bits/stdc++.h> using namespace std; int t, n, last; string s, wynik; int main() { ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin >> t; while (t--) { cin >> n >> s; wynik = ""; int ile0 = 0, ile1 = 0; for (int i = 0; i < s.size() && s[i] != '1'; i++) ile0++; for (int...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
#include <bits/stdc++.h> using namespace std; int main() { int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { printf("%d ", i); } printf("\n"); } return 0; }
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available...
#include <bits/stdc++.h> using std::cin; using std::min; using std::pair; using std::sort; const int MAXN = 2e5 + 10; int n, a[MAXN]; bool vis[MAXN]; int nxt[MAXN]; int get_nxt(int u) { return nxt[u] == u ? u : nxt[u] = get_nxt(nxt[u]); } int h, t; pair<int, int> q[MAXN]; int main() { scanf("%d", &n); char op; fo...
You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 ≤ a_2 ≤ a_3 ≤ ... ≤ a_n holds). To make the sequence sorted, you may perform the following operation any number of times you want (possibly ...
import math for _ in range(int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) ans=0 prob=0 rang=0 for i in range(1,n): if a[i]<a[i-1]: prob=1 rang=i for i in range(rang): if a[i]>k: a[i],k=k,a[i] ans+=1...
In Homer's school, there are n students who love clubs. Initially, there are m clubs, and each of the n students is in exactly one club. In other words, there are a_i students in the i-th club for 1 ≤ i ≤ m and a_1+a_2+...+a_m = n. The n students are so unfriendly that every day one of them (chosen uniformly at rand...
#include <bits/stdc++.h> #pragma GCC target ("avx2") #pragma GCC optimization ("O3") #pragma GCC optimization ("unroll-loops") using namespace std; typedef long long ll; const int N = 1010; const int MOD = 998244353; ll bigMod (ll a, ll e) { if (e == -1) e = MOD - 2; ll ret = 1; while (e) { if (e & 1) re...
You are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times: * you select two different numbers in the array a_i and a_j; * you remove i-th and j-th elements from the array. For example, if n=6 and a=[1, 6,...
import sys input=sys.stdin.readline t = int(input()) for i in range(t): n=int(input()) a=[int(x) for x in input().split()] a.sort() temp=1 if n==1: print(1) continue count=[] for i in range(1,n): if a[i]==a[i-1]: temp+=1 if i==n-1: ...
One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written. As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, ...
mod=10**9+7 n,m=map(int,input().split()) mat=[] for _ in range(n): s=input() mat.append(s) b=ord("A") s=[False]*255 res=1 for j in range(m): for i in range(b,b+26): s[i]=False for i in range(n): s[ord(mat[i][j])]=True r=0 for i in range(b,b+26): if(s[i]):r+=1 res*=r print(res%mod)
The main Bertown street is represented by a straight line. There are 109 bus stops located on the line. The stops are numbered with integers from 1 to 109 in the order in which they follow on the road. The city has n buses. Every day the i-th bus drives from stop number si to stop number fi (si < fi), it stops on all i...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int b[maxn << 3]; int id[maxn << 3]; int n, m; struct seg { int l, r, t, id; }; vector<int> val; int pos(int x) { return lower_bound(val.begin(), val.end(), x) - val.begin() + 1; } void build(int o, int l, int r) { if (r == l) { b[o] = -...
Vasya studies divisibility rules at school. Here are some of them: * Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even. * Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3. * Divisibility by ...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:167177216") using namespace std; int t2(int a, int b) { int k = 1; for (int i = 0; i < int(100); ++i) { k *= a; if (k % b == 0) return i + 1; k %= b; } return 0; } bool t3(int a, int b) { if ((a % b) == 1) return true; return false; } bool...
Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve. The camera's memory is d megabytes. Valera's camera can take photos of high and l...
#include <bits/stdc++.h> using namespace std; int A, B; struct Client { int a, b, idx; }; bool cmp(Client x, Client y) { return (x.a * A + x.b * B) < (y.a * A + y.b * B); } int main() { int n, d; cin >> n >> d >> A >> B; vector<Client> v(n); for (int i = 0; i < n; i++) { cin >> v[i].a >> v[i].b; v[i...
You've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we w...
#include <bits/stdc++.h> using namespace std; char mtx1[51][51]; int n1, m1; char mtx2[51][51]; int n2, m2; int x, y, ans, X, Y; void input() { int i; scanf("%d%d", &n1, &m1); for (i = 1; i <= n1; i++) { scanf("%s", mtx1[i] + 1); } scanf("%d%d", &n2, &m2); for (i = 1; i <= n2; i++) { scanf("%s", mtx...
Little Petya likes trees a lot. Recently his mother has presented him a tree with 2n nodes. Petya immediately decided to place this tree on a rectangular table consisting of 2 rows and n columns so as to fulfill the following conditions: 1. Each cell of the table corresponds to exactly one tree node and vice versa, ...
#include <bits/stdc++.h> using namespace std; int n, size[200000 + 5], dep[200000 + 5], pre[200000 + 5], le[200000 + 5], ri[200000 + 5], son[200000 + 5][4], e[200000 + 5], a[4]; long long dp[200000 + 5]; void dfs(int u, int fa) { size[u] = 1; for (int i = 0; i < e[u]; i++) { int v = son[u][i]; if (v == ...
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language...
from sys import stdin,stdout input = stdin.readline def main(): n, m = map(int,input().split()) sets = list(range(n+1+m)) sizes = [1]*(n+1+m) def get(a): if sets[a] != a: sets[a] = get(sets[a]) return sets[a] def union(a, b): a = get(a) b = get(b) ...
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sen...
#include <bits/stdc++.h> using namespace std; const int MAX = 1000000 + 5; int n; map<int, bool> visited; map<int, vector<int> > V; queue<int> Q; void Input() { cin >> n; for (int i = 1; i <= n; i++) { int x, y; cin >> x >> y; V[x].push_back(y); V[y].push_back(x); } } void DFS(int s) { Q.push(s)...
You are given a cube of size k × k × k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face. Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied: * each white cube has exactly 2 neighbourin...
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; if (N & 1) { cout << -1 << endl; return 0; } for (int i = 0; i < N; i++) { cout << endl; for (int j = 0; j < N; j++, cout << endl) { cout << endl; for (int k = 0; k < N; k++) { int n = min(min(j, k)...
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri...
import java.io.*; import java.util.*; public class D_D2_201 { public static int[] automata; static int s1len, s2len, M; static String s1, s2, virus; static int [][][] dp; static StringBuilder sb; public static void main(String[] args) throws IOException { Scanner in = new Scanner(Syste...
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer. As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the ...
#include <bits/stdc++.h> using namespace std; class p { public: int l, r, c; p(int l, int r, int c) : l(l), r(r), c(c) {} }; bool cmp(const p &i, const p &j) { return i.l < j.l; } int a[200002], n; vector<p> v; int l[100001], r[100001]; int d[6][100001]; int f(int h, int k) { if (k < 0) return 1; if (d[h][k] >...
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the pu...
#include <bits/stdc++.h> using namespace std; long long dp[4][4][50] = {0L}, t[5][5] = {0L}; bool dped[4][4][50] = {0}; long long move(int n, int from, int thr, int to) { if (dped[from][to][n]) return dp[from][to][n]; dped[from][to][n] = 1L; if (n == 0) return dp[from][to][n] = 0L; return dp[from][to][n] = ...
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem...
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) throws IOException { try { in = new BufferedReader(new FileReader("a.in")); ...
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game. Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards excep...
#include <bits/stdc++.h> using namespace std; int n; string s; bool a[6][6]; int ans = 8; void parse(string s) { int x = 0; int y = (int)(s[1] - '1'); if (s[0] == 'G') x = 1; else if (s[0] == 'B') x = 2; else if (s[0] == 'Y') x = 3; else if (s[0] == 'W') x = 4; a[x][y] = 1; return; } int...
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — c...
#include <bits/stdc++.h> using namespace std; template <typename T> T Abs(T first) { return (first < 0 ? -first : first); } template <typename T> T Sqr(T first) { return (first * first); } string plural(string s) { return (int((s).size()) && s[int((s).size()) - 1] == 'x' ? s + "en" ...
Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it is believed t...
#include <bits/stdc++.h> using namespace std; bool lucky(int i) { string val = to_string(i); for (char i : val) { if (i == '8') return true; } return false; } int main() { long long n; cin >> n; int cnt = 1; for (int i = n + 1;; i++) { if (lucky(i)) { break; } cnt++; } cout << ...
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old. They will have dinner around some round tables. You want to distribute foxes such that: 1. Each fox is sitting at some table. 2. Each table has at least 3 foxes sitting around it. 3...
#include <bits/stdc++.h> using namespace std; inline long long read() { char c = getchar(); long long f = 1, x = 0; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') x = x * 10 + (c - '0'), c = getchar(); return x * f; } void MOD(int &x) { if (x >= 10...
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ...
#include <bits/stdc++.h> using namespace std; const int INF = 1000000000; const double PI = 3.1415926535897932384626433832795028841971; long long sum[10000010], s[10000010]; int main() { long long n, m, a, b, l, t, r, j, i; cin >> a >> b >> n; for (i = 1; i <= 10000000; i++) { s[i] = a + (i - 1) * b; sum[...
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a1 × b1 rectangle, the paintings have shape of a a2 × b2 and a3 × b3 rectangles. Since th...
check = lambda ax, ay, bx, by, cx, cy : bx + cx <= ax and max(by, cy) <= ay inp = lambda : map(int, input().split()) x1, y1 = inp() x2, y2 = inp() x3, y3 = inp() if check(x1, y1, x2, y2, x3, y3) or check(y1, x1, x2, y2, x3, y3) or check(x1, y1, y2, x2, x3, y3) or check(y1, x1, y2, x2, x3, y3) or check(x1, y1, x2, y2, y...
The mobile application store has a new game called "Subway Roller". The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmo...
import java.awt.geom.Line2D; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StreamCorruptedException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparat...