input
stringlengths
29
13k
output
stringlengths
9
73.4k
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...
import java.io.*; import java.util.*; public class Problems1 { public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(System.in); int n=sc.nextInt(); if(n<3){ System.out.println(0); return; } System.out.printl...
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of...
#include <bits/stdc++.h> const int MAXN = 105; using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long last_of(long long a, long long b) { assert(b != 1); if (a % (b - 1) == 0) return a / (b - 1) - 1; return a / (b - 1); } long long cei(long long a, long long b) { retur...
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. ...
import java.io.*; import java.math.*; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; void solve() { int n = ni(); long x = nl(), y = nl(); int mx = (int) 2e6 + 3; int arr[] = new int[n]; int pre[] = new int[mx]; int val[] = new int[mx]; for (int i = 0;...
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his n sons-princes marry the brides with as big dowry as possible. In search of candidates, the king as...
#include <bits/stdc++.h> using namespace std; struct Edge { int x, y, v; } E[200005]; bool Cmp(Edge a, Edge b) { return a.v > b.v; } int Size[200005], Flag[200005]; int Fa[200005]; int GetRoot(int x) { return x == Fa[x] ? x : Fa[x] = GetRoot(Fa[x]); } int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 1...
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment n in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom. <image> The n-long segment is located at a distance equal exactly to...
#include <bits/stdc++.h> using namespace std; const int N = 1010; int n, a[N], b[N]; string s; int main() { scanf("%d", &n); for (int i = 1; i < (n + 1); ++i) scanf("%d", a + i); while (!a[n]) --n; int Min = 1 << 30, d = 1; for (int i = 1; i < (n + 1); ++i) { for (int j = 1; j < (n + 1); ++j) b[j] = a[j] ...
Let's denote as L(x, p) an infinite sequence of integers y such that gcd(p, y) = 1 and y > x (where gcd is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of L(x, p) are 1-indexed; for example, 9, 13 and 15 are the first, the second and the third elements of L(7, 22), respec...
#include <bits/stdc++.h> using namespace std; template <class T> struct rge { T b, e; }; template <class T> rge<T> range(T i, T j) { return rge<T>{i, j}; } struct debug { template <class T> debug& operator<<(const T&) { return *this; } }; using ll = long long; template <typename T> void min_self(T& a, T b...
It is never too late to play the fancy "Binary Cards" game! There is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either 2k or - 2k for some integer k β‰₯ 0. There is an infinite amount of cards ...
#include <bits/stdc++.h> using namespace std; bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; void etp(bool f = 0) { puts(f ? "YES" : "NO"); exit(0); } void addmod(int &x, int y, int mod = 1000000007) { assert(y >= 0); x += y; if (x >...
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: * divide the number x by 3 (x must be divisible by 3); * multiply the number x by 2. After each operation, Polycarp writes down the result on the boar...
n = int(input()) li = list(map(int, input().split())) g = {} def dfs(e, v, order): if e not in v: v[e] = 1 if e % 3 == 0: if (e // 3) in g: order.append(e // 3) dfs(e // 3, v, order) if e * 2 in g: order.append(e * 2) dfs(...
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as...
#include <bits/stdc++.h> using namespace std; signed main() { long long n; cin >> n; long long ans = 0; long long L = -4 * 45, R = 45; map<long long, long long> vls; for (long long i = L; i <= R; i++) vls[i] = 1e18; for (long long i = 0; i < 100; i++) { for (long long j = 0; j < 100; j++) { for ...
Alice and Bob are fighting over who is a superior debater. However they wish to decide this in a dignified manner. So they decide to fight in the Battle of Words. In each game both get to speak a sentence. Because this is a dignified battle, they do not fight physically, the alphabets in their words do so for them. ...
''' # 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!' t=int(raw_input()) while(t): t-=1 s1=raw_input() s2=raw_input() c1=[] c2=[] for i in range(27): c1.append(0) c2.append(0) #print(c) for i in range(len(...
Alice is climbing stairs. There are total N stairs. She climbs A stairs upwards in day and she comes downstairs in night by B stairs. Find number of days she will take to reach the top of staircase. Input: First and only line contains three space separated integers denoting A, B, N. Output: Print only one line o...
import math x,y,z=map(eval, raw_input().split()) a,b,n=int(x),int(y),int(z) ans=math.ceil((float(n-b)/float(a-b))) print(int(ans))
Geeko is in worry now because exam is coming up and he has to know what rank he can get in exams. So he go back into the school records and finds the amazing pattern. He finds that if a student is having a current rank n than his rank in the final exam will be the count positive numbers between in the range [1...
def main(): from collections import defaultdict from itertools import count from fractions import gcd from operator import mul from sys import stdin,stdout def lcm(a, b): return a * b / gcd(a, b) primes_cache, prime_jumps = [], defaultdict(list) def primes(): prime...
Archith loves to play with number series. Archith asked his girlfriend to a date. But she was busy in solving the homework on triangular series which stated that find the least number which has higher divisors than n in a triangular series. His girlfriend made a condition that if he solves this assignment for her she w...
test = int(raw_input()) while test>0: n = int(raw_input()) if n==0: print 1 else: i = 2 while(1): x = i*(i+1)/2 j = 1 c = 0 while j<=x: if x%j==0: c+=1 j+=1 if c>n: print x break i+=1 test-=1
Team India is playing too much cricket in this season. Team players are getting better in their performance with match by match. Sir Jadeja has become a Trump Card for M.S Dhoni. There is a hidden reason of his special position in the team. He can make new copies of a person by some magic. Due to this, players can get ...
import math test = int(raw_input()) while test: test = test-1 l = [ "Rohit", "Dhawan", "Kohli", "Yuvraj", "Raina" , "Dhoni", "Sir Jadeja"] k = int(raw_input()) val = math.log(k/7.0+1)/math.log(2) n = int(math.ceil(val)) sn_1 = 7*(int(math.pow(2,n-1))-1) inte = math.ceil(((k-sn_1)/math.pow(2,n-1))) print l[int(i...
Lucky numbers are defined as the numbers consisting only of digits 3 and 5. So, given a number N, you have to print the least lucky number strictly greater than N. Input: First line of input contains number of test cases T. Each test case contains a single number N. Output: For each test case, print the next lucky ...
def next_lucky(n): if len(n) == 0: return '' if int(n[0]) < 3: return '3'*len(n) elif int(n[0]) == 3: pos1 = int(n[0]+next_lucky(n[1:])) pos2 = int('5'+'3'*(len(n)-1)) possible = min(pos1,pos2) larger = max(pos1,pos2) if possible > int(n): ...
A Professor of Physics gave projects to the students of his class. The students have to form a team of two for doing the project. The professor left the students to decide the teams. The number of students in a class will be even. Each student has a knowledge level. It tells how much knowledge each student has. The kn...
t = input() for i in range(int(t)): i = map(int,raw_input().split()) #i = i.split(' ') n = i[0] _list = i[1:] _list.sort() i,j,a,b = 0,n-1,100001,0 while i<j: chk = _list[i]+_list[j] a = min(chk,a) b = max(chk,b) i += 1 j -= 1 print b-a
Watson gives to Sherlock a bag of numbers [1, 2, 3 ... N] and then he removes K numbers A1, A2 ... AK from the bag. He now asks Sherlock to find the P'th smallest number in the bag. Input First line contains T, the number of test cases. Each test case consists of N, K and P followed by K integers in next line denoting...
t = input(); while(t > 0): n, k, p = map(int, raw_input().split()); cl = p; a = [int(i) for i in raw_input().split()]; for i in range(0, k): if(a[i] <= cl): cl += 1; if(cl <= n): print cl; else: print -1; t -= 1;
Alice and Bob are taking a walk in the Land Of Doors which is a magical place having a series of N adjacent doors that are either open or close. After a while they get bored and decide to do something interesting. So they started closing the open doors taking turns. In each turn, the person walks upto any closed door...
t = int(raw_input()) for ti in range(t): door = raw_input() n = len(door) i = 0 op = [] while i<n: if door[i] == '_': j = 1 while i<n and door[i]== '_': i += 1 j += 1 op.append(j-1) i += 1 #print op if not op: print "Bob" elif len(op)==1 and op[0]<=n-1: print "Alice" elif len(op)==1 ...
Xsquare got bored playing with the arrays all the time. Therefore he has decided to buy a string S consists of N lower case alphabets. Once he purchased the string, He starts formulating his own terminologies over his string S. Xsquare calls a string str A Balanced String if and only if the characters of the string str...
t = int(raw_input()) for i in range(t): flag = 0 s = raw_input() d = {} for j in s: d[j] = d.get(j,0) + 1 for j,k in d.iteritems(): if(k%2 != 0): flag = 1 break if flag == 1: print -1 else: print 1
We have N lamps numbered 1 to N, and N buttons numbered 1 to N. Initially, Lamp 1, 2, \cdots, A are on, and the other lamps are off. Snuke and Ringo will play the following game. * First, Ringo generates a permutation (p_1,p_2,\cdots,p_N) of (1,2,\cdots,N). The permutation is chosen from all N! possible permutations ...
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define eb emplace_back #define all(v) (v).begin(),(v).end() #define fi first #define se second using vint=vector<int>; using pint=pair<int,int>; using vpint=vector<pint>; template<typenam...
Serval is fighting with a monster. The health of the monster is H. In one attack, Serval can decrease the monster's health by A. There is no other way to decrease the monster's health. Serval wins when the monster's health becomes 0 or below. Find the number of attacks Serval needs to make before winning. Constrai...
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int H = sc.nextInt(); int A = sc.nextInt(); System.out.println(H%A==0 ? H/A : H/A+1); } }
There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`. A person is happy if the person in front of him/her is facing the...
#include<iostream> #include<algorithm> using lint=int64_t; using namespace std; int main() { int N,K; string S; cin >> N >> K; cin >> S; int cnt=0; for(int i=0;i<S.size()-1;i++) { if(S[i]==S[i+1]) cnt++; } cout << min(cnt+2*K,N-1) << endl; return 0; }
We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. On this grid, there is a piece, which is initially placed at square (s_r,s_c). Takahashi and Aoki will play a game, where each player has a st...
#include <cstdio> using namespace std; int h, w, n; int sr, sc; char t[200001]; char a[200001]; int d[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; char dir[5] = "RLDU"; int main() { scanf("%d %d %d", &h, &w, &n); scanf("%d %d", &sr, &sc); scanf("%s", t); scanf("%s", a); int by, bx; int flag = 0; for (int i ...
There are N positive integers A_1, A_2, ..., A_N. Takahashi can perform the following operation on these integers any number of times: * Choose 1 \leq i \leq N and multiply the value of A_i by -2. Notice that he multiplies it by minus two. He would like to make A_1 \leq A_2 \leq ... \leq A_N holds. Find the minimu...
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define sqr(x) ((x)*(x)) #define mp make_pair #define ld long double #define PI pair<int,int> inline char gc(){ static char buf[100000],*p1=buf,*p2=buf; return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++; } #define gc getcha...
Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively. After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get: * Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own inte...
# A, B, C # B+C, C+A, A+B => 0A1B1C, 1A0B1C, 1A1B0C 1time => B-A # CAAB, BCAB, BCCA => 2A1B1C, 1A2B1C, 1A1B2C 2time => A-B # BCABBCCA, CAABBCCA, CAABBCAB => 2A3B3C, 3A2B3C, 3A3B2C 3time => B-A # CAABBCCACAABBCAB, BCABBCCACAABBCAB, BCABBCCACAABBCCA # => 6A5B5C, 5A6B5C, 5A5B6C 4time => A-B # A,B,C,K = map(int, raw_...
ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Ka...
#include"bits/stdc++.h" using namespace std; using ll = int64_t; int main() { ll K, A, B; cin >> K >> A >> B; if (K <= A) { cout << 1 << endl; } else if (A - B <= 0) { cout << -1 << endl; } else { ll t = K - A; cout << (t + (A - B) - 1) / (A - B) * 2 + 1 << endl; ...
There are N squares in a row. The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty. Aohashi would like to fill the empty squares with integers so that the following condition is satisfied: * For any two adjacent squares, the (absolute) difference of the two...
#include <stdio.h> long long n, a, b, c, d, e; int main() { scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &d); n--; for (long long i = 0; i <= n; i++) { if (c * i - d * (n - i) <= a - b && a - b <= d * i - c * (n - i))e = 1; } if (e)printf("YES\n"); else printf("NO\n"); }
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1. There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so th...
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; vector<long>a(n); vector<long>b(n); int i; for(i=0;i<n;i++){ cin >> a[i] >> b[i]; } long ans = 0; for(i=n-1;i>=0;i--){ a[i] += ans; if(a[i]%b[i]!=0)ans += b[i]-a[i]%b[i]; } cout << ans; }
Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vert...
import sys def solve(A): nc = 1 while nc < len(A) and A[nc] == A[0]: nc += 1 if nc > 2: return False for i in xrange(1, len(A)): if A[i] - A[i-1] > 1: return False c = 2 prev = -1 for j in xrange(nc, len(A)): if A[j] == prev: c += 1 ...
As I was cleaning up the warehouse, I found an old document that describes how to get to the treasures of my ancestors. The following was written in this ancient document. 1. First, stand 1m east of the well on the outskirts of the town and turn straight toward the well. 2. Turn clockwise 90 degrees, go straight for ...
import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); double th[] = new double[1001]; double r[] = new double[1001]; r[1] = 1; th[1] = 0; for (int i = 1; i < 1000; i++) { r[i + 1] = Math.sqrt(r[i] * r[i] + 1); th[...
An architect, Devunky, who lives in Water Deven, has been asked to renovate an old large hospital. In some countries, people don't want to use numbers that are disliked as numerophobia (4 and 9 are famous in Japan). However, the room numbers in this hospital were numbered from 1 regardless of the number of numerophobi...
#include<iostream> using namespace std; int main() { while(1){ int a, j=0; cin >> a; if (a == 0)break; j = a; string s=""; int b = 0; for (b = 1; b * 8 <= a; b *= 8) {} for (int c = b; c != 1; c /= 8) { int o =a/c; switch (a / c) { case 0:case 1:case 2:case 3:cout << a / c; break; case 4:...
You have a cross-section paper with W x H squares, and each of them is painted either in white or black. You want to re-arrange the squares into a neat checkered pattern, in which black and white squares are arranged alternately both in horizontal and vertical directions (the figure shown below is a checkered patter wi...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld=long double; int main() { int W,H;cin>>W>>H; vector<vector<int>>field(H,vector<int>(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { cin>>field[i][j]; } } ...
Problem statement JOI decided to start a new social game from tomorrow. In this social game, you can log in up to once a day, and you will get A coins each time you log in. Also, if you log in for 7 consecutive days from Monday to Sunday, you will get an additional B coins each time. No other coins will be given. ...
#include <iostream> using namespace std; int main() { int A, B, C, ans = 0, sum = 0; cin >> A >> B >> C; while (C > sum) { ++ans; sum += A; if (ans % 7 == 0) sum += B; } cout << ans << endl; }
Good evening, contestants. If a and d are relatively prime positive integers, the arithmetic sequence beginning with a and increasing by d, i.e., a, a + d, a + 2d, a + 3d, a + 4d, ..., contains infinitely many prime numbers. This fact is known as Dirichlet's Theorem on Arithmetic Progressions, which had been conjectur...
#include<bits/stdc++.h> using namespace std; int main(){ int a,d,n,cnt; bool b; while(1){ cin>>a>>d>>n; if(a==0 && d==0 && n==0) break; cnt=0; while(cnt!=n){ b=true; if(a<2 || a%2==0) b=false; if(a==2) b=true; for(int i=3;i<=sqrt(a);i++){ if(a%i==0){ b=false; break; ...
The main land of Japan called Honshu is an island surrounded by the sea. In such an island, it is natural to ask a question: "Where is the most distant point from the sea?" The answer to this question for Honshu was found in 1996. The most distant point is located in former Usuda Town, Nagano Prefecture, whose distance...
#include <bits/stdc++.h> using namespace std; typedef complex<double> P; //Point typedef pair<P,P> L; //Line, Segment const double EPS = 1e-8; double dot(P a, P b){ return real(conj(a)*b); } double cross(P a, P b){ return imag(conj(a)*b); } int ccw(P a, P b, P c){ b -= a; c -= a; if(cross(b,c) > EPS) return 1; ...
Given n, find n consecutive positive integers. However, all numbers must have divisors other than 1 and the number itself. Hint In Sample Output 2, 8, 9 and 10 are selected as three consecutive integers. The second and third lines output 3, as a divisor of 9, and the fourth line outputs 5, as a divisor of 10. Inpu...
import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int num = sc.nextInt(); BigInteger big_num = BigInteger.valueOf(1); for(int i = 2; i <= num+1; i++){ big_num = big_num.multiply(BigInteger.valueOf(i));...
From 1603 to 1867, people call that era the EDO era. EDO stands for Enhanced Driving Operation, the most advanced space navigation technology at the time, and was developed by Dr. Izy in 1603. You are a space adventurer, flying around the universe and adventuring on various planets. During that adventure, you discover...
#coding: utf-8 if __name__ == '__main__': while True: n = int(input()) if n == 0: break flag = [] for i in range(21): flag.append([0 for j in range(21)]) for i in range(n): x,y = map(int,input().split()) flag[x][y] = 1; ...
This is a story in the epoch of magic. A clan of magicians lived in an artificial island built by magic power. One day, a crisis erupted on the island. An Empire ACM (Atlas Country of Magic) required unconditional surrender to them, otherwise an imperial force attacked by magical missiles to the island. However, they ...
#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...
A palidrome craftsperson starts to work in the early morning, with the clear air allowing him to polish up his palindromes. On this morning, he is making his pieces to submit to the International Contest for Palindrome Craftspeople. By the way, in order to make palindromes, he uses a special dictionary which contains...
#include<cstdio> #include<vector> #include<cstring> #include<string> #include<queue> #include<algorithm> using namespace std; int min(int a,unsigned int b){ return min(a,(int)b); } int min(unsigned int a,int b){ return min((int)a,b); } struct edge{ int to,cost; edge(){} edge(int a,int b):to(a),cost(b){} }; vec...
Trees are sometimes represented in the form of strings. Here is one of the most popular ways to represent unlabeled trees: * Leaves are represented by "()". * Other nodes (i.e. internal nodes) are represented by "( S1 S2 ... Sn )", where Si is the string representing the i-th subnode. For example, the tree depicted...
#include <bits/stdc++.h> using namespace std; string s; int c[100009]; int main() { cin >> s; int depth = 0; c[0] = 1; for(int i = 0; i < s.size(); i++) { if(s[i] == '(') depth++; if(s[i] == ')') depth--; c[depth]++; } long long ret = 0; for(int i = 0; i <= s.size(); i++) { ret += 1LL * c[i] * (c[i] - 1) ...
You have a board with height two and width W. The board is divided into 1x1 cells. Each row of the board is numbered 1 and 2 from top to bottom and each column is numbered 1 to W from left to right. We denote a cell at the i-th row in the j-th column by (i, j). Initially, some checkers are placed on some cells of the b...
#include <iostream> #include <cstdio> #include <cassert> #include <cstring> #include <vector> #include <valarray> #include <array> #include <queue> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include <complex> #include <random> #include <bitset>...
Example Input 2 1 2 Output 2
#include<bits/stdc++.h> using namespace std; int a[1007]; int main(void) { int n, i, j, tmp, maxi = -1, dig; bool flag; scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", &a[i]); for (i = 1; i < n; i++) { for (j = i+1; j <= n; j++) { tmp = a[i] * a[j]; flag = 1; dig = tmp % 10; while (1) { tmp...
C: Prayer (Pray) Some twins are famous for praying before the contest. There are four integers $ H, W, X, Y $, and it seems unlucky if $ H \ times W $ and $ x + y $ are both odd numbers. input Four integers $ H, W, X, Y $ are given, separated by spaces. output Output "No" if you are unlucky, or "Yes" if not. But ...
#include<bits/stdc++.h> using namespace std; #define lp(i,n) for(int i=0;i<n;i++) #define lps(i,j,n) for(int i=j;i<n;i++) #define fordebug int hoge;cin>>hoge; #define DEKAI 1000000007; #define INF (1<<28) #define int long long #define double long double #define floot10 cout<<fixed<<setprecision(10) signed main(){ ...
Problem There is a tree with $ N $ vertices. Each vertex is assigned a number from 1 to $ N $. Gacho and Kawabayashi decided to play a camp game using this tree. The game starts with Gacho and Kawabayashi at different vertices. Gacho repeatedly moves the vertices alternately, and the one who can not move first is the ...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct FastIO{ FastIO(){ cin.tie(0); ios::sync_with_stdio(0); } }fastio_beet; temp...
Find the convex hull of a given set of points P. In other words, find the smallest convex polygon containing all the points of P. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. Please note that you should find all the points of P on both corner and boundary of the convex polygon....
#include<algorithm> #include<iostream> #include<complex> #include<vector> using namespace std; #define x second #define y first #define M st.size() typedef complex<double> point; pair<int,int> a[100000]; vector<int> st; bool ccw(point a,point b,point c){ b-=a; c-=a; c*=conj(b); if(c.imag()<=0)return true; r...
Write a program which print coordinates $(x_i, y_i)$ of given $n$ points on the plane by the following criteria. 1. first by $x$-coordinate 2. in case of a tie, by $y$-coordinate Constraints * $1 \leq n \leq 100,000$ * $-1,000,000,000 \leq x_i, y_i \leq 1,000,000,000$ Input The input is given in the following form...
from sys import stdin n = int(stdin.readline()) l = [] for i in range(n): a,b = map(int,stdin.readline().split()) l.append([a,b]) l.sort() for i in range(n): print(f'{l[i][0]} {l[i][1]}')
Digory Kirke and Polly Plummer are two kids living next door to each other. The attics of the two houses are connected to each other through a passage. Digory's Uncle Andrew has been secretly doing strange things in the attic of his house, and he always ensures that the room is locked. Being curious, Digory suspects th...
test=int(raw_input()) while test: s=raw_input() days=0 count=0 maximum=0 for i in range(len(s)): if s[i] == '#': if count>maximum: days+=1 maximum=count count=0 else: count=0 else: cou...
Problem description. Liza wants to share her pizza among n friends, What are the minimum number of straight knife strokes required to cut the pizza into n pieces? Input The first line contains number of test cases T. The next T lines contain the input numbers N, the numbers of pieces required. Output For each tes...
from math import ceil from math import sqrt t=input() for _ in xrange(t): n=input() if n==1: print "0" else: ans=ceil((-1+sqrt(1+4*2*(n-1)))/2) print int(ans)
Write a program that takes in a letterclass ID of a ship and display the equivalent string class description of the given ID. Use the table below. Class ID Ship Class B or b BattleShip C or c Cruiser D or d Destroyer F or f Frigate Input The first line contains an integer T, total number of testcases. Then...
t=input() for i in range(t): dic={'b':'BattleShip','B':'BattleShip','c':'Cruiser','C':'Cruiser','d':'Destroyer','D':'Destroyer','f':'Frigate','F':'Frigate'} s=raw_input() print dic[s]
It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception. The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coordinates (0; 0) and he wants to go to cell with coordinates (n-1; m-1). From c...
#! /usr/bin/python MAX_M = 100000 def xdiff(i, j, matrix, isYflow): """ coming to i,j position in the matrix from x direction. isYflow states the direction of second last move considering this as last, 0 represents from left, 1 from top and -1 for the case when both are possible. Returns the additional affected ...
Polo, the Penguin, has a lot of tests tomorrow at the university. He knows that there are N different questions that will be on the tests. For each question i (i = 1..N), he knows C[i] - the number of tests that will contain this question, P[i] - the number of points that he will get for correctly answering this questi...
def knapsack(weights,values,maxw): n=len(weights) m=[] tmp=[] for i in xrange(0,maxw+1): tmp.append(0) m.append(tmp) for i in xrange(1,n): tmp=[] for j in xrange(0,maxw+1): if j<weights[i]: tmp.append(m[i-1][j]) else: tmp.append(max(m[i-1][j],m[i-1][j-weights[i]]+p[i])) m.appen...
Given an array of N numbers, a pair of numbers is called good if difference between the two numbers is strictly less than D. Find out maximum possible sum of all good disjoint pairs that can be made from these numbers. Sum of X pairs is the sum of all 2*X numbers in the pairs. Input First line contains T, the number o...
''' Created on 21-Jul-2015 @author: Venkatesh ''' def read_int_list(): return [int(x) for x in raw_input().split()] def read_int(): return int(raw_input()) def get_max_sum(nums, n, d): nums.sort(reverse=True) total, ind = 0, 0 while ind+1 < n: diff = nums[ind] - nums[ind+1] if...
Alice has a computer that operates on w-bit integers. The computer has n registers for values. The current content of the registers is given as an array a_1, a_2, …, a_n. The computer uses so-called "number gates" to manipulate this data. Each "number gate" takes two registers as inputs and calculates a function of t...
#include <bits/stdc++.h> using namespace std; const int N = 30005, M = 550005; using ll = long long; int w, n, m, pw[15], a[N]; ll cc[N], cnt[M]; char s[15]; int calc(int num) { int ret = 0; for (int i = 0; i < w; i++) if (num & (1 << i)) ret += pw[i]; return ret; } ll dfs(int dep, int cur) { if (dep == w +...
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from 1 to n, the junction 1 is called the root. A subtree of a junction v is a set of junc...
import java.io.*; import java.math.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.StringTokenizer; public class Main { static int MAXN=201; static int spf[] = new int[MAXN]; static int ans[]=new int[MAXN]; s...
Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time! More specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The mach...
#include <bits/stdc++.h> using namespace std; const long long mod = (1e+9) + 7; const long long size = 1e+5; void solve() { string s; s += "d0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0l0lrr" "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrru"; s += "ddddddd1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l1l...
You are given an n Γ— m table, consisting of characters Β«AΒ», Β«GΒ», Β«CΒ», Β«TΒ». Let's call a table nice, if every 2 Γ— 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of Β«AΒ», Β«GΒ», Β«CΒ», Β«TΒ»), that differs from the given table in the minimum number of characters. Input First...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 5; const char choice[6][2] = {{'A', 'C'}, {'A', 'G'}, {'A', 'T'}, {'C', 'G'}, {'C', 'T'}, {'G', 'T'}}; int n, m; string str[maxn]; int ord[2][maxn][6], cnt[2][maxn]; string out[maxn]; void print(int rc, int k) { for (int i...
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n Γ— m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target( \ "sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,popcnt,abm,mmx,avx,tune=native") using namespace std; const int MOD = 1000000007; const int UNDEF = -1; const int INF = 1 << 30; template <typename T> inline bool chkmax(T &aa, T bb) { return aa < ...
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order....
#include <bits/stdc++.h> using namespace std; int read() { int xx = 0, ff = 1; char ch = getchar(); while (ch > '9' || ch < '0') { if (ch == '-') ff = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { xx = xx * 10 + ch - '0'; ch = getchar(); } return xx * ff; } long long READ() { lo...
Toad Rash has a binary string s. A binary string consists only of zeros and ones. Let n be the length of s. Rash needs to find the number of such pairs of integers l, r that 1 ≀ l ≀ r ≀ n and there is at least one pair of integers x, k such that 1 ≀ x, k ≀ n, l ≀ x < x + 2k ≀ r, and s_x = s_{x+k} = s_{x+2k}. Find th...
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Has...
Vus the Cossack has a field with dimensions n Γ— m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way: 1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field...
#include <bits/stdc++.h> using namespace std; const int maxn = 1010; long long n, m, q, a[maxn][maxn], s[maxn][maxn], xa, ya, xb, yb; char ch; long long bitcnt(long long x) { long long ret = 0; while (x) { if (x & 1) ret++; x >>= 1; } return ret; } bool rev(long long x, long long y) { x--; y--; re...
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from ...
#include <bits/stdc++.h> const int N = 1054, M = N * 2; int n, E = 0, G, Gm = INT_MAX; int to[M], first[N], next[M]; int p[N], size[N]; int cnt = 0, nb[N]; int du[N]; std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq; inline void up(...
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
# import numpy as np import array def solution(): req = int(input()) for i in range(req): count = int(input()) result = 0 if count==2: print(2) continue while count % 2 != 0 : result+=1 count+=1 print(result) def coun...
This is a harder version of the problem. In this version, n ≀ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya beli...
#include <bits/stdc++.h> using namespace std; struct msp { int x, y, t; } ans; int n; int cntans(string& s) { int t = 0, f = 0, minm = 0x3f3f3f3f; for (int i = 0; i < s.length(); i += 1) { if (s[i] == '(') ++t; else --t; if (t < minm) minm = t, f = i; } ++f; s = s.substr(f, s.length(...
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls). When the ball is inserted the following happens repeatedly: if so...
#include <bits/stdc++.h> using namespace std; string inp; vector<char> diff; vector<int> cnt; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> inp; diff.push_back(inp[0]); cnt.push_back(1); for (int i = 1; i < inp.size(); i++) { if (inp[i] != inp[i - 1]) { diff.push_back...
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}. You have to choose two arrays a_i and a_j (1 ≀ i, j ≀ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ...
import java.util.*; import java.io.*; public class D { static long mod = 1000000007; public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); int[][] mat = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { mat[i]...
per nextum in unam tum XI conscribementis fac sic vestibulo perlegementum da varo. morde varo. seqis cumula varum. cis per nextum in unam tum XI conscribementis fac sic seqis decumulamenta da varo. varum privamentum fodementum da aresulto. ...
#include <bits/stdc++.h> using namespace std; std::mt19937 rnd( (int)std::chrono::steady_clock::now().time_since_epoch().count()); long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int N = 11; int a[N]; void run() { for (int i = (0); i < (N); ++i) scanf("%d", &a[i]); for (int ...
You are given two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.invoke.MethodHandles; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Objects; imp...
You are a warrior fighting against the machine god Thor. Thor challenge you to solve the following problem: There are n conveyors arranged in a line numbered with integers from 1 to n from left to right. Each conveyor has a symbol "<" or ">". The initial state of the conveyor i is equal to the i-th character of the s...
#include <bits/stdc++.h> using namespace std; inline int max(int a, int b, int c) { return max(a, max(b, c)); } struct Node { int l = 0, r = 0, ll = 0, lr = 0, rl = 0, rr = 0, hi = 0, lhi = 0, rhi = 0, nhi = 0, nlhi = 0, nrhi = 0; bool mark = false; } s[500005 * 4]; template <typename T> void read(T &x) { x...
Since Boboniu finished building his Jianghu, he has been doing Kungfu on these mountains every day. Boboniu designs a map for his n mountains. He uses n-1 roads to connect all n mountains. Every pair of mountains is connected via roads. For the i-th mountain, Boboniu estimated the tiredness of doing Kungfu on the to...
#include <bits/stdc++.h> using namespace std; using lint = long long; using pi = pair<lint, lint>; const lint inf = 1e12; const int MAXN = 500005; vector<int> gph[MAXN]; lint up[MAXN], dn[MAXN]; lint t[MAXN], h[MAXN]; void dfs(int x, int p) { vector<pi> v; lint tot = 0; lint sum = 0; for (auto &i : gph[x]) { ...
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases. A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase ha...
/* Written by Kabir Kanha Arora @kabirkanha */ import java.util.*; public class Main { public static void main(String[] args) { // Input Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- > 0) { long x = scanner.nextLong(); ...
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's. String s has exactly n/2 zeroes and n/2 ones (n is even). In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string. What is the minimum number of...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") long long int power(long long int x, long long int n) { long long int result = 1; while (n) { if (n % 2 == 1) result = result * x; n = n / 2; x = x * x; } return result;...
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers ...
#include <unordered_set> #include <unordered_map> #include <functional> #include <algorithm> #include <iterator> #include <assert.h> #include <iostream> #include <sstream> #include <fstream> #include <cstring> #include <cstdint> #include <cstdlib> #include <chrono> #include <random> #include <cstdio> #include <cctype> ...
n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight,...
tests = int(input()) for t in range(tests): n = int(input()) heroes = list(map(int, input().split(' '))) m = min(heroes) print(sum([1 for x in heroes if x > m]))
The popular improv website Interpretation Impetus hosts regular improv contests and maintains a rating of the best performers. However, since improv can often go horribly wrong, the website is notorious for declaring improv contests unrated. It now holds a wager before each improv contest where the participants try to ...
#include<bits/stdc++.h> using namespace std; int miss[1005]; int war[1005]; long long losuj(long long a) { long long res = 1; for(int x=1;x<=10;x++) res = (res*rand())%a+1; return res; } int main() { srand(time(NULL) + clock()); int a,t; cin>>a>>t; while(t--) { string d; ...
You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7...
# Author: Javier BΓ³rquez import os import sys import bisect def main(): fastReadInt = sys.stdin.buffer.readline def fastReadStr(): return sys.stdin.buffer.readline().decode('utf-8').strip() def fastWrite(ans): return sys.stdout.buffer.write(str(str(ans) + "\n").encode('utf-8')) def fastWriteList(ans): return ...
One remarkable day company "X" received k machines. And they were not simple machines, they were mechanical programmers! This was the last unsuccessful step before switching to android programmers, but that's another story. The company has now n tasks, for each of them we know the start time of its execution si, the d...
/* * Date: 5/10/12 * Time: 12:23 * Author: * Alexander Marchuk * aamarchuk@gmail.com */ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class AutoProgramming { static int N = 3000; public class ...
The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King. We know that only LCM(k2l + 1, k2l + 1 + 1, ..., k2r + 1) dwarves can see the Great Mushroom King. Numbers k, l, r are chosen by the Great Mushroom King himself in some complicated manner...
#include <bits/stdc++.h> using namespace std; long long calc(const long long &x, const long long &pow, const long long &pp) { long long res = 1, tmp = (x % pp); long long cur = pow; while (cur > 0) { if (cur % 2 == 0) { tmp = (tmp * tmp) % pp; cur = cur / 2; } else { res = (res * tmp) % ...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> long long n; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); std::cin >> n; if (n <= 50000) std::cout << "3\n", exit(0); if (n >= 54000) std::cout << "1\n", exit(0); std::cout << "2\n"; return 0; }
A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1, and also exists an ed...
from collections import defaultdict import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self...
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will ge...
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<long long> v(n); for (int i = 0; i < n; i++) { scanf("%I64d", &v[i]); } vector<char> ans(n); ans[n - 1] = '+'; long long now = v[n - 1]; for (int i = n - 2; i >= 0; i--) { if (v[i] >= now) { ans[i] ...
Consider integer sequence a1, a2, ..., an. You should run queries of two types: * The query format is "0 i val". In reply to this query you should make the following assignment: ai = val. * The query format is "1 l r k". In reply to this query you should print the maximum sum of at most k non-intersecting subsegm...
#include <bits/stdc++.h> using namespace std; inline int Get_Int() { int Num = 0, Flag = 1; char ch; do { ch = getchar(); if (ch == '-') Flag = -Flag; } while (ch < '0' || ch > '9'); do { Num = Num * 10 + ch - '0'; ch = getchar(); } while (ch >= '0' && ch <= '9'); return Num * Flag; } name...
You have been given n distinct integers a1, a2, ..., an. You can remove at most k of them. Find the minimum modular m (m > 0), so that for every pair of the remaining integers (ai, aj), the following unequality holds: <image>. Input The first line contains two integers n and k (1 ≀ n ≀ 5000, 0 ≀ k ≀ 4), which we have...
#include <bits/stdc++.h> using namespace std; int n, m, mmax, s[5005], f[1000005], smax; bool flag[1000005]; int comp(const void *a, const void *b) { return *(int *)a - *(int *)b; } int calcans(void) { int ans, i, j, same; for (ans = 1;; ans++) { for (i = ans, same = 0; i <= smax; i += ans) { same += f[i]...
A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is t...
#include <bits/stdc++.h> using namespace std; template <class T> void show(T a, int n) { for (int i = 0; i < n; ++i) cout << a[i] << ' '; cout << endl; } template <class T> void show(T a, int r, int l) { for (int i = 0; i < r; ++i) show(a[i], l); cout << endl; } const int N = 310; const int M = 5000; const int ...
Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjace...
#include <bits/stdc++.h> using namespace std; int n; int num[4000]; double memo[9000010]; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> num[i]; int cant = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (num[i] > num[j]) cant++; } } memo[0] = 0.0; memo[1] = ...
You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you. You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, e...
#include <bits/stdc++.h> using namespace std; const int N = 25; char buf[N][N]; const int K = 8; const int MSK = 1 << K; struct vt { int x, y; vt(int _x, int _y) { x = _x, y = _y; } vt() {} friend int operator^(vt a, vt b) { return a.x * b.y - b.x * a.y; } friend vt operator-(vt a, vt b) { return vt(a.x - b.x...
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vert...
#include <bits/stdc++.h> const int N = 300200; using namespace std; int n; int tim; int tin[N]; int tout[N]; int dep[N]; int mod = 1e9 + 7; pair<int, int> t[4 * N]; vector<int> v[N]; void dfs(int x, int g) { tin[x] = tout[x] = ++tim; dep[tin[x]] = g; for (auto y : v[x]) { dfs(y, g - 1); tout[x] = tout[y];...
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out...
name=raw_input() length=len(name) palin=True mirror=True for i in xrange((length)/2): if name[i]!=name[length-i-1]: palin=False break for char in name: if char not in ['A','H','I','M','O','T','U','V','W','X','Y']: mirror=False break if palin and mirror: print 'YES' else: ...
Today DZY begins to play an old game. In this game, he is in a big maze with n rooms connected by m corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly. DZY has got lost in the maze. Currently he is in the first room and has...
#include <bits/stdc++.h> using namespace std; const int N = 505, M = 105; int n, m, k, top; int a[N], id[N], e[N][N], deg[N]; double d[N][N], v[N * N], prob[N]; int x[N * N], y[N * N], type[N * N]; struct mat { double a[M][M]; mat() { memset(a, 0, sizeof(a)); } } tr, ans; mat operator*(mat a, mat b) { mat ans; ...
Little X has solved the #P-complete problem in polynomial time recently. So he gives this task to you. There is a special n Γ— n matrix A, you should calculate its permanent modulo 1000000007 (109 + 7). The special property of matrix A is almost all its elements equal to 1. Only k elements have specified value. You c...
#include <bits/stdc++.h> using namespace std; int get() { char ch; while (ch = getchar(), (ch < '0' || ch > '9') && ch != '-') ; if (ch == '-') { int s = 0; while (ch = getchar(), ch >= '0' && ch <= '9') s = s * 10 + ch - '0'; return -s; } int s = ch - '0'; while (ch = getchar(), ch >= '0' &...
Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Inpu...
#include <bits/stdc++.h> using namespace std; string mini(string a, string b) { if (a.size() < b.size()) return a; if (a.size() > b.size()) return b; for (int c = 0; c < (int)a.size(); c++) { if (a[c] < b[c]) return a; if (a[c] > b[c]) return b; } return a; } signed main() { ios::sync_with_stdio(fal...
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most...
#include <bits/stdc++.h> using namespace std; long long n, x; const long long MAXN = 222222; const long long mod = 1e9 + 7; long long a[MAXN], cnt[MAXN] = { 0, }, dp[120] = { 0, }; void preProcess() { dp[0] = 1; for (long long i = 1; i <= 100; i++) { for (long long j = 0; j <...
Ivan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time rang...
#include <bits/stdc++.h> using namespace std; int n, m; struct Pair { int id, v; Pair() { id = v = 0; } Pair(int a, int b) { id = a; v = b; } friend bool operator<(const Pair &a, const Pair &b) { return a.v < b.v; } friend bool operator>(const Pair &a, const Pair &b) { return a.v > b.v; } friend P...
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(Sys...
One day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, bu...
#include <bits/stdc++.h> using namespace std; const int N = 25; int dp[N][N][N][N][2][2][2], na, nb, nc; string a, b, c, A, B, C; void pros(string &x) { reverse(x.begin(), x.end()); x = ' ' + x; } struct col { int a, b, c; } value[N][N][N][N][2][2][2]; struct pack { int i, posa, posb, posc, carry, enda, endb; }...
Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes. As you may know, a New Year cake is a strictly convex polygon with n vertices. Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they ...
#include <bits/stdc++.h> using LL = long long; const int MOD = (int)1e9 + 7; const int N = 500000 + 5; int n; struct Point { LL x, y; Point() {} Point(LL _x, LL _y) : x(_x), y(_y) {} Point operator-(const Point &rhs) const { return Point(x - rhs.x, y - rhs.y); } Point operator*(LL t) const { return Poin...
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature ...
#include <bits/stdc++.h> using namespace std; const int INF = int(1e9); const long long INFll = 1ll * INF * INF; const long double ldINF = 1e+018; const long double EPS = 0.000000001; const int N = 100001; template <typename T> ostream& operator<<(ostream& out, pair<T, T>& a) { out << a.first << " " << a.second; re...
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; scanf("%d%d", &n, &m); int val = 1; for (int i = 0; i < n; i++) { if (val + 2 * n <= m) cout << val + 2 * n << " "; if (val <= m) cout << val << " "; if (val + 2 * n + 1 <= m) cout << val + 2 * n + 1 << " "; if (val + 1 <= m) c...
Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of n rows and m columns and q tasks. Each task is to swap two submatrices of the given matrix. For each task Vasiliy knows six integers ai, bi, ci, di, hi, wi, where ai is the index of the row where...
#include <bits/stdc++.h> using namespace std; int n, m, q, mp[2000001], R[2000001], D[2000001]; int main() { scanf("%d%d%d", &n, &m, &q); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &mp[(i) * (m + 1) + (j)]); } } for (int i = 0; i <= n; i++) { for (int j = 0; j <=...
Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving. More formally, first one of four diagonal directions is chosen and the billiard ball moves ...
#include <bits/stdc++.h> using namespace std; int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } int main() { int x, y; cin >> x >> y; cout << gcd(x - 1, y - 1) + 1 << endl; }
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class JavaApplication6 { static int[] problemvalues; static int[] solutions; static int[][] scores; static int[] delta; static int ans; public static...