input
stringlengths
29
13k
output
stringlengths
9
73.4k
You have to paint with shades of grey the tiles of an nΓ— n wall. The wall has n rows of tiles, each with n tiles. The tiles on the boundary of the wall (i.e., on the first row, last row, first column and last column) are already painted and you shall not change their color. All the other tiles are not painted. Some of...
#include <bits/stdc++.h> using namespace std; using LL = long long; const int MAX_N = 1e5 + 5; struct Graph { int to, cap, cost, next; } e[MAX_N * 50]; int fir[MAX_N], e_cnt; void clearGraph() { memset(fir, -1, sizeof(fir)); e_cnt = 0; } void Add_Edge(int u, int v, int c, int w) { e[e_cnt] = (Graph){v, c, w, fi...
Please pay attention to the unusual memory limit in this problem. In a parallel universe, Satan is called "Trygub". For that reason, the letters of his namesake were deleted from the alphabet in ancient times. The government has n workers standing in a row and numbered with integers from 1 to n from left to right. Th...
#include <bits/stdc++.h> using namespace std; #define N 100100 int id[300], x[N], fst[30], lst[30], cnt[30]; int n, a, b; bool dp[1<<20]; char ch[30], s[N]; inline bool good(int y) { int l = n, r = 0, tot = 0; for (int i = 0; i < 20; i ++) if (y >> i & 1) { if (cnt[i]) { tot += cnt[i];...
Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation p of length n. Scientists found out, that to overcome an obstacle, the robot should make p an identity permutation (make p_i = i for all i). Unfortunately, scientists can't control the robot. Thus the only way to make p ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int n; cin >> n; vector<pair<int, int>> v; ll ans = 0; vector<int> a(n); iota(a.begin(), a.end(), 1); for (int i = 1; i + 1 < n; i++) { if (i < n / 2) v.emplace_back(i, n - 1); else v.emplace_back(i, 0); } v.e...
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at tha...
#include <bits/stdc++.h> using namespace std; int main() { int n, x, a, b; vector<int> v; vector<int> v2; cin >> n >> x; for (int i = 0; i < n; i++) { cin >> a >> b; if (a < b) { v.push_back(a); v2.push_back(b); } else { v.push_back(b); v2.push_back(a); } } sort(v.b...
<image> William owns a flat in central London. He decided to rent his flat out for the next n days to earn some money. Since his flat is in the center of the city, he instantly got m offers in the form (l_i, r_i), which means that someone wants to book the flat from day l_i until day r_i inclusive. To avoid spending ...
/* KAMUI! β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–“β–’β–’β–‘β–’β–’β–’β–’β–’β–‘β–‘β–‘β–’β–’β–’β–“β–“β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–ˆβ–“β–’β–’β–’β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–’β–’β–‘β–’β–’β–’β–“β–ˆβ–ˆβ–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–ˆβ–ˆβ–’β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–‘β–’β–’β–’β–’β–“β–ˆβ–ˆβ–“β–“β–“β–“ β–“β–“β–“β–ˆβ–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–’β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–’β–ˆβ–ˆβ–ˆβ–’β–‘β–‘β–’β–’β–’β–ˆβ–ˆβ–“β–“β–“ β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“ ...
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string s and cut out som...
#include <bits/stdc++.h> using namespace std; int main() { string a, b; cin >> a >> b; int k = 0; string star = "*"; for (int i = 0; i < 12; i++) star = star + star; a = star + a + star; int res = 3000; for (int i = 0; i < a.size(); i++) { int u = 0; for (int j = 0; j < b.size(); j++) if (...
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet. The Smart Beaver is going to bring som...
#include <bits/stdc++.h> using namespace std; const int MaxN = 10005; int a[MaxN], b[MaxN]; int N, C; long long sol(long long d, long long C) { long long ret = 0; for (int i = 0; i < N; i++) { ret += a[i] * d / b[i]; if (ret > C) return C + 1; } return ret; } long long getA(long long C) { long long L ...
A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine. Let us remind you that a ring is a region located between two...
#include <bits/stdc++.h> using namespace std; int fib[1000]; inline int sqr(int x) { return x * x; } int main() { int x1, y1, r1, R1; int x2, y2, r2, R2; scanf("%d%d%d%d", &x1, &y1, &r1, &R1); scanf("%d%d%d%d", &x2, &y2, &r2, &R2); double d = sqr(x1 - x2) + sqr(y1 - y2); int ret = 0; { if (sqr(r1 + R2...
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that t...
#include <bits/stdc++.h> using namespace std; const int N = (int)1e7; int n, m, a[200000], b[200000], pn, p[N]; bool u[N + 2]; vector<int> e[664600], g[664600]; int main() { p[pn++] = 2; for (int i = 3; i < N; i += 2) if (!u[i]) { p[pn++] = i; if (1LL * i * i > N) continue; for (int j = i * i;...
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of ...
n=int(raw_input()) if n==1 or n==2: print -1 else: a=[] for i in range(2,n+1): a.append(i) a.append(1) for i in a: print i,
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a...
#include <bits/stdc++.h> using namespace std; bool comp(int a, int b) { return (a < b); } int main() { long long int s = 100010; bool a[s]; memset(a, true, s); a[1] = false; for (int i = 2; i * i < s; i++) { if (a[i]) { for (int j = i + i; j < s; j += i) a[j] = false; } } long long int m, n;...
Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of nΒ·m square tiles forming a n Γ— m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color. Shaass wants ...
#include <bits/stdc++.h> using namespace std; int n, m, s, t, x, y; long long ans; set<pair<int, int> > st; int rd() { char c; while (c = getchar(), c < 'A') ; return c; } int main() { scanf("%d%d%d%d", &m, &n, &t, &s); y = (rd() == 'D') ? 1 : -1, x = (rd() == 'R') ? 1 : -1; ans = 1; for (int i = 1; i...
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style. Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of cons...
from functools import reduce from operator import * from math import * from sys import * from string import * from collections import * setrecursionlimit(10**7) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] RI=lambda: list(map(int,input().split())) RS=lambda: input().rstrip().split() #####################...
Xenia the vigorous detective faced n (n β‰₯ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the ...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, s, f; cin >> n >> m >> s >> f; map<long long int, pair<long long int, long long int> > hash; int i; long long int mx = INT_MIN; for (i = 0; i < m; i++) { long long int x, y, z; c...
John Doe has recently found a "Free Market" in his city β€” that is the place where you can exchange some of your possessions for other things for free. John knows that his city has n items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that eac...
#include <bits/stdc++.h> using namespace std; int n, d; int dp[1130000]; int main() { scanf("%d %d", &n, &d); int s = 0; dp[0] = 1; for (int i = 0; i < n; i++) { int ci; scanf("%d", &ci); s += ci; for (int v = s; v >= ci; v--) { dp[v] |= dp[v - ci]; } } int lla = -1e9; int la = 0...
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl...
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; const long long INF = 1e18; int main() { double n, i, k, m = 101; cin >> n; vector<long long> a(n, 0); vector<double> b(101, 0); for (i = 0; i < (n); i++) { cin >> a[i]; b[a[i]]++; } double x = 0, y = 0; for (i = 0; ...
Input The input contains a single integer a (1 ≀ a ≀ 64). Output Output a single integer. Examples Input 2 Output 1 Input 4 Output 2 Input 27 Output 5 Input 42 Output 6
i = [0, 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267, 1, 4, 1, 5, 1, 4, 1, 50, 1, 2, 3, 4, 1, 6, 1, 52, 15, 2, 1, 15, 1, 2, 1, 12, 1, 10, 1, 4, 2 ] print(i[input()...
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct. Fortunately the child knows how to solve such complicated test. The chi...
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.StringTokenizer; public...
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, havi...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:20000000") int n; char s[200005]; int a[200005]; bool v[200005]; int l[200005], r[200005]; priority_queue<pair<int, pair<int, int> > > q; vector<pair<int, int> > res; int main() { scanf("%d\n", &n); gets(s); for (int i = 0; i < (n); ++i...
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that su...
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); OutputWriter out = new OutputWriter(outputStream); ...
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha...
#include <bits/stdc++.h> using namespace std; int n, m, ans, x, y, nrIN[100005]; vector<int> v[100005], N, ord[100005]; unordered_set<long long> S; bool viz[100005], viz2[100005]; long long to_ll(int x, int y) { return 1LL * x * 1e6 + y; } void dfs(int nod) { N.push_back(nod); viz[nod] = 1; for (auto it : v[nod])...
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≀ n ≀ 106). The second line contains a sequence o...
#include <bits/stdc++.h> using namespace std; int arr[4]; int main() { int n, a; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a); arr[a]++; } return printf("%d\n", n - max(max(arr[1], arr[2]), arr[3])), 0; }
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom. A bar of chocolate can be presented as an n Γ— n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are ...
#include <bits/stdc++.h> using namespace std; struct SegmentMaxTree { SegmentMaxTree(int default_value, int n) : default_value(default_value) { sz = 1; while (sz < n) { sz = sz << 1; } items.resize(2 * sz - 1, default_value); } void Set(int first, int last, int value) { return Set(first,...
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all...
n = int(input()) hs = list(map(int, input().split())) maxx = 0 ans = [] for h in reversed(hs): if h > maxx: ans.append(0) else: ans.append(maxx-h+1) maxx = max(maxx, h) print(' '.join(map(str, reversed(ans))))
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiadβ€”'1' for a correctly identified cow and '0' otherwise. However, all is not...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; ...
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder. Let's denote a flip operation of an integer as follows: number is considered...
var str = readline(); var len = str.length; function work(type, beg, end) { var arr = new Array(len); for (var i = 0; i < len; ++i) { arr[i] = Number(str[i]); } var ans = new Array(len); var down = false; while (true) { if (beg > end) { if (type === 1 && !down || ty...
There is a social website with n fanpages, numbered 1 through n. There are also n companies, and the i-th company owns the i-th fanpage. Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow. The website doesn’t allow a situation where i follows j and a...
#include <bits/stdc++.h> using namespace std; int Q, N, M, K, L; long long FAN[100001]; int p[100001]; long long v[100001]; struct comp { bool operator()(const int& a, const int& b) const { if (v[a] != v[b]) return v[a] < v[b]; return a < b; } }; set<int, comp> children[100001]; int deg[100001]; multiset<lo...
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dista...
import sys def main(arr): curr = None m = float("inf") for d, pos in arr: if d == 'L': if curr is not None: m = min(m, pos - curr) elif d == 'R': curr = pos print(m // 2 if m != float("inf") else -1) if __name__ == "__main__": arr = [] fo...
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood. Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights ...
import java.util.Scanner; public class P071C { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); int n = inScanner.nextInt(); int[] moods = new int[n]; for (int i = 0; i < n; i++) { moods[i] = inScanner.nextInt(); } for...
Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1 Γ— 1 Γ— 1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row. Sometimes Alyona chooses some segment towers, and put on the top of each tower several cub...
#include <bits/stdc++.h> using namespace std; struct four { int a, b, c, d; four(int a_ = 0, int b_ = 0, int c_ = 0, int d_ = 0) { a = a_; b = b_; c = c_; d = d_; } int f() { return d - a; } }; bool operator<(const four& f, const four& g) { return (f.a < g.a); } int n, m; vector<long long> a, b,...
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at ...
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as...
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class App { public static PrintWriter out; static int s = Integer.MIN_VALUE; public static void main(String[] args) {...
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help. Form...
import java.util.*; public class C{ final int MOD = (int)1e9 + 7; long get(int x, int y, int lim){ if (Math.min(x,y) < 0) return 0L; long[][][][] d = new long[32][2][2][2], sm = new long[32][2][2][2]; d[31][1][1][1] = 1; for (int w = 30; w >= 0; w--) for (int a = 0; a < 2; a++) for (int b = 0; b < ...
<image> Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of carame...
#include <bits/stdc++.h> using namespace std; int func(int A[], char ch) { switch (ch) { case 'v': { A[0] = 1; return 0; break; } case '<': { A[1] = 1; return 1; break; } case '^': { A[2] = 1; return 2; break; } case '>': { A[3] =...
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for...
import java.util.*; import java.text.*; import javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; void solve() throws Exception { int n=...
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner. For each of the p...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, k; cin >> n >> k; long long int p[n], mx = 0; std::vector<long long int> v; for (int i = 0; i < n; i++) { cin >> p[i]; v.push_back(p[i]); if (p[i] > mx) mx = p[i]; } for (int i = 0; i < n; i++) { int cmp = 1; i...
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way: <image> This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o...
class polynomial: def __init__(self, data): self.data = data def __lshift__(self, x): return polynomial([0] * x + self.data) def __len__(self): return len(self.data) def __sub__(self, other): newData = [y - x for y, x in zip(self.data, other.data + [0] * 10...
We call a positive integer x a k-beautiful integer if and only if it is possible to split the multiset of its digits in the decimal representation into two subsets such that the difference between the sum of digits in one subset and the sum of digits in the other subset is less than or equal to k. Each digit should bel...
#include <bits/stdc++.h> using namespace std; void upd(long long &x, long long y) { x += y; } struct node { int nxt; long long sta, v[10]; node() { nxt = 0; memset(v, 0, sizeof(v)); } }; struct state { vector<node> nodes; int head[100007]; state() { memset(head, -1, sizeof(head)); } size_t size(...
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an...
#include <bits/stdc++.h> using namespace std; int n; char s[200]; int ucnt, rcnt; int main() { scanf("%d", &n); getchar(); gets(s); int ans = strlen(s); for (int i = 0; i < n - 1; i++) { if ((s[i] == 'U' && s[i + 1] == 'R') || (s[i] == 'R' && s[i + 1] == 'U')) i++, ans--; } cout << ans << endl; ...
After a revolution in Berland the new dictator faced an unexpected challenge: the country has to be somehow ruled. The dictator is a very efficient manager, yet he can't personally give orders to each and every citizen. That's why he decided to pick some set of leaders he would control. Those leaders will directly orde...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000; int n, m; unordered_set<int> g[MAXN]; int color[MAXN]; int low[MAXN]; int depth[MAXN]; stack<pair<int, int> > edge_stack; vector<pair<int, int> > edges_to_remove; int COMP_ID; int comp_before[MAXN]; int comp_after[MAXN]; void remove_comp(int u, int ...
A very unusual citizen lives in a far away kingdom β€” Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg β€” he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery an...
#include <bits/stdc++.h> using namespace std; template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { for (int i = 0; i < t.size(); i++) s << t[i] << " "; return...
Benny is given two strings S and T. The length of the string S is N and the length of the string T is M respectively. Also, imagine that alphabets are cyclic in nature: a-b-c-…-x-y-z-a-b.. and so on. The distance between two letters is the minimal distance between them in the alphabet cycle. For example, distance be...
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys, math, random, operator from string import ascii_lowercase from string import ascii_uppercase from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations from Queue import Queue, PriorityQue...
It’s the year 2552, the Humans just won a war against a very powerful alien race that had invaded our solar system. The Human army is in celebration mode! The army has n soldiers. The soldiers are numbers from 1 to n. The army has a superiority hierarchy. Every soldier has one immediate superior. The superior of a su...
from collections import deque def calculate(tree): queue = deque(tree[0]) handshakes = fistpumps = nodes = level = 0 while queue: for _ in xrange(len(queue)): root = queue.popleft() handshakes += level fistpumps += nodes - level nodes += 1 queue.extend(tree[root]) level += 1 return handshakes, f...
ACT I Handi Bhaiya is a very notorious kid and always troubles his parents and friends. One day his naughtiness lead him to a demon Kali(THE COBRA COMMANDER) who trapped him into a triangular magic cell. Handi Bhaiya parents want their kid back and asks for your help. ACT II You knew that the entire humanity will hate...
t = int(raw_input()) for _ in range(t): l = [] l = map(int, raw_input().split()) if l[0]+l[1]>l[2] and l[1]+l[2]>l[0] and l[2]+l[0]>l[1]: if l[0]==l[1] and l[1]==l[2]: print 'YES. It is a equilateral triangle.' elif l[0]==l[1] or l[1]==l[2] or l[2]==l[0]: print 'YES. ...
Two players are playing with N-dimensional rectangular with sizes of its sides (a1, a2, ... aN). (Let's call this rectangular as "cube"). Initially there is one cell marked with coordinates (x1, x2, ... xN). On his/her turn a player should divide a current cube into two cubes by exactly one cut along one of the val...
#!/usr/bin/env python from sys import stdin def main(): TC = int(stdin.readline().strip()) for tc in xrange(TC): N = int(stdin.readline().strip()) A = map(int, stdin.readline().split()) X = map(int, stdin.readline().split()) nims = [0] * (2*N) for i in xrange(N): nims[i*2 ...
As you know, there is a furious battle going on between Marut and Devil. They are fighting with strings. Marut's strings are denoted by M and Devil's strings are denoted by D. Both of them are throwing strings on each other in order to get points. Their strings collide in air and one occurrence of some character in one...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' if __name__ == "__main__": line1 = raw_input() vals = [int(x) for x in line1.split()] times = int(raw_input()) marut_points = 0 devil_points = 0 for i in range(0,times): marut =...
Bruce and Diana love to eat peanuts. Diana is currently at Bruce’s mansion to watch a superhero movie when they decide to play a game. Bruce has N number of peanuts in a jar. The rules are simple. In each turn, a player can eat either one or four peanuts. Diana is allowed to start first every time. The player who can e...
for _ in range(input()): n = input() s = n % 5 if s == 1 or s== 3 or s == 4: print "Yes" else: print "No"
Bawris, are wells or ponds in which the water may be reached by descending a set of steps. They may be covered and protected and are often of architectural significance. Rajasthan has a history of maintaining bawris, but now they are of architectural significance hence ASI is interested to save a historic bawris from...
for _ in xrange(input()): a,b,c,d=map(int,raw_input().split()) e=[a,b] f=[c,d] e.sort() f.sort() if e[0]>=f[0] and e[1]>=f[1]:print "Possible" else:print "Not Possible"
See Russian Translation The statement of this problem is quite short , apt and clear. We don't want any coder to spend time in reading a lengthy, boring story that has no connection with the actual problem. The problem states: Given a pair (1,1), your aim is to get a new pair (a,b) in minimum number of operations. ...
test_cases=int(raw_input()) for ite in range(test_cases): given_pair=[int(i) for i in raw_input().split()] num_operations=0 while given_pair!=[1,1] and given_pair!=[1,0] and given_pair!=[0,1]: if given_pair[0]>given_pair[1]: num_operations+=given_pair[0]//given_pair[1] given_pair[0]%=given_pair[1] else: ...
Fatal Eagle is trying his best to save his city, but he's failing to do so. He knows he needs some external help; some guidance, something... something out of ordinary to defeat this powerful enemy called Mr. XYZ. "Find out the number of pairs in the list you've made, who sum up to an even number!" "Who are you? And w...
T=int(raw_input()); for i in range(T): N=int(raw_input()); li=map(int,raw_input().split()); count=0; for i in range(len(li)): for j in range(i,len(li)-1): if((li[i]+li[j+1])%2==0 and li[i]!=li[j+1]): count+=1; print count;
There are N points on a number line, i-th of which is placed on coordinate X_i. These points are numbered in the increasing order of coordinates. In other words, for all i (1 \leq i \leq N-1), X_i < X_{i+1} holds. In addition to that, an integer K is given. Process Q queries. In the i-th query, two integers L_i and R...
#include <bits/stdc++.h> using namespace std; using Int = long long; const char newl = '\n'; 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;} template<typename T> void drop(const T &x){cout<<x<<endl;exit(0);} te...
There are N people (with different names) and K clubs. For each club you know the list of members (so you have K unordered lists). Each person can be a member of many clubs (and also 0 clubs) and two different clubs might have exactly the same members. The value of the number K is the minimum possible such that the fol...
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZER...
Takahashi participated in a contest on AtCoder. The contest had N problems. Takahashi made M submissions during the contest. The i-th submission was made for the p_i-th problem and received the verdict S_i (`AC` or `WA`). The number of Takahashi's correct answers is the number of problems on which he received an `A...
#include <iostream> #include <vector> using namespace std; int main() { int n, m; cin >> n >> m; vector<bool> flag(n); vector<int> cnt(n); int ac = 0, wa = 0; for (int i = 0; i < m; ++i) { int p; cin >> p; --p; string s; cin >> s; if (flag[p]) continue; if (s == "WA") ++cnt[p]; else { wa += cnt[p]...
Given are integers L and R. Find the number, modulo 10^9 + 7, of pairs of integers (x, y) (L \leq x \leq y \leq R) such that the remainder when y is divided by x is equal to y \mbox{ XOR } x. What is \mbox{ XOR }? The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows: * When A \mbox{ XOR } B is writte...
#include<bits/stdc++.h> #define ll long long using namespace std; ll f[64][2][2][2][2];ll l,r;ll ans1=0;int l1[64],r1[64];ll mod=1e9+7; ll dfs(int pos,int tl,int tr,int ts,int th){ if(pos<0) return 1;ll &ans=f[pos][tl][tr][ts][th]; if(ans) return ans; for(int i=0;i<=1;i++){ for(int j=0;j<=1;j++){int fs=ts,fl=t...
In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively. Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k. ...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] ant = new int[5]; int dis = 0; for(int i = 0; i < 5; i++) { ant[i] = sc.nextInt(); } dis = sc.nextInt(); for(int i = 0; i < 4; i++) { for(int j = i + 1; j < 5; j++) ...
Niwango-kun, an employee of Dwango Co., Ltd., likes Niconico TV-chan, so he collected a lot of soft toys of her and spread them on the floor. Niwango-kun has N black rare soft toys of Niconico TV-chan and they are spread together with ordinary ones. He wanted these black rare soft toys to be close together, so he deci...
#include <algorithm> #include <iostream> #include <vector> #include <math.h> #include <set> #include <map> #include <string> #include <stack> #include <queue> #include <iomanip> #include <numeric> #include <tuple> #include <bitset> #include <complex> #include <unistd.h> #include <cassert> #include <cctype> #include <ra...
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i. All employees of AtCoder are now le...
#include <bits/stdc++.h> #define ll long long #define N 1000100 ll n,s,ans,x[N],p[N]; using namespace std; int main(){ scanf("%lld%lld",&n,&s); for (ll i=1;i<=n;i++) scanf("%lld%lld",&x[i],&p[i]); for (ll l=1,r=n;l<=r;){ if (x[l]>=s){ans+=x[r]-s; break;}//ζ‰€ζœ‰δΊΊιƒ½εœ¨δΈ€θΎΉη›΄ζŽ₯εΌ€θΏ‡εŽ» if (x[r]<=s){ans+=s-x[l...
In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton. Init...
#include <bits/stdc++.h> using namespace std ; const int N = 5010 ; const long long inf = 10000000000000000 ; pair<int,int> zab [ N ] ; bool cmp ( pair<int,int> A, pair<int,int> B ) { return A.first + A.second < B.first + B.second ; } long long dp [ N ][ 3 ]; int main() { // freopen("input.txt", "r", stdin) ...
You are given four integers: H, W, h and w (1 ≀ h ≀ H, 1 ≀ w ≀ W). Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive: * The matrix has H rows and W columns. * Each element of the matrix is an integer between -10^9 and 10^...
#include<bits/stdc++.h> using namespace std; const int maxn=1000; int H,W,h,w; int main() { cin>>H>>W>>h>>w; if (H%h==0&&W%w==0) { cout<<"No"; return 0; } else { cout<<"Yes"<<endl; int t=(H/h)*(W/w); int x=t+1,y=(t+1)*(h*w-1)+1; for (int i=1;i<=H;i++) for (int j=1;j<=W;j++) { if (i%h==0&&j%w...
You are given an integer sequence a of length N. How many permutations p of the integers 1 through N satisfy the following condition? * For each 1 ≀ i ≀ N, at least one of the following holds: p_i = a_i and p_{p_i} = a_i. Find the count modulo 10^9 + 7. Constraints * 1 ≀ N ≀ 10^5 * a_i is an integer. * 1 ≀ a_i ≀ ...
#include<bits/stdc++.h> using namespace std; #define mo 1000000007ll #define N 100010 #define int long long int n,d[N],a[N],vi[N],c[N],le[N],s[N],f[N],ans; void dfs(int x){ int v=0,y=0,z=0,p=0; while(c[x]){ v++; c[x]=0; if(le[x]){ if(!y){ z=y=v; p=le[x]; } else{ ans=ans*((le[x]<v-z)+(le[x]<...
We have a grid with H rows and W columns. The state of the cell at the i-th (1≀i≀H) row and j-th (1≀j≀W) column is represented by a letter a_{ij}, as follows: * `.` : This cell is empty. * `o` : This cell contains a robot. * `E` : This cell contains the exit. `E` occurs exactly once in the whole grid. Snuke is tryi...
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> #include<vector> using namespace std; #define si short int #define MAX 101 si f[MAX][MAX][MAX][MAX],s[MAX][MAX]; si sum(int a,int b,int c,int d) { if(a>c)swap(a,c);if(b>d)swap(b,d); return s[c][d]-s[a-1][d]-s[c...
A smelt fishing tournament was held at Lake Hibara. The winner is the one who wins the most smelt. Create a program that reads the list of participant numbers and the number of fish caught and outputs the number of winners and the number of fish caught. If there are multiple winners, output the one with the lowest par...
#include<stdio.h> int main(void) { int a,s,d,f,g,i; f=-1; g=0; scanf("%d",&a); for(i=1;i<=a;i++){ scanf("%d %d",&s,&d); if(f==d){ if(g>s){ g=s; } } else if(f<d){ f=d; g=s; } } printf("%d %d\n",g,f); return 0; }
As bad weather continues and vegetable prices soar, Seven-Eleven is offering customers bulk purchase sales of vegetables. The store is very busy, as you can get vegetables that are hard to find in stores at reasonable prices. One day, a group of three good friends living in the Matsunaga housing complex bloomed with a...
#include<iostream> #include<algorithm> #include<functional> using namespace std; int main(){ int n,m; while(cin>>n>>m,n!=0||m!=0){ int a[1000]={0},ans=0; for(int i=0;i<n;i++)cin>>a[i]; sort(a,a+n,greater<int>()); if(n>=m){ for(int i=0;i<n;i++){ if((i+1)%m==0){ a[i]=0; } } } for(int i=0;i<n...
We make a tower by stacking up blocks. The tower consists of several stages and each stage is constructed by connecting blocks horizontally. Each block is of the same weight and is tough enough to withstand the weight equivalent to up to $K$ blocks without crushing. We have to build the tower abiding by the following ...
#include <iostream> #include<vector> #include<algorithm> #include<string> #include<map> #include<set> #include<stack> #include<queue> #include<math.h> using namespace std; typedef long long ll; #define int long long typedef vector<int> VI; typedef pair<int, int> pii; #define fore(i,a) for(auto &i:a) #define REP(i,n) fo...
There is a vampire family of N members. Vampires are also known as extreme gourmets. Of course vampires' foods are human blood. However, not all kinds of blood is acceptable for them. Vampires drink blood that K blood types of ones are mixed, and each vampire has his/her favorite amount for each blood type. You, cook ...
#include <iostream> #include <vector> using namespace std; int main(){ int n,k,t; bool f=true; vector<int> s; while(1){ cin >> n >> k; if(n==0&&k==0) break; for(int i=0;i<k;i++){ cin >> t; s.push_back(t); } for(int i=0;i<n;i++){ for(int j=0;j<k;j++){ cin >> t; s[j]-=t; } } fo...
Let's think about verbal arithmetic. The material of this puzzle is a summation of non-negative integers represented in a decimal format, for example, as follows. 905 + 125 = 1030 In verbal arithmetic, every digit appearing in the equation is masked with an alphabetic character. A problem which has the above equa...
#include <iostream> #include <algorithm> #include <string.h> using namespace std; #define N 15 int imax, jmax, solution, digit[256], low[256]; char word[N][16]; bool ok[10]; void found(void){ for(int i=0; i<imax; i++){ if(strlen(word[i])>1&&digit[word[i][strlen(word[i])-1]]==0)return; } ++solution; } void solv...
Consider a closed world and a set of features that are defined for all the objects in the world. Each feature can be answered with "yes" or "no". Using those features, we can identify any object from the rest of the objects in the world. In other words, each object can be represented as a fixed-length sequence of boole...
import java.util.Arrays; import java.util.Scanner; public class Main { Scanner sc = new Scanner(System.in); int n; int s; int[] ans; int memo[][]; int rep(int masked, int answer) { if (memo[masked][answer] != -1) { return memo[masked][answer]; } int count = 0; for (int i = 0; i < n; i++) { if (...
Notes For this problem, it is recommended to use floating point numbers, which are more accurate than double. Input m n x k l y For input, six integers m, n, x, k, l, y are given in the above input format. These six integers correspond to those in the problem statement, repeating the horizontal m: n cut x times...
#include <bits/stdc++.h> using namespace std; int cnt[45][45] = {0}; long double dis[45][45] = {0}; long double sum[45][45] = {0}; int m, n, x; long double ans = 1; long double solve(); int main() { cout << fixed << setprecision(12); int t; for(t = 0; t < 2; ++t) { cin >> m >> n >> x; ans *= solve(); ...
Princess'Marriage Marriage of a princess English text is not available in this practice contest. A brave princess in a poor country, knowing that gambling payouts are determined by the parimutuel method, felt more familiar with gambling and was convinced of her victory in gambling. As a result, he spent more money t...
while True: N,M = map(int,input().strip().split(" ")) if [N,M] == [0,0]: break L = [] S = 0 for i in range(N): l = list(map(int,input().strip().split(" "))) l.reverse() L.append(l) S = S + l[0]*l[1] L.sort() for j in range(0,N): t = N-j-1 ...
A linear congruential generator produces a series R(β‹…) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≀ S, A, C ≀ 15 and M = 256. Now suppose we have some input string I(β‹…), where each character in the string is an integer between 0 and (M - ...
#include <cstdio> #include <iostream> #include <string> #include <sstream> #include <stack> #include <algorithm> #include <cmath> #include <queue> #include <map> #include <set> #include <cstdlib> #include <bitset> #include <tuple> #include <assert.h> #include <deque> #include <bitset> #include <iomanip> #include <limit...
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the ...
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<complex> #include<bitset> #include<stack> #include<unordered_map> #include<utility> usi...
Sanpo Problem Statement The cats love walking. There are new discoveries as you walk down the road. The town where Sora lives consists of N squares and N-1 roads. The road just connects the two squares and does not branch or intersect. For the road, the time t to walk, the upper limit m of the number of discoveries...
#include <bits/stdc++.h> using namespace std; using ll = long long int; void chmax(ll &A, ll B) { A = max(A, B); } struct Edge { Edge() {} Edge(int to_, int tm_, int lim_, int cost_) : to(to_), tm(tm_), lim(lim_), cost(cost_) {} int to, tm, lim, cost; }; using Graph = vector< vector<Edge> >; ll N, T, dp...
Taro loves a game called Vongress. Vongress is a camp game played on a board that is a convex polygon consisting of n vertices. In this game, m players place one piece each inside the board. The position of the piece is represented by a set of x-coordinate and y-coordinate, and the size of the piece is not considered....
#include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <climits> #include <ctime> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <set> #include <map> #include <iostream> #include <deque> #include <complex> #include <string> #include <iomanip>...
B: Yamanote-line Game-Yamanote-line Game- Bean (?) Knowledge The Yamanote line is convenient. The reason is that you can ride as many laps as time allows just by paying 130 yen. However, if you board with a ticket, you must be careful about the valid time of the ticket. It seems safe with an IC card. Taking advantage...
#include<iostream> using namespace std; int main(){ int a,n,d,c=0; cin >> n >> d; for(int i=0;i<n;i++) { cin >> a; if(a>d)c+=a-d; } if(c==0)cout << "kusoge" << endl; else cout << c << endl; return 0; }
G: Donuts Orientation story Homu-chan's recent boom is making sweets. It seems that he makes a lot of sweets and shares them with his friends. Homu-chan seems to be trying to make donuts this time. There are many important things in making donuts. Not only the dough and seasoning, but also the decorations to make it...
#include <bits/stdc++.h> #define syosu(x) fixed<<setprecision(x) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> P; typedef pair<double,double> pdd; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd...
problem AOR Ika is a monster buster. One day, as I was walking down the road, I met a sleeping monster. AOR Ika, who has a strong fighting spirit, decides to hit the monster with a wake-up blow. However, the current attack power of AOR Ika is $ 0 $, and she cannot make a decent attack as it is. AOR Ika-chan, who is ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<l_l, l_l> llll; typedef pair<int, int> i_i; template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T &a,...
You have $N$ items that you want to put them into a knapsack. Item $i$ has value $v_i$, weight $w_i$ and limitation $m_i$. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most $W$, that is capacity of the knapsack. * You ...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using vl = vector<ll>; template<class T> using vc = vector<T>; template<class T> using vvc = vector<vector<T>>; #define eb emplace_back #define all(x) (x).begin(), (x).end() #define rep(i, n) for (ll i = 0; i < (n); i++) #defin...
Factorize a given integer n. Constraints * 2 ≀ n ≀ 109 Input n An integer n is given in a line. Output Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a s...
#include <bits/stdc++.h> using namespace std; int main() { long long n,m; cin>>n; m=sqrt(n); cout<<n<<":"; for(int i=2;i<=n;i++) { while(n%i==0){ cout<<" "<<i; n/=i; } if(n==1) break; if(i>=sqrt(n)) { cout<<" "<<n; brea...
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. WAP to check that if 2 such numbers have this property Input: The first line will consist of the total number of test cases T(1 ≀ T ≀ 10). The next T lines will consist of one number on each lin...
import sys t = int(input()) while t>0: a = sys.stdin.readline() b = sys.stdin.readline() if len(a)!=len(b): print ("0") else: x=0 while x!=len(a): check=1 y=0 while y!=len(b): if a[x]==b[y]: b=b[:y]+"a"+b[y+1...
Statement You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the le...
s=''.join(list(map(chr, range(122, 96, -1)))) tc=int(raw_input().strip()) for _ in range(tc): n=int(raw_input().strip()) r=(n%25)*(-1)-1 if(r==-1): print s*(n/25) else: print s[(n%25)*(-1)-1:]+s*(n/25)
Awesomeness of a string is defined by a pair of a character C and an integer F, satisfying the following conditions : C must belong to the given string S and there must be a substring subS of S having length equal to F such that all the characters in subS are equal to c. F should be as large as possible. Yo...
a=raw_input() c,f=0,0 for i in range(len(a)): val=1 while i<len(a)-1 and a[i]==a[i+1]: i=i+1 val=val+1 if val>f: f=val c=a[i] elif val==f: if c>a[i]: c=a[i] print c print f
In an attempt to control the rise in population, Archer was asked to come up with a plan. This time he is targeting marriages. Archer, being as intelligent as he is, came up with the following plan: A man with name M is allowed to marry a woman with name W, only if M is a subsequence of W or W is a subsequence of M. A ...
#### CodeChef #### Open the Dragon Scroll #### 2016.04.07 ## ##def binary(n): ## total = 0 ## while n >0 : ## if n%2 == 1: ## n = n/2 ## total += 1 ## else: ## n = n/2 ## return total ## ##def result(k,n): ## total = 0 ## for i in xrange(n,n-k,-1): ## ...
Given two matrices A and B. Both have N rows and M columns. In the matrix A, numbers from 1 to MN have been written in row major order. Row major order numbers cells from left to right, and top to bottom. That is, 1 2 3 ... M A = M+1 M+2 ...
import sys from fractions import gcd num = int(sys.stdin.readline().rstrip()) while num != 0: n,m = [int(s) for s in sys.stdin.readline().rstrip().split()] count = 0 if n==1 and m==1: count = 1 else: count = gcd(n-1,m-1) + 1 print count num -= 1
You have to submit the assignment tomorrow. It has to be 1000 words long and your lecturer has warned you about writing in really big handwriting so that you can get away with writing less. And how many words have you used? You don't know because you have not written this program yet. Just find the number of words per ...
#!/usr/bin/python count = int(raw_input()) for i in range(count): words = raw_input().split() print len(words)
This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class TheHat { int N = (int) 1e5 + 10; int INF = (int) 2e9 + 10; int n; int[] b ...
Ildar took a band (a thin strip of cloth) and colored it. Formally, the band has n cells, each of them is colored into one of 26 colors, so we can denote each color with one of the lowercase letters of English alphabet. Ildar decided to take some segment of the band [l, r] (1 ≀ l ≀ r ≀ n) he likes and cut it from the...
#include <bits/stdc++.h> using std::max; using std::min; using std::reverse; using std::swap; const int INF = 1e9; const int N = 200010; const int C = 26; int n, sqrtn; char str[N]; int csum[N][C]; namespace SA { int n; int reala[N], realb[N], *a = reala, *b = realb; int sa[N], rk[N], h[N]; int c[N], m; int st[19][N]; ...
You are given two huge binary integer numbers a and b of lengths n and m respectively. You will repeat the following process: if b > 0, then add to the answer the value a~ \&~ b and divide b by 2 rounding down (i.e. remove the last digit of b), and repeat the process again, otherwise stop the process. The value a~ \&~...
#include <bits/stdc++.h> using namespace std; long long int power[200005]; void init() { power[0] = 1; for (long long int i = 1; i < 200005; i++) { power[i] = (2 * power[i - 1]) % 998244353; } } void solve() { string s1, s2; long long int n, m; cin >> n >> m; cin >> s1 >> s2; long long int k = max(n...
Consider a permutation p_1, p_2, ... p_n of integers from 1 to n. We call a sub-segment p_l, p_{l+1}, ..., p_{r-1}, p_{r} of the permutation an interval if it is a reordering of some set of consecutive integers. For example, the permutation (6,7,1,8,5,3,2,4) has the intervals (6,7), (5,3,2,4), (3,2), and others. Each...
#include <bits/stdc++.h> using namespace std; int T, mod; inline int add(int a, int b) { if ((a += b) >= mod) a -= mod; return a; } inline int dec(int a, int b) { if ((a -= b) < 0) a += mod; return a; } inline int mult(int a, int b) { long long t = 1ll * a * b; if (t >= mod) t %= mod; return t; } int f[41...
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β€” colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
import java.io.*; import java.util.*; import java.math.BigInteger; import java.lang.*; public class Main { static class sort1 implements Comparator<List<Integer>> { public int compare(List<Integer> a,List<Integer> b) { return (a.size() - b.size()); ...
Vasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train. Vasya gets on the train at the station. The train consists of n cars indexed from 1 to n counting from the locomotive (head of the train). Three types of events occur while the train is moving: 1. Some n...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; pair<long long, long long> p[N]; int n, m, r = 1; long long k = 0, b = 0; double get_k(pair<long long, long long> a, pair<long long, long long> b) { return 1.0 * (a.second - b.second) / (a.first - b.first); } long long calc(pair<long long, long lon...
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They are given a sequen...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 1; i < n; i++) { if ((a[i] == 3 && a[i - 1] == 2) || (a[i] == 2 && a[i - 1] == 3) || (a[i] == a...
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to...
#include <bits/stdc++.h> bool debug = true; using namespace std; static auto start = chrono::high_resolution_clock::now(); int prime(int n) { int i, j; for (i = 2; i * i <= n; i++) { if (!(n % i)) return 0; } return 1; } int main(void) { if (0) { freopen("in.txt", "r", stdin); freopen("out.txt", "...
The only difference between easy and hard versions is the size of the input. You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'. You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ...
t=int(input()) while t: n,m=map(int,input().split()) s=input() s1="RGB"*(m//3)+"".join(["R","G","B"][:m%3]) s2="GBR"*(m//3)+"".join(["G","B","R"][:m%3]) s3="BRG"*(m//3)+"".join(["B","R","G"][:m%3]) mi=10**9 #print(s1) for i in range(0,n-m+1): c1,c2,c3=0,0,0 for j in range...
You are given two strings s and t both of length 2 and both consisting only of characters 'a', 'b' and 'c'. Possible examples of strings s and t: "ab", "ca", "bb". You have to find a string res consisting of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and...
from itertools import product def main(): n, s, t = int(input()), input(), input() print('YES') abc = ('abc', 'acb', 'bac', 'bca', 'cab', 'cba') if s[0] != s[1] and t[0] != t[1]: for p in abc: if s not in p and t not in p: print(p[0] * n, p[1] * n, p[2] * n, sep='')...
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β€” their sum is equal to 0. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means...
import math as ma x= int(input()) a = [] o = [] e = [] t = [] for i in range (x): p = int(input()) a.append(p) if p%2 ==0: e.append(p) else: o.append(p) t.append(p//2) r = int(abs(sum(e)/2 + sum(t))) for i in a: if i % 2 ==0: print(int(i/2)) else: if(r!=0): print(ma.ceil(i/2)) r-=1 else: prin...
Christmas was knocking on the door, and our protagonist, Bob, was preparing a spectacular present for his long-time second best friend Charlie. As chocolate boxes are lame, he decided to decorate a tree instead. Bob's tree can be represented as an undirected connected graph with n nodes (numbered 1 to n) and n-1 edges....
#include <bits/stdc++.h> using namespace std; mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); const int N = 5e5 + 7; const int M = 1e9 + 7; const int MEM = 1e7; int c[MEM]; int ptr = 0; struct Vector { int* v; int n = 0; Vector() { v = &c[ptr]; } int size() const { return n; }; i...
We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem. Given an undirected labeled tree consisting of n vertices, find a set of segments such that: 1. both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n ...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 500005; vector<long long> g[MAXN]; long long ind; pair<long long, long long> ans[MAXN]; void dfs(long long v, long long p) { for (long long i = (long long)g[v].size() - 1; i >= 0; i--) { if (g[v][i] != p) { ans[g[v][i]].second = ind--; ...
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
n = int(input()) if n % 2 == 0: a = [0]*n x1, y1 = list(map(int, input().split())) x11, y11 = x1, y1 for i in range(n-1): x2, y2 = list(map(int, input().split())) a[i] = [x2-x1, y2-y1] x1, y1 = x2, y2 a[n-1] = [x11-x2, y11-y2] fl = True for i in range(int(n/2)): ...
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l .....
#include <bits/stdc++.h> using namespace std; template <int m> struct modint { unsigned x; modint() : x(0) {} modint(long long arg) { arg %= m; if (arg < 0) { x = arg + m; } else { x = arg; } } modint& operator+=(const modint& other) { x += other.x; if (x >= m) { x -=...
Unfortunately, a mistake was found in the proof of the author's solution to this problem. Currently, we don't know the absolutely correct solution. However, you can solve this task, but if your solution passes all the tests, it is not guaranteed to be correct. If your solution has passed all the tests and you are sure ...
#include <bits/stdc++.h> using namespace std; template <class c> struct rge { c b, e; }; template <class c> rge<c> range(c i, c j) { return rge<c>{i, j}; } template <class c> auto dud(c* x) -> decltype(cerr << *x, 0); template <class c> char dud(...); struct debug { template <class c> debug& operator<<(const c&...