input
stringlengths
29
13k
output
stringlengths
9
73.4k
Reca company makes monitors, the most popular of their models is AB999 with the screen size a × b centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio x: y became popular with users. That's why the company wants to reduce monitor AB999 size so th...
#------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w')...
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..." The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could h...
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); if (n == 0 && m != 0) System.out.println("Impossible"); else { int min = n + Math.max...
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
import java.util.Scanner; /** * * @author ZEZOmaster */ public class SystemofEquations { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int counter = 0; for (int i...
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression <image> means applying the o...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; const int mod = 1e9 + 9; int n, m; long long pot[maxn]; bool test() { long long p = 1; for (int i = 1; i <= m; ++i) { p *= 2LL; if (p > n) return true; } return false; } int main() { cin >> n >> m; if (!test()) { cout << 0 ...
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters. Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const int N = 55; double dp[N][N], fact[N]; int a[N]; int main() { int n; cin >> n; double factN = 1.0, ans = 0.0; dp[0][0] = 1.0; fact[0] = 1.0; for (int i = 1; i <= n; ++i) { cin >> a[i]; fact[i] = fact[i - 1] * i; } i...
A double tourist path, located at a park in Ultima Thule, is working by the following principle: * We introduce the Cartesian coordinate system. * At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second o...
#include <bits/stdc++.h> using namespace std; inline int get() { char c; while (!isdigit(c = getchar())) ; int v = c - 48; while (isdigit(c = getchar())) v = v * 10 + c - 48; return v; } int n, m, k, p, i, ll, lt, tt, o[400001], s[400001], v[400001]; map<int, int> Mp; struct Ar { int l; bool i; cons...
While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem: Given an integer sequence a1, a2, ..., an. You should run q queries of two types: 1. Given two integers l and r (1 ≤ l ≤ r...
#include <bits/stdc++.h> using namespace std; const int MOD = 95542721; const int MAX = 100005; int seg[4 * MAX][48], mark[4 * MAX], tmp[48], a[MAX]; int n, q; int next(int x) { return 1ll * x * x % MOD * x % MOD; } void fix(int& x) { while (x >= MOD) x -= MOD; while (x < 0) x += MOD; } void merge(int v) { for (i...
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three int...
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; const long long MAX_N = 100004; struct Point { Point(int _x = 0, int _y = 0) : x(_x), y(_y) {} int x, y; bool operator<(const Point t) const { return x < t.x || (x == t.x && y < t.y); } }; bool check(vector<Point>& data) { for...
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: * overall, there must be m dances; * exactly three people must take part in each dance; * eac...
#! /usr/bin/env python n, m = [int(x) for x in input().split()] dancers = {} for i in range(m): dance = [int (x) for x in input().split()] for j in range(3): if dance[j] not in dancers: dancers[dance[j]] = j else: dancers[dance[(j + 1) % 3]] = (dancers[dance[j]] + 1) % 3...
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current seq...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import javax.swing.text.Position; public class C381 { pu...
Inna is fed up with jokes about female logic. So she started using binary logic instead. Inna has an array of n elements a1[1], a1[2], ..., a1[n]. Girl likes to train in her binary logic, so she does an exercise consisting of n stages: on the first stage Inna writes out all numbers from array a1, on the i-th (i ≥ 2) s...
#include <bits/stdc++.h> const int maxn = 100050, maxb = 20; int n, m, d = 17, A[maxn]; long long ans = 0; int main() { int d0, i, j, p, v; scanf("%d%d", &n, &m); for (i = 1; i <= n; i++) scanf("%d", &A[i]); for (d0 = 0; d0 < d; d0++) for (i = 1; i <= n; i++) if ((A[i] >> d0) & 1) { for (j = 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; vector<vector<int> > G; vector<int> a, b, sol; void DFS(int node, int parent, bool even_times, bool odd_times, int level) { bool ok = false; if (level & 1) { if (odd_times) a[node] ^= 1; } else if (even_times) a[node] ^= 1; if (a[node] != b[node]) { sol....
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One ...
#include <bits/stdc++.h> using namespace std; struct node { int ind, type; long long cost; }; bool operator<(const node& a, const node& b) { if (a.cost != b.cost) return a.cost < b.cost; if (a.type != b.type) return a.type < b.type; return a.ind < b.ind; } set<node> S; node temp, cur; bool vis[100000]; vector...
One way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task. Let's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle. <image>(Picture from Wikipedia pag...
#include <bits/stdc++.h> using namespace std; int n, m; int a[40][40]; int b[40][40]; int ta[40][40], tb[40][40]; void flip() { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ta[j][i] = a[i][j]; tb[j][i] = b[i][j]; } } swap(n, m); for (int i = 0; i < n; i++) { for (int j = 0...
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table abcd edfg hijk ...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; public void solve() throws IOException { ...
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic...
#include <bits/stdc++.h> using namespace std; const int MOD = (int)1e9 + 7; const int MAX = 1e6; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long int n, mx = 0, po = 0; cin >> n; string s; cin >> s; map<int, int> mp; for (int i = 0; i < n; i++) { mp[s[i]]++; if (mp[s[i]...
What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears! In that country there is a rock band called CF consisting of n bears (including Mike) numbered from 1 to n. <image> ...
#include <bits/stdc++.h> using namespace std; inline int read() { int res = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -f; ch = getchar(); } while (isdigit(ch)) { res = (res << 3) + (res << 1) + ch - '0'; ch = getchar(); } return res * f; } namespace qiqi { co...
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are n warriors. Richelimakieu wants to choose three ...
#include <bits/stdc++.h> using namespace std; long long int graph[4005][4005]; vector<long long int> v[4005]; long long int n, m; int main() { scanf("%lld", &n); scanf("%lld", &m); long long int i, a, b, j, k; for (i = 0; i < m; i++) { scanf("%lld", &a); scanf("%lld", &b); graph[a][b] = 1; graph...
Edo has got a collection of n refrigerator magnets! He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be posit...
#include <bits/stdc++.h> using namespace std; struct node { int x, y; } p[100005]; bool cmp1(int a, int b) { return p[a].x < p[b].x; } bool cmp2(int a, int b) { return p[a].x > p[b].x; } bool cmp3(int a, int b) { return p[a].y < p[b].y; } bool cmp4(int a, int b) { return p[a].y > p[b].y; } int pos1[100005], pos2[1000...
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can...
# coding: utf-8 # In[8]: num = int(raw_input()) vals = list(map(int,raw_input().split())) result = 0 prev = None for i in range(num): if vals[i] == 1: if prev is None: result = 1 else: if result == 0: result = i-prev else: resul...
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ. As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as ...
#include <bits/stdc++.h> using namespace std; int f(char a[], char b[]) { int diff = 0; for (int i = 0; i < 6; ++i) diff += (a[i] != b[i]); return (int)ceil(diff / 2.0) - 1; } int main() { int n; scanf("%d", &n); char str[n][6]; for (int i = 0; i < n; ++i) scanf("%s", str[i]); int ans = 6; for (int i ...
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; long long int n = s.length(); long long int a[n]; a[0] = 1; for (long long int i = 1; i <= n - 1; i++) { a[i] = 1; if (s[i] == s[i - 1]) a[i] = a[i - 1] + 1; } for (long long int i = 0; i < n; i++) { if (a[i] == 0...
Little Petya was given this problem for homework: You are given function <image> (here <image> represents the operation of taking the remainder). His task is to count the number of integers x in range [a;b] with property f(x) = x. It is a pity that Petya forgot the order in which the remainders should be taken and wr...
// package CodeForces; import java.io.*; import java.util.*; public class Problem_68A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); int min=sc.nextInt(); for(int i=0;i<3;i++) min=Math.min(min, sc.nextInt()); int st...
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it ...
#include <bits/stdc++.h> using namespace std; int cas, cass; int n, m, lll, ans; long long aans; long long e[200014]; int to[200014]; int t[200014]; bool mark[200014]; long long mi(int x, int y) { long long sum = 1; while (y) { if (y & 1) sum = (sum * x) % 1000000007; x = (x * x) % 1000000007; y >>= 1; ...
Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m. About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On ...
#include <bits/stdc++.h> using namespace std; int n, m, d[int(1e5 + 5)], a[int(1e5 + 5)]; bool ok(int days) { vector<int> when(m + 1, 0x3f3f3f3f3f3f3f3fLL); for (int i = 1, __R = days; i <= __R; i++) if (d[i]) when[d[i]] = i; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair...
There are n types of coins in Byteland. Conveniently, the denomination of the coin type k divides the denomination of the coin type k + 1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types k + 1 and k equals ak. It is known that for each x there are at most 20 coin types...
#include <bits/stdc++.h> using namespace std; int IN() { int c, f, x; while (!isdigit(c = getchar()) && c != '-') ; c == '-' ? (f = 1, x = 0) : (f = 0, x = c - '0'); while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + c - '0'; return !f ? x : -x; } const int N = 300000 + 19; const int oo = (1 << 30) ...
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain ...
import math as mt import sys,string input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) def isSubseq(s,b,v): i=0 j=0 while(i<len(s) and j<len(b...
Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1 ≤ V ≤ 100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her frien...
#include <bits/stdc++.h> using namespace std; template <class T> inline T bigmod(T p, T e, T M) { long long ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } ...
The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study. Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory....
#include <bits/stdc++.h> using namespace std; const int N = 10050; int n; vector<int> a[N]; map<pair<int, int>, int> E; struct getAnswer { int x, y, id; double T; getAnswer(int x, int y, int id, double T) : x(x), y(y), id(id), T(T) {} }; vector<getAnswer> ans; void dfs(int v, int p = 0, double T = 0) { for (int...
In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop t...
#include <bits/stdc++.h> using namespace std; map<string, int> id; inline int getID(string s) { if (id.find(s) == id.end()) { int sz = id.size(); id[s] = sz; } return id[s]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, a, b, k, f; cin >> n >> a >> b >> k >> f; map<pair<int...
For each positive integer n consider the integer ψ(n) which is obtained from n by replacing every digit a in the decimal notation of n with the digit (9 - a). We say that ψ(n) is the reflection of n. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:16777216") using namespace std; template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); } const long double PI = 3.1415926535897932384626433832795; const long double EPS = 1e-9; long long l, r; long long mirr(l...
Vasya and Petya were tired of studying so they decided to play a game. Before the game begins Vasya looks at array a consisting of n integers. As soon as he remembers all elements of a the game begins. Vasya closes his eyes and Petya does q actions of one of two types: 1) Petya says 4 integers l1, r1, l2, r2 — boundar...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class _895E_3 { public static void main(String args[]) { FastScanner in = new FastScanner(); PrintWri...
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. <image> Thus, he came up with a puz...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; namespace Dup4 { inline int read() { int x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) f ^= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c - '0'); return x * (f ? 1 : -1); ...
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in ...
#include <bits/stdc++.h> int main() { int n, m, a, b, ans; ans = 3; scanf("%d%d%d%d", &n, &m, &a, &b); a--; b--; if (a % m == 0 || b % m == m - 1) ans = 2; if (a % m == ((b % m) + 1) % m) ans = 2; if (a % m == 0 && b % m == m - 1) ans = 1; if (ans > 1 && b == n - 1) { if (a % m == 0) ans = 1...
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them. The stones are located at integer distances from the banks. There are a_i ...
#include <bits/stdc++.h> using namespace std; int res = 1e9, n, k; int a[1000005]; int main() { cin >> n >> k; for (int i = 1; i < n; ++i) { cin >> a[i]; a[i] += a[i - 1]; if (i >= k) res = min(res, a[i] - a[i - k]); } cout << res; return 0; }
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant fo...
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 10; long long aft[N], a[N]; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); long long n, k; cin >> n >> k; long long ans = 0; for (long long i = 1; i <= n; ++i) { cin >> a[i]; } aft[n + 1] = n + 1; aft[n] = n; ...
Given a character C, print the ASCII value of that character. Input: First and only line in input contains a character C. Output: Print the ASCII value of the character C. Constraints: C ∈ ASCII characters SAMPLE INPUT b SAMPLE OUTPUT 98
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' k=raw_input() print ord(k)
Programmers generally love to play chess! You too have recently acquired an interest in playing chess and you find bishop to be the most fascinating warrior of all. During a random chess practice session, you are faced with this problem : "Two bishops are lying on the chessboard. You can move only one of them. What i...
def diagonal(x1, y1, x2, y2): if abs(x1 - x2) == abs(y1 - y2): return True return False def solve(): C = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 0], ...
Several drivers had lined up for the Drag Racing Competition at the Tokyo Drift Street. Dom had organized the competition, but he was not available during all the races and hence he did not know their results. In the drag race match, 2 drivers race against each other and one of them is the winner, and the loser gets el...
''' # Read input from stdin and provide input before running code ''' from collections import Counter name = int(raw_input('')) list=[] for line in range((2**name)-1): winner=raw_input('').split(' ')[0] list.append(winner) print(str(Counter(list).most_common(1)[0][0]))
The fight between Batman and Superman just got dirty. Superman tried to trick Batman and locked him inside an N x N grid. This gird is really special. It has values at each of its cell which is some positive integer. Superman gave Batman a serious headache inside the grid. He gave him an integer K and ordered him to t...
n,k= map( int, raw_input().split() ) a = [ [] for i in range(n+1) ] a[0] = [0 for i in range(n+1) ] for i in range(1,n+1): a[i] = [0] + map( int,raw_input().split() ) for i in range(1,n+1): for j in range(1,n+1): a[i][j] = a[i][j] + a[i-1][j] + a[i][j-1] - a[i-1][j-1] ans = 0 for i in range(k,n+1): for j in r...
Everyone who is involved with HackerEarth in what so ever form knows who Little Kuldeep is. He's not so little, but he's called that. (No one knows why!) He's pretty efficient at organizing, mentoring, managing various hiring challenges, contests happening on HackerEarth all the time. But age has caught up with him, fi...
def do_overlap(start_time1,end_time1,start_time2,end_time2): latest_start = max(start_time1, start_time2) earliest_end = min(end_time1, end_time2) return latest_start < earliest_end t=input() start_times=[] end_times=[] while t>0: t-=1 time_input=raw_input().split('-') a,b=time_input[0].split(':') start_time...
Recently you invented a brand-new definition of prime numbers. For a given set of positive integers S let's call X a prime if there are no elements in S which are divisors of X (except X itself). You are given a set S. Find elements in it which are prime numbers for this set. Input The first line contains one intege...
''' # 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!' #let my set of number is in a list s. s = [] prime_list = s output = [] item = raw_input() maxLengthList = int(item) item1 = raw_input() #item1 = input("") s = ite...
Recently Akash got this equation. Now being curious he wanted to know that for a given N , is it possible to find P1, P2, P3 and P4 for below equation under following conditions. ( P1-P2 ) + ( P3 - P4 ) = N P1, P2, P3, P4 are prime numbers P1 and P2 are consecutive Primes and P1 > P2 P3 and P4 are consecutive Primes ...
t=input() while t: t-=1 n = input() if n%2==0 and n>=4 and n<=308: print 'YES' else: print 'NO'
Betty had invited her friends over for breakfast. Being great at tongue twisters, Betty decides to have some fun with the others by making them repeat one of her tongue twisters while she made the sandwich. Betty bought a bit of butter, but the butter was too bitter So, Betty bought some better butter to make the bit...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t =int(raw_input()) while ( t > 0): t-=1 n,p = [int(i) for i in raw_input().split(' ')] while (n > 3 and p > 0) : n = n/2 + 1 if n%2 == 0 else n/2 +2 p = p-1 print n
Fatal Eagle has decided to do something to save his favorite city against the attack of Mr. XYZ, since no one else surprisingly seems bothered about it, and are just suffering through various attacks by various different creatures. Seeing Fatal Eagle's passion, N members of the Bangalore City decided to come forward ...
t=int(raw_input()) a=[[0 for x in range(201)] for x in range(201)] for n in range(1,200): a[n][n]=1 for k in range(n-1,0,-1): a[n][k]=a[n-k][k]+a[n][k+1] for ii in range(t): z=map(int,raw_input().strip().split(' ')) print a[z[0]][z[1]]
Before the Battle of Kamino the Confederacy of Independent Systems developed the a way to communicate with the far systems. This way is very unique as every word consists of exactly L lowercase letters. Also, there are exactly D words in this. Jedi order intercept these messages and built a dictionary out of it. Now t...
import sys L=map(str, sys.stdin.read().split()) l, D, N= int(L[0]), int(L[1]), int(L[2]) known=L[3: 3+D] L=L[3+D: ] for x in xrange(N): temp=[] for y in xrange(l): temp.append([]) flag=False ctr=0 for y in L[x]: if y=="(": flag=True elif y==")": flag=False ctr+=1 elif flag: tem...
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions: * A_i \neq B_i, for every i such that 1\leq i\leq N. * A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N...
''' 完全順列(derangement) モンモール数(Montmort number) ''' MOD = 10**9+7 N, M = map(int, input().split()) # 片方の順列の総数を求める ans = 1 for i in range(N): ans *= M-i ans %= MOD # M枚からN枚選ぶ完全順列を計算 d = [1, M-N] for i in range(2, N+1): # 1がk番目にある # 1番目にkがある t = (i-1)*d[-2] % MOD # 1番目にkがない t += (M-N+i-1)*d[-...
Takahashi has a string S consisting of lowercase English letters. Starting with this string, he will produce a new one in the procedure given as follows. The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following: * If T_i = 1: reverse the string S...
import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.Scanner; public class Main { void run() { Scanner sc = new Scanner(System.in); LinkedList<Character> l = new LinkedList<>(); boolean isR = false; String ...
Given is a string S. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different. Cons...
s = input() k = int(input()) m = 0 j = 0 if len(set(list(s))) == 1: print((len(s) * k) // 2) exit() for i in range(len(s)): if len(s) <= j + 1: a = m * k if s[0] == s[-1] == s[len(s) // 3]: print(a + k - 1) else: print(a) break if s[j] == s[j + 1]:...
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i. We will write a positive integer on each vertex in T and calculate our score as follows: * On each edge, write the smaller of the integers writ...
import java.io.*; import java.util.*; public class Main { static HashMap<Integer,Integer>[] g; //<toRoom, keyNecessary> static int n,m; static long mod = 1000000000+7; static HashSet<Integer>[] tree; static int[][] edge; static int[] c,res; public static void main(String[] args) throws Exc...
There is a grid 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. For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an empty square; if a...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int mx=1001,mod =1e9+7; ll dp[mx][mx]; int main() { int h,w; char ch; cin>>h>>w; dp[1][0]=1; for(int i=1; i<=h; i++) { for(int j=1; j<=w; j++) { cin>>ch; if(ch=='.') d...
Snuke has an integer sequence A of length N. He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen. Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the ma...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=(2e5)+10; int n; ll s[maxn],a[maxn],s1,s2,s3,s4,ans=1e18; int find(int l,int r,ll x) { while (l<r) { int mid=(l+r+1)/2; if (s[mid]<=x) l=mid; else r=mid-1; } return l; } int main() { //freopen("1.txt","r",stdin); scanf("%d",&n...
On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in `yyyy/mm/dd` format. For example, January 23, 2018 should be written as `2018/01/23`. After finishing the document, she noticed that she had mistakenly wrote `2017` at the beginning of the date col...
#include<iostream> using namespace std; int main(){ string s; cin>>s; cout<<"2018/01/"<<s[8]<<s[9]; }
You are given a three-digit positive integer N. Determine whether N is a palindromic number. Here, a palindromic number is an integer that reads the same backward as forward in decimal notation. Constraints * 100≤N≤999 * N is an integer. Input Input is given from Standard Input in the following format: N Output...
N = input() print('Yes' if N == N[-1::-1] else 'No')
We will call a non-negative integer increasing if, for any two adjacent digits in its decimal representation, the digit to the right is greater than or equal to the digit to the left. For example, 1558, 11, 3 and 0 are all increasing; 10 and 20170312 are not. Snuke has an integer N. Find the minimum number of increasi...
#include<bits/stdc++.h> const int N=5e5+5; char c[N]; int n,i,a[N],x; int main(){ *c='0';scanf("%s",c+1);for(i=1,n=strlen(c+1);i<=n;++i)a[i]=c[i]-c[i-1]; for(i=n;i;--i)if(a[i]<0)--a[i-1],a[i]+=10,++a[n]; for(;a[n]>10;)for(i=n;a[i]>=10 && a[n];--i)++a[i-1],a[i]-=10,a[n]--; for(i=n-1;i;--i)if(a[i]==10 && a[n])a[i]=0,...
This contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters. Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way. You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtai...
import re print("YNeos"[re.match(".*C.*F.*",input())==None::2])
Create a program that reads the attendance numbers of students in a class and the data that stores the ABO blood group and outputs the number of people for each blood type. There are four types of ABO blood types: A, B, AB, and O. Input A comma-separated pair of attendance numbers and blood types is given over mult...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str,strArray[]; int a=0,b=0,ab=0,o=0; while((str=br.read...
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and ...
rgb = set(["r","g","b"]) while 1: worm = raw_input() if worm == "0": break n = len(worm) L = 1 cnt = flag = 0 queset = set([worm]) while 1: que = list(queset) queset = set() for r in range(L): Worm = que.pop(0) if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != W...
At the pancake shop you work for, pancake dough is lined up in a row on an elongated iron plate and baked. Pancakes can be completed by turning them over with a spatula several times. How many times you turn it over to complete it depends on the pancake. Since the spatula is large, two adjacent pancakes will be turned...
#include<bits/stdc++.h> using namespace std; using ll = long long; using ull = unsigned long long; using V = vector<int>; using VV = vector<V>; using VVV = vector<VV>; using VL = vector<ll>; using VVL = vector<VL>; using VVVL = vector<VVL>; template<class T> using VE = vector<T>; template<class T> using P = pair<T, T>;...
Illumination Illuminations are displayed in the corridors every year at the JOI High School Cultural Festival. The illuminations consist of N light bulbs, which are lined up in a row from the west side to the east side of the corridor. Each light bulb is either on or off. A machine that operates a light bulb is sleep...
//============================================================================ // Name : AOJ.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostr...
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks. Counting upon you...
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <map> using namespace std; typedef pair<string,string> SP; struct Rule { int type; string a, b; }; const int type_permit = 0; const int type_deny = 1; int N, M; vector<Rule> rules; bool isMatch(const string &s, const string ...
In the year 2xxx, an expedition team landing on a planet found strange objects made by an ancient species living on that planet. They are transparent boxes containing opaque solid spheres (Figure 1). There are also many lithographs which seem to contain positions and radiuses of spheres. <image> Figure 1: A strange o...
#include<iostream> #include<complex> #include<algorithm> #include<vector> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) #define ALL(C) (C).begin(),(C).end() #define pb push_back #define mp make_pair const double eps = 1e-10; typedef complex<double> P; ...
Problem J String Puzzle Amazing Coding Magazine is popular among young programmers for its puzzle solving contests offering catchy digital gadgets as the prizes. The magazine for programmers naturally encourages the readers to solve the puzzles by writing programs. Let's give it a try! The puzzle in the latest issue ...
from bisect import bisect n, a, b, q = map(int, input().split()) W = [input().split() for i in range(a)] X = [int(x) for x, c in W] C = [c for x, c in W] P = [list(map(int, input().split())) for i in range(b)] Y = [y for y, h in P] + [n+1] D = [0]*b for i in range(b): y0, h = P[i]; y1 = Y[i+1] l = y1 - y0 ...
Deciphering Characters Image data which are left by a mysterious syndicate were discovered. You are requested to analyze the data. The syndicate members used characters invented independently. A binary image corresponds to one character written in black ink on white paper. Although you found many variant images that ...
#include <bits/stdc++.h> using namespace std; vector<vector<bool>> Input() { int h, w; cin >> h >> w; if (h == 0 && w == 0) return {}; vector<vector<bool>> image(h + 2, vector<bool>(w + 2, true)); for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) { char c; ci...
Scientist Frank, majoring in electrochemistry, has developed line-shaped strange electrodes called F-electrodes. During being activated, each F-electrode causes a special potential on and between the two lines touching the F-electrode’s endpoints at a right angle. Then electrically-charged particles located inside the ...
#include <bits/stdc++.h> #define REP(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; using namespace std; typedef complex<double> P; const double EPS = 1e-8; // 誤差を加味した符号判定 int sign(double a){ if(a > EPS) return +1; if(a < -EPS) return -1; return 0; } // 内積・外積 double dot(P a, P b){return real(c...
International Christmas Present Company (ICPC) is a company to employ Santa and deliver presents on Christmas. Many parents request ICPC to deliver presents to their children at specified time of December 24. Although same Santa can deliver two or more presents, because it takes time to move between houses, two or more...
#include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; const int INF = 1000000000; typedef vector< vector<int> > graph; graph g; vector<int> match; vector<bool> visit; bool search(int u){ if(u<0) return true; for(int i=0;i<g[u].size();i++){ int next = g[u][i]; if(v...
Now I have a card with n numbers on it. Consider arranging some or all of these appropriately to make numbers. Find the number obtained by adding all the numbers created at this time. For example, if you have 1 and 2, you will get 4 numbers 1, 2, 12, 21 so the total number is 36. Even if the same numbers are produced ...
#include<bits/stdc++.h> using namespace std; #define int long long typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define all(v) (v).begin(),(v).end() #define each(it,v) for(__typeof((v).begin()) it=(v)...
Problem Statement JAG Kingdom is a strange kingdom such that its $N$ cities are connected only by one-way roads. The $N$ cities are numbered $1$ through $N$. ICPC (International Characteristic Product Corporation) transports its products from the factory at the city $S$ to the storehouse at the city $T$ in JAG Kingdom...
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; typedef pair<int,...
Watching baseball The other day, your competitive programming companion, Mr. O, went out to watch a baseball game. The games I watched were a total of four games, Team X and Team Y, but it was a one-sided development, and Team X won all the games. Moreover, the total score of X in the four games was 33 points, while t...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...
Anti-aircraft shield In 3xxx, human beings who advanced to planets outside the solar system were troubled by the damage to the base caused by the arrival of a large number of meteorites. The International Cosmic Protection Company has developed a new anti-aircraft shield to solve this problem. The base to be protecte...
#include<bits/stdc++.h> using namespace std; using Int = long long; const Int OFS = 50000; const Int MAX = 1e6 + 2 * OFS; Int s[MAX],d[MAX],f[MAX]; Int u[MAX]; signed main(){ Int n,m; while(cin>>n>>m,n||m){ m--; vector<Int> a(m),x(m); for(Int i=0;i<m;i++) cin>>a[i]>>x[i]; memset(s,0,sizeof(s))...
Problem Great Demon King Megumi wants to defeat the $ N $ hero who lives on the ground. Megumi can cast explosion magic up to $ M $ times. Explosion magic is magic that extinguishes heroes who exist within a radius of $ r $ around arbitrary coordinates. The hero is very thin, so you don't have to consider the size. Al...
#include <bits/stdc++.h> using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; constexpr ll TEN(int n) { return (n==0) ? 1 : 10*TEN(n-1); } template<class T> using V = vector<T>; template<class T> using VV = V<V<T>>; using D = double; using P = complex<D>; const D PI =...
Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n. The Koch curve is well known as a kind of fractals. You can draw a Koch curve in the following algorithm: * Divide a given segment (p1, p2) into three equal segments. * Replace the middle segment by the two sides of...
import math def koch(d,x1,y1,x2,y2): if d == 0: return xs = (2*x1+x2)/3 ys = (2*y1+y2)/3 xt = (x1+2*x2)/3 yt = (y1+2*y2)/3 xu = (xt-xs)*math.cos(math.pi/3) - (yt-ys)*math.sin(math.pi/3) + xs yu = (xt-xs)*math.sin(math.pi/3) + (yt-ys)*math.cos(math.pi/3) + ys koch(d-1,x1,y1,x...
Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter. A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck. The deck of cards is represented by a string as follows. abcdeefab The first character and the last character co...
while 1: s = input() if s == "-": break for _ in range(int(input())): h = int(input()) s = s[h:] + s[:h] print(s)
Problem description John and Dave are two close friends. One day John bluffs to Dave that in past some weeks he has learnt to program using any programming languages. Dave started laughing wildly on John but John insisted that he can really do programming. Then Dave decided to test John programming skills by giving him...
t=input() for _ in xrange(t): n,x=raw_input().split() n=int(n) while n>0: x=eval(x+raw_input("")) x=str("{0:.2f}".format(x)) n-=1 print x
Ramesh is contemplating putting a new flooring throughout his house, but he has an important constraint: no tiles must be cut in the process of tiling any room. The floor of every room must be completely tiled, and all tiles in a particular room must be orientated the same way. This will make it easier for him to count...
t = int(raw_input()) for i in range(t): X, Y, x, y = map(int, raw_input().split()) room = X*Y tile = x*y if room%tile == 0: print "yes" else: print "no"
According to Gregorian Calendar, it was Monday on the date 01/01/2001. If any year is input, Write a program to display what is the day on the 1st January of this year. Input The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer year. Output Display th...
total_cases = int(raw_input()) def convert(a) : if a==0 : return 'sunday' elif a==1: return 'monday' elif a==2: return 'tuesday' elif a==3: return 'wednesday' elif a==4: return 'thursday' elif a==5: return 'friday' elif a==6: return 'saturday' while total_cases > 0: total_cases -= 1 day = 1 year...
In Conway's Game of Life, cells in a grid are used to simulate biological cells. Each cell is considered to be either alive or dead. At each step of the simulation each cell's current status and number of living neighbors is used to determine the status of the cell during the following step of the simulation. In this o...
#program for one dimensional game of life iteration = int(raw_input()) match = [[0,1],[3,2],[5,4],[6,7]] poss = [[0,3,5,6],[1,2,4,7]] for i in range(iteration): count = 0 row = raw_input() arr = poss[int(row[-1])] for el in arr: output = str(el % 2) current = el for j in range(len(row)): current = match[cu...
Little Red Riding Hood inherited an enormously large number of Candies from her father's Candy factory. Now she wants to divide these candies equally among her and her horse Hood. After the division, both Red and Hood get an equal, integral number of candies. Your task is to find out whether this is possible or not. ...
n=input() if str(n)[-1] in "02468": print "YES" else: print "NO"
Have you ever implemented a program adding two big integers that cannot be represented by the primitive data type of your programming language? The algorithm is just simulation of the column addition method that we have been taught in elementary school. Sometimes we forget the carry and the result is incorrect. In th...
t=int(raw_input()) for i in xrange(t): n=int(raw_input()) print (9*n -1 + 10.0**(-n))/18
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are...
import java.io.*; import java.util.*; public class Main { static Scanner in; static PrintWriter out; static Random rand = new Random(); static int gcd(int a, int b) { if(a%b==0) return b; return gcd (b, a%b); } public static void main(String args[]) throws IOException { out = new PrintWriter(Syste...
There are n cities in the Kingdom of Autumn, numbered from 1 to n. People can travel between any two cities using n-1 two-directional roads. This year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level 1. Each region of i-th level s...
#include <bits/stdc++.h> using namespace std; int n; int mod = 1e9 + 7; int fa[1000100]; long long s[1000100]; long long f[1000100], h[1000100]; long long gcd(long long a, long long b) { if (a % b == 0) return b; return gcd(b, a % b); } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%lld", &s...
You successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question. There are n crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without pa...
#include <bits/stdc++.h> using namespace std; const int CUTOFF = 550; int N, Q; vector<vector<int>> rides; bool consistent() { vector<int> location(N); vector<vector<pair<int, int>>> small_locations(N); for (int r = 0; r < Q; r++) if (rides[r].size() > CUTOFF) { fill(location.begin(), location.end(), -1...
Zeyad wants to commit n crimes in Egypt and not be punished at the end. There are several types of crimes. For example, bribery is a crime but is not considered such when repeated twice. Therefore, bribery is not considered a crime when repeated an even number of times. Speeding is a crime, but is not considered such w...
#include <bits/stdc++.h> using namespace std; const int mod = 12345; char A; long long n; vector<int> ok[30]; int pcnt = 0, m, ans = 0, maxn[30], x, c; struct Matrix { int a[125][125]; Matrix() { memset(a, 0, sizeof(a)); }; Matrix operator*(const Matrix &x) const { Matrix ans = Matrix(); for (int i = 1; i...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of...
#include <bits/stdc++.h> using namespace std; long long n, ans, cnt[(101 * 1000)], dp_down[(101 * 1000)], dp_up[(101 * 1000)]; vector<pair<long long, bool> > e[(101 * 1000)]; void dfs2(long long x, long long par = 0) { for (int i = 0; i < e[x].size(); i++) if (e[x][i].first != par) { if (e[x][i].second) ...
Suppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins. To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} … t_{k}. The i-th of these strings should be encode...
#include <bits/stdc++.h> using namespace std; signed main() { int n, a, b; cin >> n >> a >> b; string s; cin >> s; vector<int> dp(n + 1, INT_MAX); vector<vector<int> > lcp(n, vector<int>(n)); for (int i = n - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (s[i] == s[j]) { if (i ...
Carl has n coins of various colors, and he would like to sort them into piles. The coins are labeled 1,2,…,n, and each coin is exactly one of red, green, or blue. He would like to sort the coins into three different piles so one pile contains all red coins, one pile contains all green coins, and one pile contains all b...
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > o; vector<int> ans[100010], anss[5]; int pre[100010], nex[100010]; int flag; char st[100010]; int cnt; int tot; int id[100010]; int n; void print1() { if (o.size()) { printf("Q"); printf(" %d", (int)o.size()); for (pair<int, int> num : ...
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ...
n,a,x,b,y=map(int,input().split(" ")) flag =1 while a!=x and b!=y: a = a+ 1 b = b-1 if(a==n+1): a = 1 if(b==0): b=n if(a==b): flag =0 print('YES') break; if flag==1: print ('NO')
Vasya has an array a_1, a_2, ..., a_n. You don't know this array, but he told you m facts about this array. The i-th fact is a triple of numbers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n) and it means: * if t_i=1 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is sorted in non-decreasing order; * if t_i...
"""609C""" # import math # import sys def main(): n,m = map(int,input().split()) l = [] s = [] r = [] d = [0]*n for _ in range(m): a,b,c = map(int,input().split()) s.append(a) b-=1 l.append(b) c-=1 r.append(c) if a==1: d[b]+=1 d[c]-=1 dx = [-1]*(n-1) add = 0 for i in range(n): add+=d[i] ...
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract 1 from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to 1, in other wo...
import java.io.OutputStream; import java.util.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.io.BufferedWriter; import java.util.InputM...
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. ...
#include <bits/stdc++.h> using namespace std; int inline read() { int num = 0, neg = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') neg = -1; c = getchar(); } while (isdigit(c)) { num = (num << 3) + (num << 1) + c - '0'; c = getchar(); } return num * neg; } const int maxn = 500...
The only difference between easy and hard versions is constraints. There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ...
import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self....
Very soon, the new cell phone services provider "BerLine" will begin its work in Berland! The start of customer service is planned along the main street of the capital. There are n base stations that are already installed. They are located one after another along the main street in the order from the 1-st to the n-th ...
#include <bits/stdc++.h> using namespace std; int n; int p[8505]; int wh[8505]; int ans[8505]; int level[8505]; int nxt[9][8505]; int prv[9][8505]; pair<int, int> bros[9][8505]; int svd = 0, lsz, l; inline void go(int &f) { int id = f, t = 0; f = nxt[l][f]; if (wh[f] < wh[id]) id = f, t = 1; f = nxt[l][f]; if...
One day in the IT lesson Anna and Maria learned about the lexicographic order. String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The le...
#include <bits/stdc++.h> using namespace std; string s; struct compare { bool operator()(pair<int, int> a, pair<int, int> b) const { int l1 = a.second - a.first, l2 = b.second - b.first; if (l1 == l2) return s[a.second - 1] < s[b.second - 1]; if (l1 + 2 <= l2) return false; if (l2 + 2 <= l1) return tr...
Word s of length n is called k-complete if * s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 ≤ i ≤ n; * s has a period of k, i.e. s_i=s_{k+i} for all 1 ≤ i ≤ n-k. For example, "abaaba" is a 3-complete word, while "abccba" is not. Bob is given a word s of length n consisting of only lowercase Latin letters a...
#include <bits/stdc++.h> using namespace std; int main(void) { cin.tie(0); ios::sync_with_stdio(false); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; string S; cin >> S; int ans = 0; bool used[200010] = {}; for (int i = 0; i < n; i++) { if (used[i]) continue; ...
For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated. You are given three numbers: * n_0 — th...
for testcase in range(int(input())): n0, n1, n2 = map(int, input().split()) if n1 == 0: if n0: ans = "0" * (n0 + 1) else: ans = "1" * (n2 + 1) else: ans = ["0" * (n0 + 1), "1" * (n2 + 1)] for i in range(n1 - 1): ans.append(str(i & 1)) ...
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given n nonnegative integers a_1, a_2, ..., a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 ≤ i ≤ n, the elements a_{i - 1} and a_...
n = int(input()) a = [int(x) for x in input().split()] if n == 1: print(a[0]) exit() evens = [a[0]] odds = [a[1]] for i in range(2,n): if i % 2 == 0: evens.append(evens[-1]+a[i]) else: odds.append(odds[-1] + a[i]) # print(evens) # print(odds) maxi = 0 for i in range(len(evens)): score = evens[i] if i == 0: ...
Boboniu likes bit operations. He wants to play a game with you. Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m. For each i (1≤ i≤ n), you're asked to choose a j (1≤ j≤ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise...
from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) z=[] ma=0 for i in a: x=float("infinity") for j in b: x=min(i&j,x) ma=max(x,ma) for i i...
An agent called Cypher is decrypting a message, that contains a [composite number](https://en.wikipedia.org/wiki/Composite_number) n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle. In one move Cypher can choose two adjacent numbers in ...
#include <bits/stdc++.h> using namespace std; template <typename T> void cetak(T t) { cout << t << ')' << endl; } template <typename T, typename... V> void cetak(T t, V... v) { cout << t; if (sizeof...(v)) cout << ", "; cetak(v...); } typedef int (*func)(int, int); const int MOD = 1e9 + 7; int add(int x, int y)...
n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i. Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of sh...
#include <bits/stdc++.h> void init(); void solve(); int main() { init(); while (scanf("%*[ \t\n]*") != EOF) { solve(); } return 0; } const int MOD = 998244353; const int MaxN = 5001; int a[MaxN], n; long long dp[2][MaxN]; void init() {} void solve() { scanf("%d", &n); for (int i = 0; i < n; i++) { s...
Polycarp was given an array of a[1 ... n] of n integers. He can perform the following operation with the array a no more than n times: * Polycarp selects the index i and adds the value a_i to one of his choice of its neighbors. More formally, Polycarp adds the value of a_i to a_{i-1} or to a_{i+1} (if such a neighbo...
def check(sm): cur = 0 for i in range(n): cur += lis[i] if cur == sm: cur = 0 elif cur > sm: return False return cur == 0 t = int(input()) s = "" for i in range(t): n = int(input()) lis = [*map(int, input().split())] sm = sum(lis) ans = -1 for j in range(n, 0, -...