input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given a permutation p_1, p_2, ... , p_n (an array where each integer from 1 to n appears exactly once). The weight of the i-th element of this permutation is a_i. At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p_1, p_2, ... , ...
#include <bits/stdc++.h> using namespace std; using lld = long long int; using pii = pair<int, int>; using pll = pair<lld, lld>; using pli = pair<lld, int>; using pil = pair<int, lld>; int n, m; lld ms[2 * 262144]; lld mt[2 * 262144]; pii a[200009]; pii b[200009]; void update(int dep, int ql, int qr, int ll, int rr, in...
Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of p players playing in p different positions. She also recognizes the importance of audience support, so she wants to select k people as part of the audience. There are n people in Byteland. Alice needs ...
import java.util.*; import java.io.*; public class TeamBuilding { // https://codeforces.com/contest/1316/problem/E static int n, p, k; static A[] a; static long[][] s, memo; static int[] map; static long sum=0, INF = (long)(1e15); public static void main(String[] args) throws IOException, FileNotFoundExce...
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{...
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long sx = 0, sy = 0, mod = (long) (1e9 + 7); static ArrayList<Integer>[] a; static long[][][] dp; static long[] fa; static long[] farr; public static PrintWriter out; static ArrayList<pair> pa = new ArrayList<>(); ...
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to k. However, the voucher has a...
import java.io.*; import java.math.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { final static int MAXN ...
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≤ i < j < k ≤ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
def solve(arr): for i in range(1, len(arr)-1): if arr[i] > arr[i-1] and arr[i] > arr[i+1]: print("YES") print(i, i+1, i+2) return print("NO") for _ in range(int(input())): input() arr = [int(e) for e in input().split()] solve(arr)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
t = int(input()) for _ in range(t): n = int(input()) s = input() print(s[0::2])
In the Kingdom of Wakanda, the 2020 economic crisis has made a great impact on each city and its surrounding area. Cities have made a plan to build a fast train rail between them to boost the economy, but because of the insufficient funds, each city can only build a rail with one other city, and they want to do it toge...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using db = double; using str = string; using pi = pair<int, int>; using pl = pair<ll, ll>; using pd = pair<db, db>; using vi = vector<int>; using vb = vector<bool>; using vl = vector<ll>; using vd = vector<db>; using vs = vector...
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q). Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 7; template <typename A> ostream &operator<<(ostream &cout, vector<A> const &v); template <typename A, typename B> ostream &operator<<(ostream &cout, pair<A, B> const &p) { return cout << "(" << p.first << ", " << p.second << ")"; } template <typenam...
You want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side. Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal...
//Be Name Khoda #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define pb push_back #define pp pop_back #define all(x) x.begin(), x.end() #define pll pair< ll, ll > const ll mxn = 1e5 + 10; ll t, n, k, q; vector<ll> v, v2; void input() { v.clear(), v2.clear(); ...
You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in...
#include <bits/stdc++.h> using namespace std; using ll = long long; set<pair<int, int>> mp[26]; map<pair<int, int>, char> st; int main() { int n, m, ans[2] = {0}; cin >> n >> m; while(m--){ char x; cin >> x; if (x == '+') { int u, v; char c; c...
You are wandering in the explorer space of the 2050 Conference. The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1. At each step, y...
// Author : RegalBeast import java.io.*; import java.util.*; public class Main { static final FastReader FR = new FastReader(); static final PrintWriter PW = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { StringBuilder solution = new StringBuilder(); int r...
Cirno has prepared n arrays of length n each. Each array is a permutation of n integers from 1 to n. These arrays are special: for all 1 ≤ i ≤ n, if we take the i-th element of each array and form another array of length n with these elements, the resultant array is also a permutation of n integers from 1 to n. In the ...
#include <cstdio> #include <vector> #include <set> using namespace std; const int mod = 998244353; set<int> e[510][510]; int a[1010][510], d[1010][1010], u[1010]; vector<int> col[2], g[1010]; void dfs(int v, int b) { u[v] = -2; col[b].push_back(v); for (int i = 0; i < g[v].size(); i++) { int w = g[v][i]; if (u[w...
Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i ≥ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this val...
#include <bits/stdc++.h> using namespace std; int d[100100], a, b, m, r; int main() { cin >> a >> b >> m >> r; d[r] = 1; for (int i = 2;; i++) { r = (r * a + b) % m; if (d[r]) { cout << i - d[r] << endl; return 0; } d[r] = i; } }
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the...
import sys import math from heapq import *; input = sys.stdin.readline from functools import cmp_to_key; def pi(): return(int(input())) def pl(): return(int(input(), 16)) def ti(): return(list(map(int,input().split()))) def ts(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(i...
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff. The store will work seven days a week, but not around the clock. Every day at least k people must work in the store. Berland has a law that determines the order of working days and non-working...
#include <bits/stdc++.h> using namespace std; void solve() { long long int n, m, k; vector<long long int> v; cin >> n >> m >> k; if (k == 1) { for (long long int i = 1; i <= n + m; i += (n - 1)) v.push_back(i); } else { for (long long int i = 0; i < k; i++) v.push_back(1); for (long long int i = 2...
In 2N - 1 boxes there are apples and oranges. Your task is to choose N boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges. Input The first input line contains one number T — amount of tests. The description of each test starts with a natural number N — amou...
#include <bits/stdc++.h> using namespace std; struct box { int a; int o; int ind; }; vector<box> lst; bool compare(const box &a, const box &b) { return a.a < b.a; } int main() { int t, n; cin >> t; while (t--) { lst.clear(); cin >> n; long long sumo = 0, tsumo = 0; for (long long i = 0; i < ...
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially S...
import sys a = sys.stdin.readline().strip() b = sys.stdin.readline().strip() count = 1 for i in b: if i == a[count-1]: count += 1 if count > len(a): count = len(a) print count
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the ...
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { FastScanner in; PrintWriter out; public void solve() throws IOException { int result = 0; int n = in.nextInt(); int k = in.nextInt(); int[] array = new...
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the...
#include <bits/stdc++.h> using namespace std; long long n, k, a, c, sum; int j = 1; int main() { ios_base::sync_with_stdio(false); cin >> n >> k; c = n; for (int i = 1; i <= n; ++i) { cin >> a; if ((sum - (c - j) * (j - 1) * a) < k) { cout << i << '\n'; --c; } else { sum += a * (j ...
Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b...
#include <bits/stdc++.h> using namespace std; int n, ns[100100], cnt; int ble(int a) { while (a - (a & -a)) a -= a & -a; return a; } bool test(int v) { int a = -1; cnt = 0; for (int i = 0; i < n; ++i) if (ns[i] & (1 << v)) a &= ns[i], cnt++; return !(a % (1 << v)); } int main() { scanf("%d", &n); fo...
Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: 1. there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; 2. value r - l takes the maximum...
#include <bits/stdc++.h> using namespace std; int const N = 512312; int const INF = 1e9 + 7; int n, a[N], mn[35][N], gcd[35][N], numlog[N]; int gcd__(int a, int b) { return b ? gcd__(b, a % b) : a; } void build1() { numlog[1] = 0; for (int c = 2; c <= n; c++) { numlog[c] = numlog[c / 2] + 1; } for (int c = ...
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1. For example, sequences [1, 5], [10], [5...
#!/usr/bin/python from __future__ import division from sys import stdin, stdout, maxint import fractions, math, bisect N = int (stdin.readline ()) arr = map (int, stdin.readline ().split ()) if N == 1: print -1 else: arr.sort () mindiff = maxint for n in xrange (N - 1): mindiff = min (mindif...
You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum <image>, where function f(s) is determined as follows: * f(1) = 0; * Let's assume that p is the minimu...
#include <bits/stdc++.h> using namespace std; const int Maxn = 5005; const int Maxm = 100005; bool nprime[Maxm]; vector<int> pr; bool bad[Maxm]; set<int> B; int n, m; int a[Maxn]; int g[Maxn], best[Maxn]; int delt[Maxn]; int sum, bdelt; int gcd(int x, int y) { return x ? gcd(y % x, x) : y; } int main() { for (int i =...
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which ...
#include <bits/stdc++.h> using namespace std; const int N = 100001; int n; vector<int> g[N]; int a[N]; int b[N]; vector<int> ans; void dfs(int now, int fa, int depth, int k[2]) { a[now] ^= k[depth & 1]; if (a[now] != b[now]) { ans.push_back(now); k[depth & 1] ^= 1; } for (int i = 0; i < g[now].size(); +...
You are given a permutation of numbers from 1 to n. Determine whether there's a pair of integers a, b (1 ≤ a, b ≤ n; a ≠ b) such that the element <image> (note, that it is usual division, not integer one) is between a and b in this permutation. Input First line consists of a single integer n (1 ≤ n ≤ 300000) — the si...
#include <bits/stdc++.h> using namespace std; namespace zzc { const int maxn = 5e5 + 5; long long c[maxn], a[maxn], l[maxn], r[maxn]; long long t, n; long long lowbit(long long x) { return x & (-x); } void update(long long pos, long long k) { for (long long i = pos; i <= n; i += lowbit(i)) { c[i] += k; } } long...
Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n and gcd(al, al + 1, ..., ar) = xi. <image> is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi. ...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; final static String IO = "_std"; int gcd(int a, int b) { return b == 0 ? a : gcd(b, ...
It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of n songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on. The i-th...
#include <bits/stdc++.h> using namespace std; const int maxn = 5005; int n, T; int p[maxn], t[maxn]; double dp[maxn][maxn]; double pp, p1, tmp, ans; int main() { while (scanf("%d%d", &n, &T) != EOF) { for (int i = 1; i <= n; i++) scanf("%d%d", &p[i], &t[i]); memset(dp, 0, sizeof(dp)); dp[0][0] = 1; an...
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice ...
import java.io.*; import java.util.*; import java.lang.*; import java.math.BigInteger; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; public class Main { static StringTokenizer st=new StringTokenizer(""); static BufferedReader br; ////////////////////////...
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, s...
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream))...
Company "Robots industries" produces robots for territory protection. Robots protect triangle territories — right isosceles triangles with catheti parallel to North-South and East-West directions. Owner of some land buys and sets robots on his territory to protect it. From time to time, businessmen want to build offic...
#include <bits/stdc++.h> using namespace std; template <typename T> inline void maximize(T &a, T b) { if (b > a) a = b; } template <typename T> inline void minimize(T &a, T b) { if (b < a) a = b; } template <typename T> inline void xReplace(T v, T &mx, T &sx) { if (v > mx) sx = mx, mx = v; else if (v > sx) ...
Igor is in the museum and he wants to see as many pictures as possible. Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassa...
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf598d { public static void main(String[] args) throws IOException { int n = rni(), m = ni(), k = ni(), ans[][] = new int[n][m]; boolean map[][] = new boolean[n][m], visited[][] = ...
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer! Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher...
import itertools def remove_signs(s: str, signs: list) -> str: for i in range(len(signs)): s = s.replace(signs[i], '') return s def get_permulation_of_strings(s1, s2, s3): return list(map("".join, itertools.permutations([s1, s2, s3]))) def main(): signs = [';', '_', '-'] str1 = remove_si...
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict o...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); Person[] arr = new Person[n]; String type = ""; for (int i = 0; i < n; i++) { arr...
A famous sculptor Cicasso goes to a world tour! Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland. Cicasso is very devoted ...
#include <bits/stdc++.h> using namespace std; vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } void err(vector<string>::iterator it) {} template <typename T, typename... Args> void err(vector<string>:...
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of i...
#include <bits/stdc++.h> using namespace std; const int MAX = (int)1E5 + 10; int n, m; vector<int> e[MAX]; int d[MAX]; void dfs(int u, int p) { for (auto v : e[u]) if (v != p) { d[v] = d[u] + 1; dfs(v, u); } } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int x, y; ...
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya. Filya works a lot and he plans to visit ...
l1,r1,l2,r2,k=map(int,input().split()) ma=max(l1,l2) mi=min(r1,r2) if k<=mi and k>=ma: print(max(0,mi-ma)) else: print(max(0,mi-ma+1))
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead. The first task he faced is to check whether the king is in check. Anton doesn't know how to implement thi...
#include <bits/stdc++.h> using namespace std; char p[500005]; long long int px[500005], py[500005]; int main() { long long int x, y; int n; scanf("%d", &n); scanf("%lld %lld", &x, &y); for (int i = 0; i < n; i++) cin >> p[i] >> px[i] >> py[i]; int flag = 0; char pp; pp = 'X'; long long int dist, md = ...
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets...
n = input() k = input() digit = len(n) lst = [] def recul(k): if len(k)== 0: return if k[-digit:] < n: lst.append(k[-digit:]) if k[-digit:][0:1] == '0' and len(k[-digit:]) != 1: recul(k[:-digit]+'0') else: recul(k[:-digit]) else: temp = -digit+1 while k[temp:temp+1]== '0' and temp<0: temp +...
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who ...
import java.util.*; public class MainC { public static void main(String[]args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); ArrayList<Double>pr = new ArrayList<Double>(); double Q; for (int i = 0; i<T;i++){ double a = sc.nextInt(); doubl...
You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal. One matrix is lexicographically...
#include <bits/stdc++.h> const int MAXN = 110; int a[MAXN][MAXN]; void solve(int n, int pos, int k) { if (k == 1) { a[pos][pos] = 1; return; } if (k == 0) return; if (k <= (n << 1) - 1) { for (int i = pos; i <= pos + (k - 1 >> 1); i++) a[pos][i] = a[i][pos] = 1; solve(n - 1, pos + 1, (k & 1) ^ 1...
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written. Grigory couldn't understand for a long time what these letters remind him ...
#include <bits/stdc++.h> using namespace std; const int N = (1 << 20); const double pi = acos(-1); inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); ...
I won't feel lonely, nor will I be sorrowful... not before everything is buried. A string of n beads is left as the message of leaving. The beads are numbered from 1 to n from left to right, each having a shape numbered by integers between 1 and n inclusive. Some beads may have the same shapes. The memory of a shape ...
#include <bits/stdc++.h> using namespace std; struct fenwick_tree_1D { long long n, log_n; vector<long long> tree; fenwick_tree_1D(long long _n) : n(_n), log_n((long long)(log2(_n) + 1.0L)), tree(_n + 5) {} void update(long long x, long long v) { while (x <= n) { tree[x] += v; x += x & (-x...
This is an interactive problem. Jury has hidden a permutation p of integers from 0 to n - 1. You know only the length n. Remind that in permutation all integers are distinct. Let b be the inverse permutation for p, i.e. pbi = i for all i. The only thing you can do is to ask xor of elements pi and bj, printing two ind...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const double eps = 1e-12; const int MOD = 1e9 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int maxn = 5e3 + 4; const int maxm = 1e3 + 4; inline long long rule(long long x) { return (x %= MOD) += x < 0 ? MOD :...
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles. I...
#include <bits/stdc++.h> using namespace std; inline void timer(void) { int t = clock(); cout << (float(t)) / CLOCKS_PER_SEC; } int main() { int n, a, b, x, y, x_ = 0; cin >> n >> x >> y; if (!(y % x)) if (!(n % x)) return !(cout << "YES" << endl << n / x << ' ' << 0); else return !(cout <...
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied. The classroom contains n rows of seats ...
'''input 1 10 1 .......... ''' n,m,k = map(int,raw_input().split()) arr = [] for i in range(n): tmp = list(raw_input().strip()) arr.append(tmp) ans = 0 for i in range(n): cnt = 0 tmp = [] for j in range(m): if arr[i][j] == '.': cnt += 1 else: if cnt >= k: tmp.append(cnt) cnt = 0 if cnt >= k: tm...
You have two variables a and b. Consider the following sequence of actions performed with these variables: 1. If a = 0 or b = 0, end the process. Otherwise, go to step 2; 2. If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; 3. If b ≥ 2·a, then set the value of b to b - 2...
a, b = map(int, input().split()) while a != 0 and b != 0: if a >= 2 * b: a = a % (2 * b) elif b >= 2 * a: b = b % (2 * a) else: print(a, b) exit(0) print(a, b)
Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance ...
#include <bits/stdc++.h> using namespace std; long long dp[1111][1111][2]; const long long mod = 1000000007; int lim, len; char s[1111]; long long getdp(int l, int less, int last, int ok) { if (l == -1) return ok; long long &ret = dp[l][last][ok]; if (!less && ret != -1) return ret; long long res = 0; int u; ...
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a wa...
#include <bits/stdc++.h> using namespace std; int x[78], y[78]; set<int> mp[400005]; int delta = 200000; int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { scanf("%d", x + i); } for (int i = 1; i <= m; i++) { scanf("%d", y + i); } set<int> st; for (int i = 1; i <= n; i...
A boy named Mohan was very fond of integer arrays and loved performing various operations on them. Once he decided to calculate a unique value of the array, which he named as Babua value. To find that value, he calculates the absolute difference between all consecutive elements in an array and adds it to the first ele...
def gcd(a,b): if (a%b==0): return b return gcd(b,a%b) z=input() a=map(int,raw_input().split()) a=sorted(a) ans=0 for x in a: ans+=x #for x in a: # for y in a: # ans+=abs(x-y) start=0 aa=0 count=0 for x in a: aa+=2*(count*x-start) start+=x count+=1 ans+=aa num=ans den=z g=gcd(num,den) num,den=num/g,den...
"Too close Yet too far" It is well known that our chotu is chotu (Height-wise :P). On Hug day his short height is creating problems for him as most of the girls are taller than him so he can't hug them properly. To overcome the problem he has decided that he shall hug the girl whose height is closest to him. Given th...
import math t = int(raw_input()) while t>0: a = raw_input().split(' ') a = [int(x) for x in a if x!=''] b = raw_input().split(' ') b = [int(x) for x in b if x!=''] for i in range(0, len(b)): b[i]=abs(b[i]-a[1]) b.sort() print b[0] t=t-1
Sorry folks,, admin has no time to create a story for this problem... You have two integers n and m and you have to print value of factorial(n)%m. OUTPUT a single integer containing answer of problem. Input 23 14567 NOTE You do not need to create a program for this problem you have to write your answers of given in...
from math import factorial a,b=map(int,raw_input().split()) j=factorial(a) p=j%b print p
Hanuman has been a great admirer of Ram. However, there is one thing that Hanuman finds really difficult when talking to Ram. Hanuman can only understand sentences in reverse order but Ram,though an incarnation of God,is somehow unable to speak in reverse. Help Ram by creating a program that will generate the sentence(...
noOfSentences = int(raw_input()) def reverseString(s): strings = s.split(" ") strings = strings[::-1] return ' '.join(strings) for caseNo in range(1, noOfSentences + 1): print reverseString(raw_input())
There was girl named Julia in their neighbourhood. Both of them liked her and were trying to impress her. Now that Tim and Bob are done with daddy’s game. Julia thought that Tim solved the game on his own and was deeply impressed. After few days, Julia and Tim realised they fell in love with each other. They started ta...
for i in range(input()): k=input() st=[] s=raw_input() for j in range(len(s)): l=ord(s[j])-k if l<ord('A'): l=l+26 st.append(chr(l)) print "".join(st)
Solve the mystery. Input: String which consists of words(all the characters of any word are lower case letters) and punctuation marks(consists of {'.' , ',' , '?' , '!'}). Also every input string consists of one '*' in it. It is guaranteed that strings doesn't start or end with space(' ') and only one answer exists f...
N=input(); for k in range(0,N): st=raw_input() str="" ct=0; for i in range(0,len(st)): if(st[i].isalnum()==1)or st[i]=='*': str=str+st[i]; #print str ct=len(str)-1; c="" for i in range(0,len(str)): if(str[i]=='*'): c=str[ct]; break; ...
Julia has a sack full of red and yellow balls and wants to arrange them in a particular order as defined below. Let us consider two definitions - Chroma-regularity - maximum number of objects of the same color that appear consecutively. Min-Arrangement - An arrangement of the objects with minimum Chroma Regularit...
''' # 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!' r=input() s=input() m=min(r,s) n=max(r,s) if m==n or s==1: print "1" else: while m>0: n=n/2+1 m-=1 print n
Bob gives you a list of N strings and a task to solve. The task is to remove all the duplicate strings from the list and print the resulting list of strings in a sorted order. Input: The first line contains an integer N. Then next N lines contain a string Si. Output: Print the sorted list. Constraints: 1 ≤ |N| ≤ ...
n=input() a=set() for i in range(n): str=raw_input() a.add(str) for i in sorted(a): print i
Mr. Osama is a maths enthusiast. Numbers and equations never fails to amaze him. Recently he started exploring a weird problem. The explanation of the problem he is working on, is given below. He takes the equation, ax1+bx2+cx3+.... = 1, for some integers x1,x2,x3,... He likes to analyze the properties of this equation...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' from fractions import gcd t=input() while t>0: t-=1 n=input() l=[int(i) for i in raw_input().split()] if reduce(gcd,l)==1: print "YES" else: print"NO"
Rohan is programmer. He designed a game called X-Game. In this game, there are N number of soldiers, represented in terms of their powers. The algorithm of this game arranges all soldiers in all possible different groups. Every group will fight among the soldiers of the same group and after the fight ends, the remain...
mod = 10**9+7 for _ in xrange(input()): n = input() lst = map(int, raw_input().split()) ans = 0 for i in lst: ans |= i print (((2**(n-1)) % mod) * (ans % mod)) % mod
Given are an integer K and integers a_1,\dots, a_K. Determine whether a sequence P satisfying below exists. If it exists, find the lexicographically smallest such sequence. * Every term in P is an integer between 1 and K (inclusive). * For each i=1,\dots, K, P contains a_i occurrences of i. * For each term in P, there...
#include<iostream> #include<cstdio> #include<vector> #include<algorithm> using namespace std; const int K=105,N=1005; int k,n; int a[K]; vector<int>merge(const vector<int>&a,const vector<int>&b) { vector<int>res; size_t i=0,j=0; while(i<a.size()&&j<b.size()) { if(a[i]<b[j]) res.push_back(a[i]),i++; else res.pus...
Akari has n kinds of flowers, one of each kind. She is going to choose one or more of these flowers to make a bouquet. However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b. How many different bouquets are there that Akari can make? Find the count modulo (10^9 + 7). Here,...
#include <bits/stdc++.h> using namespace std; #define ll long long #define ar array const int M=1e9+7; int n, a, b; ll iv[200001]; ll nck(int n, int k) { ll ans=1; for(int i=1; i<=k; ++i) ans=ans*(n-i+1)%M*iv[i]%M; return ans; } ll powM(ll b, int p) { ll r=1; for(; p; b=b*b%M, p/=2) if(p&1) r=r*b%M; ret...
We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied: * For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers ar...
#include <bits/stdc++.h> using namespace std; int main() { int n, m, a, b; scanf("%d%d%d%d", &n, &m, &a, &b); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if ((i <= b && j <= a) || (i > b && j > a)) putchar('1'); else putchar('0'); } putchar('\n'); } return 0; }
You have N cards. On the i-th card, an integer A_i is written. For each j = 1, 2, ..., M in this order, you will perform the following operation once: Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j. Find the maximum possible sum of the integers written o...
N,M=map(int,input().split()) L=[(1,a) for a in map(int,input().split())] for _ in range(M): L.append(tuple(map(int,input().split()))) L=sorted(L,key=lambda x: x[1],reverse=True) ans,k=0,0 for n,a in L: if n+k>=N: ans+=a*(N-k) break else: ans+=a*n k+=n print(ans)
Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`. Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7: * For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, a...
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter ...
Decades have passed since the beginning of AtCoder Beginner Contest. The contests are labeled as `ABC001`, `ABC002`, ... from the first round, but after the 999-th round `ABC999`, a problem occurred: how the future rounds should be labeled? In the end, the labels for the rounds from the 1000-th to the 1998-th are dec...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a; a = scan.nextInt(); if(a <= 999) System.out.println("ABC"); else System.out.println("ABD"); } }
You are given a string S consisting of lowercase English letters. Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations. Constraints * 1 \leq |S| \leq 2 × 10^5 * S consists of lowercase Englis...
#include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #define LL long long using namespace std; char s[200010]; int n,last[30],pos[200010],tr[200010],num[30]; void change(int k,int c) {for(int i=k;i<=n;i+=i&-i) tr[i]+=c;} int get(int k) {int ans=0;for(int i=k;i>=1;i-=i&-i) ans+=tr[i];return ans;} bool...
We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. * Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element...
#include<iostream> using namespace std; int main(){ int i,l; long long m,K,a[50]; cin >> K; l = K%50; m = K/50; cout << 50 << endl; if(K<=50){ for(i=0;i<K;i++){ a[i] = 50; } for(i=K;i<50;i++){ a[i] = 0; } }else{ for(i=0;i<l;i++){ a[i] = m+50; } for(i=l;i<50;i++){ a[i] = 49 - l + m ; } } for(i=0;i<50;...
You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels. A pixel is the smallest element of an image, and in this problem it is a square of size 1×1. Also, the given images are binary images, and the color of each pixel is either white or bl...
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) using namespace std; typedef long long ll; typedef pair <double,double> P; int main() { int n,m; cin>>n>>m; string a[55],b[55]; rep(i,n) cin>>a[i]; rep(i,m) cin>>b[i]; rep(i,n) { rep(j,n) { if (i+m-1>n-1) continue; if (...
On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers. There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and...
#!/usr/bin/env python3 import sys try: from typing import Any, Union, List, Tuple, Dict except ImportError: pass sys.setrecursionlimit(10**6) def debug(*args): print(*args, file=sys.stderr) def exit(): sys.exit(0) W, H = map(int, input().split()) p = [] for i in range(W): p.append(int(input())) q = [] for j in ra...
The time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct ans...
def get_input(): while True: try: yield ''.join(input()) except EOFError: break teams = [0 for i in range(101)] points = [False for i in range(31)] while True: a,b = [int(i) for i in input().split(",")] if a == 0 and b == 0: break teams[a] = b points...
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking de...
#include <cstdio> #include <vector> #include <queue> #include <algorithm> #include <cstring> #include <functional> using namespace std; struct data{ int t,id,id_park,type; data(){} data(int tt,int ii,int dd,int ttt){ t=tt; id=ii; id_park=dd; type=ttt; } bool operator<(const data &d1)const{ if(t==d1.t){ ...
Nobuo-kun and Shizuo-kun are playing a game of competing for territories on a rectangular island. As shown in Fig. 1 below, the entire island is made up of square compartments divided in a grid pattern, and the profits and losses resulting from these are indicated by integers. <image> In this game, move one piece t...
#include <bits/stdc++.h> #define FOR(i, a, b) for (int i = a; i <= (int) b; ++i) #define ii pair <int, int> using namespace std; const int N = 1e3 + 3; int m, n, a[N][N], f[N][N][2], vis[N][N][2]; void init() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("main.inp","r",stdin); ...
problem N students from JOI High School are lined up in a row from east to west. The i-th student from the western end of the column is student i. Each student has a bib with one integer. Initially, the integer Ai is written on the number of student i. There are M batons, and the batons are numbered from 1 to M. For ...
#include<iostream> #include<string> #include<algorithm> #include<cmath> using namespace std; int main(void) { int n, m, a; cin >> n >> m; int test[101] = { 0 }; for (int h = 0; h < n; h++) { cin >> a; test[h] = a; } for (int h = 1; h <= m; h++) { for (int i = 0; i < n; i++) { if (i != n - 1 && test[i] %...
Your job is to find out the secret number hidden in a matrix, each of whose element is a digit ('0'-'9') or a letter ('A'-'Z'). You can see an example matrix in Figure 1. <image> Figure 1: A Matrix The secret number and other non-secret ones are coded in a matrix as sequences of digits in a decimal format. You shoul...
#include "bits/stdc++.h" using namespace std; inline int comp(string& s, string &t) { if (s.size() < t.size()) return 1; if (s.size() > t.size()) return 0; for (int i = 0; i < s.size(); i++) { if (s[i] < t[i]) return 1; if (s[i] > t[i]) return 0; } return 0; } void solve(void) { int w, h; while(cin >> w ...
After counting so many stars in the sky in his childhood, Isaac, now an astronomer and a mathematician, uses a big astronomical telescope and lets his image processing program count stars. The hardest part of the program is to judge if a shining object in the sky is really a star. As a mathematician, the only way he kn...
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <stack> #include <utility> #include <complex> #include <vector> #define loop(i,a,b) for(int i=(a);i<int(b);i++) #define rep(i,b) loop(i,0,b) using namespace std; const double EPS = 1e-8; const double INF = 1e12; typedef complex<double...
Sixth Sense Ms. Future is gifted with precognition. Naturally, she is excellent at some card games since she can correctly foresee every player's actions, except her own. Today, she accepted a challenge from a reckless gambler Mr. Past. They agreed to play a simple two-player trick-taking card game. Cards for the gam...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define NUM 10005 int N; int P[5005],F[5005]; vector<int> V; int P_table[NUM],F_table[NUM]; int P_TMP...
Origami, or the art of folding paper Master Grus is a famous origami (paper folding) artist, who is enthusiastic about exploring the possibility of origami art. For future creation, he is now planning fundamental experiments to establish the general theory of origami. One rectangular piece of paper is used in each of...
#include <iostream> #include <string> #include <cstdlib> #include <cmath> #include <vector> #include <unordered_map> #include <map> #include <set> #include <algorithm> #include <queue> #include <stack> #include <functional> #include <bitset> #include <assert.h> #include <unordered_map> #include <fstream> #include <ctim...
You are hired by the ∀I¶אΞ℘, an extraterrestrial intelligence, as a programmer of their typesetting system. Your task today is to design an algorithm for text justification. Text justification is to equalize the line widths as much as possible by inserting line breaks at appropriate posi- tions, given a word sequence ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define MAX 1024 #define INF LLONG_MAX/4 ll N, W; ll memo[MAX]; vector<ll> a; ll solve(int n) { if (n == N) return 0; ll &res = memo[n]; if (res != -1) return res; res = INF; ll sum = 0; for (int i = n; i < N; i++) { ...
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 practice is to improve the ability to read messages hidden from sentences by searching for palindromes in strings. There may be many palindromes, so I'd like to count the number w...
#include <cstdio> #include <iostream> #include <queue> #include <set> using namespace std; template<typename C, typename C::value_type low, typename C::value_type high> class PalindromeTree{ const static int m = high - low + 1; typedef typename C::value_type T; struct node{ int next[m]; int len; in...
You are playing a solitaire puzzle called "Connect", which uses several letter tiles. There are R × C empty cells. For each i (1 ≤ i ≤ R), you must put a string si (1 ≤ |si| ≤ C) in the i-th row of the table, without changing the letter order. In other words, you choose an integer sequence {aj} such that 1 ≤ a1 < a2 <...
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; const int MAX_R = 128; const int MAX_C = 16+1; const int BIT = 1<<MAX_C; int r, c; string s[MAX_R]; int dp[2][BIT]; int main() { while(1) { if(cin >> r >> c) ; else break; for(int i = 0; i < r; ++i) cin >> s[i...
One day, Ikta, an elementary school student, received a piece of paper with mathematical formulas from his grandfather. Apparently, the grandfather will give you as much money as the answer to the formula. Ikta has only learned addition, subtraction, and multiplication, so only addition, subtraction, and multiplication...
#include <bits/stdc++.h> using namespace std; namespace { typedef long long Long; template<class T> ostream& operator<<(ostream& os, const vector<T>& vs) { if (vs.empty()) return os << "[]"; os << "[" << vs[0]; for (int i = 1; i < vs.size(); i++) os << "," << vs[i]; return os...
F: Miko Mi String- story Mikko Mikkomi ~! Everyone's idol, Miko Miko Tazawa! Today ~, with Mikoto ~, practice the string algorithm, let's do it ☆ Miko's special ~~ character making ~~ The slogan "MikoMikomi" becomes "MikoMikoMi" in Roman letters! In other words, if A = “Mi” and B = “Ko”, you can write in the form of...
#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; st...
problem One day, Sosusa, who loves prime numbers, was playing with the pair $ (p, q) $, where $ p + q $ is a prime number. Suddenly, Sosusa wondered how many of these pairs were prime numbers with $ p $ and $ q $ both less than or equal to $ N $. Find the number on your behalf. output Output the number of pairs. A...
#include <bits/stdc++.h> using namespace std; /* bool isPrime(int x) { test++; if(x < 2) return false; if(x == 2) return true; if(x % 2 == 0) return false; for(int i = 3; i * i <= x; i += 2) { if(x % i == 0) return false; } return true; } */ vector<bool> prime(1e7 + 1, true); void make_prime() { pri...
Problem You were asked by a company to create a program. The company has $ N $ jobs, and each job is numbered from $ 1 $ to $ N $. There are $ M_i $ prerequisite jobs $ X_ {i, j} $ in job $ i $, and work $ X_ {i, j} $ is performed before job $ X_ {i, j} $. And work $ i $ suffers a great loss. So ask you to find the n...
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <complex> #include <string> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <functional> #include <cas...
Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print t...
import java.util.Scanner; public class Main { final boolean DEBUG = false; class Node { int key; Node p, l, r; Node(int key) { this.key = key; } void insert(Node z) { Node y = null; Node x = this; while (x != null) { y = x; if (z.key < x.key) x = x.l; else x = x.r; } z.p ...
For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations: * push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$. * randomAccess($p$): Print element $a_p$. * pop($d$): Delete the first element of $A$, if $d = ...
from collections import deque class shinajina(): def push(A,que): if que[1]==0: A.appendleft(que[2]) elif que[1]==1: A.append(que[2]) def randomaccess(A,que): print(A[que[1]]) def pop(A,que): if que[1]==0: A.popleft() elif que[1]==1...
Problem Description Two mathematicians Mr.X and Mr.Y are discussing about a problem. Mr.X says that the ans is a and Mr.Y says the ans is b(where a and b being string containing 0's and 1's). After arguing for a long time they find that Mr.X was giving the answer in binary code where as Mr.Y was giving the answer in Gr...
for _ in range(input()): s=raw_input() g='' g+=s[0] for i in range(1,len(s)): g+=str(int(s[i-1])^int(s[i])) print g
Today, Chef woke up to find that he had no clean socks. Doing laundry is such a turn-off for Chef, that in such a situation, he always buys new socks instead of cleaning the old dirty ones. He arrived at the fashion store with money rupees in his pocket and started looking for socks. Everything looked good, but then Ch...
jacketCost, sockCost, money = map(int,raw_input().split()) if((money-jacketCost)//sockCost)%2==0: print('Lucky Chef') else: print('Unlucky Chef')
The palindrome is a string that can be read the same way from left to right and from right to left. For example, strings "aaaaa", "1221", "bbaabb" are palindromes, however the string "chef" is not a palindrome because if we read it from right to left, we will obtain "fehc" that is not the same as "chef". We call a str...
T = int(raw_input()) for i in range(T): N = int(raw_input()) if N%2 == 0: print N else: print N-1
Today, as usual, Jerry comes up with a new puzzle for Tom. Jerry knows very well that Tom is well aware of the concepts of fibonacci series. So he intends to present the problem with a twist. By choosing any random integer Jerry asks Tom to tell whether the given number is a fibonacci number.   Input The first line o...
a = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,1771128657,46368,75025, 121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169, 63245986,102334155,165580141,267914296,433494437,701408733] t = int(raw_input()) while t: t-=1 n = long(raw...
John wanted to buy gifts for some k children in his apartments on christmas. He goes to the shop and the shopkeeper shows him n gifts. How many ways John can choose k gifts from n total gifts ?. Since answer could be large print the answer mod 1000000007 NOTE : ordering of the gifts do not matter Different order of sa...
def C(n, r): if(n<r): return 0 if(r==0): return 1 if(r==1): return n if(r>n/2): return C(n, n-r) else: res = 1 for i in xrange(0, r): res*=(n-i) res/=(i+1) return res%1000000007 li=list() for _ in xrange(int(raw_input()...
All bandits are afraid of Sheriff. Sheriff constantly fights crime, but when bandits lay low, he gets bored and starts to entertain himself. This time Sheriff gathered all the bandits in his garden and ordered them to line up. After the whistle all bandits should change the order in which they stand. Sheriff gave all...
def gcd(a, b): """ Compute the GCD of 2 numbers. """ while b: a, b = b, a % b return a def _lcm(a, b): """ Compute the LCM of 2 numbers. """ return (a * b) / gcd(a, b) def lcm(*args): """ Compute the LCM of arbitrary amount of numbers. """ return reduce(_lcm, args) def garden_game(): # Get the number...
You are given a text consisting of n space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. w_i is the i-th word of text. All words consist ...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int INF = 1e9; const int N = 300 + 5; map<string, int> Map; int id[N], w[N], a[N], p[N]; void getNext(int a[], int n) { p[0] = -1; int j = -1; for (int i = 1; i < n; i++) { while (j != -1 && a[j + 1] != a[i]) j = p[j]; if (a[j + ...
The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknow...
#include <bits/stdc++.h> using namespace std; const int B = 1e7 + 10; int mndv[B], prm[B], nprm; int mdv[60][2], gdv[60], ndv; long long phidv[60]; int Ndv; long long m, x; inline long long Mul(long long a, long long b, long long mod) { a %= mod, b %= mod; long long z = (long double)a / mod * b; long long res = (...
After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency. These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of t...
import java.util.Scanner; public class Main { private static Scanner in = new Scanner(System.in); public static void main(String[] args) { int n = in.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } long ans = 0; ...
Polycarp has a lot of work to do. Recently he has learned a new time management rule: "if a task takes five minutes or less, do it immediately". Polycarp likes the new rule, however he is not sure that five minutes is the optimal value. He supposes that this value d should be chosen based on existing task list. Polyca...
#include <bits/stdc++.h> using namespace std; struct node { long long sum; int cnt; node *ptl, *ptr; node() { sum = cnt = 0; ptl = ptr = NULL; } void build(int l, int r) { sum = cnt = 0; if (l == r) return; int mid = (l + r) >> 1; if (ptl == NULL) ptl = new node(); ptl->build(l, ...
You are given two integers n and k. Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minim...
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (b == 0) return a; a %= b; return gcd(b, a); } bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) { return (a.second < b.second); } int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int mi...
The tic-tac-toe game is starting on a tree of n vertices. Some vertices are already colored in white while the remaining are uncolored. There are two players — white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it in...
#include <bits/stdc++.h> using namespace std; vector<int> adjList[2000000]; int main() { int i, j; int T, t; int n, u, v; char c; scanf("%d", &T); for (t = 0; t < T; t++) { scanf("%d", &n); for (i = 0; i < n - 1; i++) { scanf("%d %d", &u, &v); u--, v--; adjList[u].push_back(v); ...
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
n=int(input()) print((n*(n+1)*(n+2))//3-2-n*(n+1))
Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≤ i, j ≤ n the inequality k ⋅ |i - j| ≤ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension....
#include <bits/stdc++.h> using namespace std; long long diff[10000006]; long long same[10000006]; long long fastexpo(long long x, long long n) { if (n == 0) return 1; long long temp = fastexpo(x, n / 2) % 1000000007; if (n & 1) return (temp * temp * x) % 1000000007; return (temp * temp) % 1000000007; } int main...
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte...
n = int(input()) s = input() mid = n//2; ans = int(s) for i in range(mid, 0, -1): if s[i] != '0': val = int(s[:i]) + int(s[i:]) ans = min(ans, val) break for i in range(mid+1, n): if s[i] != '0': val = int(s[:i]) + int(s[i:]) ans = min(ans, val) break print(ans...