input
stringlengths
29
13k
output
stringlengths
9
73.4k
This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend...
#include <bits/stdc++.h> using namespace std; const long long N = 1e6 + 5; long long a[N]; vector<int> vec; long long yinzi[N]; long long summ[N]; int main() { long long n, m, i, j, k, ans, num = 0, sum, maxa = 0; scanf("%lld", &n); for (i = 1; i <= n; i++) { scanf("%lld", &a[i]); maxa = max(maxa, a[i]); ...
Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permut...
#include <bits/stdc++.h> using namespace std; const int64_t INF = 2e18; void add(int64_t& a, int64_t b) { a = min(INF, a + b); } void mul(int64_t& a, int64_t b) { if (b == 0) { a = 0; } else if (a > INF / b) { a = INF; } else { a *= b; } } template <typename T> struct BIT { int n; vector<T> dat;...
In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains...
#include <bits/stdc++.h> using namespace std; void file() { freopen("input.in", "r", stdin); freopen("output.out", "w", stdout); } int n, kkk; string a[101], b[101]; bool f; bool g; void rec(int x, int y, int hod) { if (x < 1 || y < 1 || x > 8 || y > 8 || f) return; if (x - hod + 1 >= 1 && a[x - hod + 1][y - 1]...
Mayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget, it was decided not to dig new tunnels but to use the existing underground network. The tunnel system of the city M. consists of n metro stations. The stations are connected with n - 1 bidirectional tunnels...
#include <bits/stdc++.h> const int N = 5e5 + 5, M = N * 2, LN = 20; int n, m, p[LN][N], *fa = *p; int o[N], id[N], eid[N], dep[N], cnt; int cov[N], tag[N], bel[M]; std::vector<int> g[N]; inline void up(int &x, int y) { if (x < y) x = y; } inline void down(int &x, int y) { if (x > y) x = y; } void dfs(int u) { o[+...
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place s...
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using pi3 = pair<int, pii>; using INT = long long; const int inf = 1e9; const int MM = 10101; const int KK = 1010; int dp[MM][KK]; int a[MM]; int n, m; int out(int first) { return first < 1 || first > m; } int dx[] = {-1, 1}; int main() { cin >...
Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end. To achieve this, he can perform the following operation any number of times: * Select any...
#include <bits/stdc++.h> using namespace std; long long int MOD = 998244353; long long int pwr(long long int x, long long int y) { long long int res = 1; x = x % MOD; while (y > 0) { if (y & 1) res = (res * x) % MOD; y = y >> 1; x = (x * x) % MOD; } return res; } inline long long int addmod(long l...
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≤ i ≤ n) she calculated a_i — the length of ...
T = int(input()) def solve(): N = int(input()) A = list(map(int,input().split())) def next_char(c): if c == 'a': return 'b' return 'a' ans = [] ans.append('a'*101) for a in A: lst = ans[-1] lst = lst[:a] + next_char(lst[a]) + lst[a+1:] ans.a...
You're given an array a of n integers, such that a_1 + a_2 + ⋅⋅⋅ + a_n = 0. In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make a...
def main(): t = int(input()) for _ in range(t): n = int(input()) alst = list(map(int, input().split())) ans = 0 total = 0 for a in alst: total -= a ans = max(ans, total) print(ans) main()
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. Y...
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not ...
A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not. The string t is called a substring of the string s if it can be read starting from some posi...
s = raw_input () p = raw_input () n = len (s) m = len (p) countInP = [0] * 26 for i in p: countInP[ord (i) - ord ('a')] += 1 ans = 0 for i in xrange (n): if s[i] != '?': countInP[ord (s[i]) - ord ('a')] -= 1 if i < m - 1 : continue if i - m >= 0 and s[i - m] != '?': countInP[ord (s[i - m]) - ord ('a')] += 1 if ...
You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k ≤ n < 2k). Let's call as inversion in a a pair of indices i < j such that a[i] > a[j]. Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]]. Your goal...
from collections import Counter import string import math import sys # sys.setrecursionlimit(10**6) from fractions import Fraction def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arr...
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s. Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order. A merge z is produced from a sequence a by the following rules: * if a_i=0, then re...
#include<bits/stdc++.h> #define int long long #define x first #define y second #define mp make_pair #define pb push_back #define endl "\n" using namespace std; const int max_n = 1e3+100; const int max_value = 1e6+10; const int inf = 1e18; const long long Mod = 998244353; int n,m; string x,y; int dp[max_n][max_n][3];...
This is an interactive problem! Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 ≤ t ≤ 2), two different indices i and j (1 ≤ i, j ≤ n, i ≠ j), and an integer x (1 ≤ x ≤ n - 1). Dep...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.stream.Collectors; public class SolutionC extends Thread { static class FastReader { BufferedReader br; StringTokenizer st; public F...
Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose...
A=[] t=int(input()) def isg(l,r): for i in range(l,r+1): for j in range(i+1,r+1): for k in range(j+1,r+1): if(A[i]>=A[j] and A[j]>=A[k]): return False if(A[i]<=A[j] and A[j]<=A[k]): return False return True for i in rang...
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row — the row which has exac...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[][] a=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { a[i][j]=sc.nextInt(); } } //主对角线 int k=0,kk=0; int i=0,j=0,ii=n-1; ...
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y...
import java.util.Scanner; public class CF197C { public static void main(String[] args) { new CF197C().solve(); } private void solve() { Scanner sc = new Scanner(System.in); String s = sc.next(); StringBuilder sb = new StringBuilder(s.length()); char curMax = 'a'; ...
The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers (x; y), such that 0 ≤ x ≤ w and 0 ≤ y ≤ h. Thus, the Little Elephant knows only (w + 1)·(h + 1) distinct integer points. The Little...
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &t) { t = 0; char ch = getchar(); int f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } do { (t *= 10) += ch - '0'; ch = getchar(); } while ('0' <= ch && ch <= '9'); t *= f; } con...
Old MacDonald has a farm and a large potato field, (1010 + 1) × (1010 + 1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Ol...
#include <bits/stdc++.h> using namespace std; struct Rectangle { int X0, X1, Y0, Y1; }; int Get() { char c; while (c = getchar(), c < '0' || c > '9') ; int X = 0; while (c >= '0' && c <= '9') { X = X * 10 + c - 48; c = getchar(); } return X; } char GetDirection() { char c; while (c = getch...
Once Bob decided to lay a parquet floor in his living room. The living room is of size n × m metres. Bob had planks of three types: a planks 1 × 2 meters, b planks 2 × 1 meters, and c planks 2 × 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, f...
#include <bits/stdc++.h> using namespace std; char mask[105][105]; int main() { int i, j, n, m, a, b, c, need; scanf("%d%d%d%d%d", &n, &m, &a, &b, &c); if (n % 2 && m % 2 || (n * m > (a + b) * 2 + c * 4)) puts("IMPOSSIBLE"); else { if (n % 2) { if (a >= m / 2) { a -= m / 2; need = ...
We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of...
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") const long long maxn = 2e5 + 50, N = 2e4 + 10, SQRT = 300, base = 607583, mod = 1e9 + 7, INF = 1e14 + 1, lg = 25; const long double eps = 1e-4; struct node { pair<long long, long long> last; node() { last = {-1, -1}; } }; no...
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") using namespace std; const int maxn = 3e2 + 10, maxm = 1e3 + 10; const long long mod = 1e9 + 12341; int n, m; const long long decm = 128; long long pw[maxn]; void init(int n = maxn - 5) { pw[0] = 1; for (int i = 1; i <= n; ++i) pw[i] = pw[i - 1] * decm % mod; }...
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t...
import math n = int(input()) l = [int(x) for x in input().split()] a1 = sum(l) a2 = n a3 = 0 temp = 0 l.sort() for i in range(n): temp += l[n-i-1] a3-=(a1-temp) a3+=(n-i-1)*(l[n-i-1]) a1 = a1+a3+a3 a4 = math.gcd(a1, a2) print(a1//a4, a2//a4)
Let's assume that we are given an n × m table filled by integers. We'll mark a cell in the i-th row and j-th column as (i, j). Thus, (1, 1) is the upper left cell of the table and (n, m) is the lower right cell. We'll assume that a circle of radius r with the center in cell (i0, j0) is a set of such cells (i, j) that <...
#include <bits/stdc++.h> using namespace std; int a[510][510], b[510][510], x[510], d[510], n, m, r; int ans[510][510], sum[510][510], as = 0; long long sm = 0; void init() { scanf("%d%d%d", &n, &m, &r); int dx = r; for (int i = (0); i <= (r); ++i) { while (((i) * (i)) + ((dx) * (dx)) > ((r) * (r))) dx--; ...
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, ...
#include <bits/stdc++.h> using namespace std; const int kMax = 50; bool mp[510][510]; bool vis[510]; int link[510]; int in[510], out[510]; int n, m; bool dfs(int cur, int u) { for (int i = 1; i <= n; i++) { if (i == cur) continue; if (!vis[i] && mp[u][i]) { vis[i] = 1; if (!link[i] || dfs(cur, lin...
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece s...
/** * File : B.java * Author : Bao To Hoai * Date : 02.11.2020 13:56:25 UTC+7 * Last Modified Date: 02.11.2020 14:04:25 UTC+7 * Last Modified By : Bao To Hoai */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stri...
In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners: <image> That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an. Your task is to paint a cardiogram by given sequence ai. Input The first line contai...
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Vadim */ public class Main { public s...
There is a computer network consisting of n nodes numbered 1 through n. There are links in the network that connect pairs of nodes. A pair of nodes may have multiple links between them, but no node has a link to itself. Each link supports unlimited bandwidth (in either direction), however a link may only transmit in a...
#include <bits/stdc++.h> int read() { int r = 0, t = 1, c = getchar(); while (c < '0' || c > '9') { t = c == '-' ? -1 : 1; c = getchar(); } while (c >= '0' && c <= '9') { r = r * 10 + c - 48; c = getchar(); } return r * t; } const int N = 200010; int n, f[N], q; long long w[N]; std::pair<lon...
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity ...
#include <bits/stdc++.h> using namespace std; string s[6]; char out[107][107]; vector<int> szs; const int n = 6; int f11 = -1, f12 = -1, f13 = -1, f21 = -1, f22 = -1, f23 = -1; bool cdyx(string a, string b) { if (((int)(a).size()) < ((int)(b).size())) return 1; if (((int)(a).size()) > ((int)(b).size())) return 0; ...
Misha has an array of n integers indexed by integers from 1 to n. Let's define palindrome degree of array a as the number of such index pairs (l, r)(1 ≤ l ≤ r ≤ n), that the elements from the l-th to the r-th one inclusive can be rearranged in such a way that the whole array will be a palindrome. In other words, pair (...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int a[N], cnt[N]; int n; bool isPali() { for (int i = 1; i <= n; i++) { if (a[i] != a[n + 1 - i]) return false; } return true; } bool canPali() { int odd = 0; for (int i = 1; i <= n; i++) { if (cnt[i] & 1) odd++; } return (n & 1)...
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how. In order not to waste time, he decided to practice t...
#include <bits/stdc++.h> using namespace std; signed long long W, H, N; set<int> XX, YY; multiset<int> WW, HH; void solve() { int i, j, k, l, r, x, y; string s; cin >> W >> H >> N; XX.insert(0); XX.insert(W); YY.insert(0); YY.insert(H); WW.insert(W); HH.insert(H); for (i = 0; i < N; i++) { cin >...
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers. There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every ci...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; const int MOD = 1000000007; const double EPS = 1e-9; vector<int> g[MAXN]; int tot[MAXN], good[MAXN]; int p[MAXN], q[MAXN]; set<int> bad; bool vis[MAXN]; vector<int> res; int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); for (int i = 0; i ...
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful...
#include <bits/stdc++.h> using namespace std; long long fact[200001]; long long invFact[200001]; long long mod = 1000 * 1000 * 1000 + 7; long long binpow(long long x, long long n) { if (n == 0) return 1; else if (n & 1) return (binpow(x, n - 1) * x) % mod; else return binpow((x * x) % mod, n >> 1); } ...
A function <image> is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all <image>. We'll deal with a more... discrete version of this term. For an array <image>, we define it's Lipschitz constant <image> as follows: * if n < 2, <image> * if n ...
#include <bits/stdc++.h> using namespace std; using i64 = long long; using Pii = pair<int, int>; constexpr int MAX = 100010; constexpr int INF = 0x3F3F3F3F; unordered_map<int, int> mp; int a[MAX], b[MAX], ll[MAX], rr[MAX], pre[MAX], stk[MAX], top; i64 Solve(int l, int r) { int n = 0; for (int i = l; i < r; ++i) { ...
Let's define the transformation P of a sequence of integers a1, a2, ..., an as b1, b2, ..., bn, where bi = a1 | a2 | ... | ai for all i = 1, 2, ..., n, where | is the bitwise OR operation. Vasya consequently applies the transformation P to all sequences of length n consisting of integers from 1 to 2k - 1 inclusive. He...
#include <bits/stdc++.h> using namespace std; const int maxn = 7e4 + 100; long long n, k; const int mod = 1e9 + 7; namespace MTT { const int M = 32768; int len, t1[maxn], t2[maxn], t3[maxn]; struct Complex { long double x, y; Complex(long double _x = 0, long double _y = 0) { x = _x, y = _y; } Complex operator+(co...
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots o...
#include <bits/stdc++.h> using namespace std; int n, m, end_dag = -1; vector<vector<int> > e; vector<char> visited; vector<int> sorted; vector<int> dist; vector<int> p; int max_len = 0; int max_t = 0; void toposort(int u) { visited[u] = 't'; for (int i = 0; i < e[u].size(); i++) { if (visited[e[u][i]] == 'f') {...
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
n = int(input()) s = input() s = set(s) if n<27: print(n - len(s)) else: print('-1')
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city h...
#include <bits/stdc++.h> using namespace std; vector<int> E[100005]; int sz[100005]; double dp[100005]; void dfs(int x) { sz[x] = 1; for (int i = 0; i < E[x].size(); i++) { int y = E[x][i]; dfs(y); sz[x] += sz[y]; } } void redfs(int x) { dp[x]++; for (int i = 0; i < E[x].size(); i++) { int y =...
Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types: 1. 1 l r x — increase all integers on the segment from l to r by values x; 2. 2 l r — find <image>, where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it mod...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 123; const int mod = 1e9 + 7; const int INF = 1e9 + 1; const long long INFL = 1e18 + 1; const double eps = 1e-9; const double pi = acos(-1.0); inline void add(long long &a, long long b) { a += b; if (a >= mod) a -= mod; } inline long long sum(long lo...
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are a...
#include <bits/stdc++.h> using namespace std; struct man { string name; int score; man() {} man(string nname, int nscore) : name(nname), score(nscore) {} bool operator<(const man &m) const { if (score != m.score) return score > m.score; return name < m.name; } bool operator>(const man &m) const { ...
You are given two trees (connected undirected acyclic graphs) S and T. Count the number of subtrees (connected subgraphs) of S that are isomorphic to tree T. Since this number can get quite large, output it modulo 109 + 7. Two subtrees of tree S are considered different, if there exists a vertex in S that belongs to ...
#include <bits/stdc++.h> using namespace std; const int md = 1e9 + 7; struct edge { int id1, id2; }; edge e[2][11111]; const long long mod = (1e9 + 9) * (1e4 + 7); const int a = 37, b = 1007, pn = 1e4 + 9, base = 67; int n[2]; vector<int> adj[2][1111]; int dp[1 << 12], ww[1001][13], root, pr[1001]; bool can[1 << 12];...
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know,...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 15; const long long inf = 1e18; inline int read() { int x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; return x * f; } inline void write(...
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
import math a = int(input()) #print(math.log(a)) b = int(10 ** ((math.log(a+1) // math.log(10)))) #print(b) total = b while total <= a: total += b print(str(total-a))
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is kno...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); string g, s; cin >> g >> s; int a[26], flag = 0; for (int i = 0; i < s.size(); ++i) { if (s.at(i) == '*') flag = 1; } for (int i = 0; i < 26; ++i) { a[i] = 0; } for (int i = 0; i < g.size(); ++i) { a[g...
This story is happening in a town named BubbleLand. There are n houses in BubbleLand. In each of these n houses lives a boy or a girl. People there really love numbers and everyone has their favorite number f. That means that the boy or girl that lives in the i-th house has favorite number equal to fi. The houses are ...
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("-O3") const int MAXN = 1e5 + 5; const int MAXK = 18; const int MAXQ = MAXN; const int S = 400; struct Query { int l, r, idx, lc; bool operator<(Query other) const { if (l / S != (other.l) / S) return l < other.l; return ((l / S) & 2) ? r < ...
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks. Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans. Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e3 + 5; const int INF = 1e9 + 7; int cnt[maxn][maxn]; char board[maxn][maxn]; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int n, m, k; pair<int, int> st, ed; int bfs() { queue<pair<int, int> > que; que.push(st); cnt[st.first][st.second] = 0...
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions. Suddenly in the morning, Vasya found that somebody spoiled his string...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int N, M; string s; int memo[MAXN], ans[MAXN], preSum[MAXN], consecutive[MAXN][2]; void input() { cin >> N; getline(cin, s); getline(cin, s); cin >> M; s = " " + s; } int solve() { for (int i = 1; i <= N; i++) preSum[i] = preSum[i - 1]...
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the m...
#include <bits/stdc++.h> using namespace std; struct node { long l, r, cnt; }; node mn(long x, long y, long z) { node tmp; tmp.l = x; tmp.r = y; tmp.cnt = z; return tmp; } vector<node> tree; void put(long x) { bool b[30] = {}; long i = 0; while (x) { b[i] = x % 2; x >>= 1; i++; } long ...
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!). Main feature of services offered by BigData Inc. is the access availability guarantee even under the ci...
#include <bits/stdc++.h> using namespace std; template <typename type = int> using Graph = vector<vector<type>>; int n, m, h; Graph<int> g; vector<int> a; int cur_num, num_scc; vector<bool> visited, inStack; vector<int> num, low, scc_num; stack<int> s; Graph<int> scc_to_node; void initialize() { cur_num = num_scc = 0...
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
n = int(input()) + 1 if n == 1: print(0) exit() if n % 2 == 0: print(n //2) else: print(n)
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
l = int(input()) s = list(input()) for i in range(2, l + 1): if l % i > 0: continue s[:i] = s[i - 1::-1] print(''.join(s))
View Russian Translation Little pig Benny has just taken a shower. Now she is going to buy some gifts for her relatives. But the problem is that Benny doesn't know how to reach to the gift shop. Her friend Mike has created a special set of instructions for her. A set of instructions is a string which consists of lett...
inp=raw_input() x,y=0,0 icy={} icy[(0,0)]=1 count=0 for i in inp: if i=='L': y=y-1 if(icy.get((x,y),0)>0): count=count+1 else: icy[(x,y)]=1 if i=='R': y=y+1 if(icy.get((x,y),0)>0): count=count+1 else: icy[(x,y)]=1 if i=='U': x=x-1 if(icy.get((x,y),0)>0): count=count+1 else...
In 1976 the “Four Color Map Theorem” was proven with the assistance of a computer. This theorem states that every map can be colored using only four colors, in such a way that no region is colored using the same color as a neighbor region. Here you are asked to solve a simpler similar problem. You have to decide wheth...
import math class Graph(object): def __init__(self, N) : self.V = N self.gr = [[] for i in range(0, self.V + 1)] def addEdge(self, x, y): self.gr[x].append(y) self.gr[y].append(x) def V(self): return self.V def adj(self, x): return self.gr[x] def dfs(G, curr, prev, vis, ans): vis[curr] = math...
Ferb purchased some colors to decorate his backyard fence. The fence is big (it has to be, as the backyard once hosted a circus, and a roller coaster ride !) and he had to buy multiple boxes of same color. He has a design in mind to paint, its simple and colorful too. Ferb is planning to color every wood of the fence ...
t = input(); while(t > 0): n = input(); m = f = 0; a = [int(i) for i in raw_input().split()]; for i in range(0, n): if(a[i] == m): f = 1; m = a[i]; if(f == 0): print "can do"; else: print "bad luck"; t -= 1;
Mr. Hahn, our very own DJ, was seeing Chester and Mike fighting over such questions lately. Being a geek himself, he thought of showing off his skills and gave the both of them a question. He gave them a single positive integer, N. For all the numbers under 10^N(inclusive) they had to add the square of the digits of ...
a=[1, 3, 20, 143, 1442, 14377, 143071, 1418854, 14255667, 145674808, 1492609148] n=input() print 10**n-a[n],a[n]
Mani wants to eat chocolates, but her brother Pane does not give her the chocolates easily. Pane being a mathematician wants to teach Mani an important concept. Pane makes Mani stand on an infinite straight line. He marks all integers at equal divisions on the line and places chocolates on the integer X. Initially Man...
def gcd(a,b): if(a==0): return b; elif(b==0): return a; elif(a>b): return gcd(a%b,b); else: return gcd(a,b%a); dp=[]; g = 0; g1 = 0; su = 0; for i in range(102): dp.append(0); for i in range(1,101): for j in range(i+1,101): g = gcd(i,j); for k in range(j+1,101): g1 = gcd(g,k); dp[g1] = dp[g1]...
This time, Karan has decided to leave his laptop aside and take part in a long jump event - Noodle Jump. This is a special type of long jump event - it consists of a number of long jumps, of varying lengths. Assuming the positive x-axis as the track, the coordinates where he can put his foot are given. He cannot put h...
n,k = map(int, raw_input().split()) cords = map(int, raw_input().split())[:n] cords.sort() last_cord=0 for cord in cords: next_cord_distance= cord-last_cord if next_cord_distance<=k: last_cord=cord print last_cord
Problem Statement: You are one of the organizers of Pragyan.Having worked so hard to ensure success of the event, you are able to spot the word "pragyan" in any text. You are given a stream of character strings and you need to output them till you find the word "pragyan".Stop processing after NOTE: The word "pragyan"...
def main(): p = [] while(1): str = raw_input() p.append(str) if( str.lower() == "pragyan"): break for i in p: print(i) if __name__ == "__main__":main()
Shil got interested in palindrome research. For that he needs some research data for a particular string S. To obtain this data he has some queries of following type: 1 L x - update L^th character of string to x 2 L R - find if all the character of string from index L to R can be rearranged such that they can form a ...
def main(): N, Q = map(int, raw_input().strip().split()) size = (N << 1) + 2 bin_idx_tree = [] for __ in range(size): bin_idx_tree.append(dict()) S = list(raw_input().strip()) for (idx, ch) in enumerate(S): update(bin_idx_tree, size, idx+1, ch, 1) for __ in range(Q): ...
Navi got a task at school to collect N stones. Each day he can collect only one stone. As N can be a very large number so it could take many days to complete the task, but then he remembers that his mother gave him a magic that can double anything (i.e if he has 2 stones, the magic will make them to 4 stones). Navi ...
def days(n): if( not(n-(-n&n)) ): return 1; power=0 check=False i=0 while(check is False): if(2**i > n): power=i-1 check=True i+=1 return 1+days(n-2**power) t=int(raw_input()) while t: t-=1 n=int(raw_input()) if(n==0): print(0) ...
A binary string of length N is a string of N characters, where each character is either 0 or 1. Wet Shark makes a list binStrings, consisting of all 2^N N-digit binary strings. For each string X in binStrings, Wet Shark runs a function ZeroShark(X), defined as follows (psuedocode): bool ZeroShark(x): //note the zero...
t=int(raw_input()) for i in xrange(0,t): n = long(raw_input()) d=[] d.append(0) d.append(0) d.append(1) f=[] f.append(0) f.append(1) f.append(1) for i in range(3, n): f.append((f[i-1] + f[i-2])%1000000007) for i in range(3, n+1): d.append((d[i-1] + d[i-2] + f[...
For a string S consisting of the uppercase English letters `P` and `D`, let the doctoral and postdoctoral quotient of S be the total number of occurrences of `D` and `PD` in S as contiguous substrings. For example, if S = `PPDDP`, it contains two occurrences of `D` and one occurrence of `PD` as contiguous substrings, s...
#include <iostream> #include <stdio.h> using namespace std; int main(){ string T; cin>>T; for(int i=0;i<T.size();i++)if(T[i]=='?')T[i]='D'; cout<<T; }
Given are N positive integers A_1,...,A_N. Consider positive integers B_1, ..., B_N that satisfy the following condition. Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds. Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N. Since the answer can be enormous, print t...
N = int(input()) A = [int(a) for a in input().split()] import fractions mod = 10**9+7 t = 1 for a in A: t = a*t//fractions.gcd(a, t) ans = 0 for a in A: ans += t//a print(ans%mod)
There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares. The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`. You will perform the following operation exactly N times: choo...
#include<iostream> #include<string> #include<algorithm> using namespace std; typedef long long ll; int N; string A; const ll MOD = 1000000007; int main() { cin >> N; cin >> A; if (A[0] == 'W' || A.back() == 'W') { cout << 0 << endl; return 0; } for (int i = 0; i < 2 * N; i++) { if (i % 2 == 0) { i...
You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x. Constraints * 0 \leq N \leq 10^4 * |a_i| \leq 10^9(0\leq i\leq N) * a_N \neq 0 * All values in input are integers. Input Input is given from Standard I...
#include <bits/stdc++.h> #define For(i, a, b) for(int (i)=(a); (i)<(b); (i)++) #define rFor(i, a, b) for(int (i)=(a)-1; (i)>=(b); (i)--) #define rep(i, n) For((i), 0, (n)) #define rrep(i, n) rFor((i), (n), 0) using namespace std; typedef long long lint; bool isprime(int i){ for(int j=2; j*j<=i; ++j){ if(i ...
In some other world, today is Christmas Eve. There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters. He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees shoul...
#include <bits/stdc++.h> using namespace std; int main(void){ int N, K; cin >> N >> K; int h[N]; for(int i=0; i<N; i++) cin >> h[i]; sort(h, h+N); int ans=1e9; for(int i=0; i<=N-K; i++){ ans = min(h[i+K-1]-h[i], ans); } cout << ans << endl; return 0; }
There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball. The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by...
#include <bits/stdc++.h> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() using namespace std; typedef long long ll; typedef long double ld; int n, a[4010], b[4010], sum[2][4010][2010]; int pos[2][2010]; int dp[2010][2010]; int main() { scanf("%d", &n); for(int i=1; i<=n+n; i++) { char ch; scan...
Snuke Festival 2017 will be held in a tree with N vertices numbered 1,2, ...,N. The i-th edge connects Vertex a_i and b_i, and has joyfulness c_i. The staff is Snuke and N-1 black cats. Snuke will set up the headquarters in some vertex, and from there he will deploy a cat to each of the other N-1 vertices. For each v...
#include<iostream> #include<algorithm> #include<vector> #include<string> #include<set> #include<queue> #include<stack> #include<bitset> #include<functional> #include<map> #include<unordered_set> using namespace std; /*int p = 998244353;*/ int p = 1000000007; #define int long long #define vel vector<long long> #define v...
We will call a string that can be obtained by concatenating two equal strings an even string. For example, `xyzxyz` and `aaaaaa` are even, while `ababab` and `xyzxy` are not. For a non-empty string S, we will define f(S) as the shortest even string that can be obtained by appending one or more characters to the end of...
#include <cstdio> #include <cstring> #define MAXN 1000010 #define LL long long int n; char str[MAXN]; int nxt[MAXN]; int s[26][MAXN]; LL L,R,S,T; void gaoNext(){ nxt[1]=0; for(int i=2,j=1;i<=n;i++,j++){ while(j && str[i]!=str[j]){ if(j==1) j=0; else j=nxt[j-1]+1; } nxt[i]=j; } } void gaoS(){ for(int ...
There are N barbecue restaurants along a street. The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i. Joisino has M tickets, numbered 1 through M. Every barbecue restaurant offers barbecue meals in exchange for these tickets. Restaurant i offers a...
#include<cstdio> #include<cstring> #include<algorithm> #define ll long long using namespace std; const int maxn=5010; int n,m,b[maxn][maxn],s[maxn],l[maxn][maxn],r[maxn][maxn],w[maxn]; ll a[maxn],A[maxn][maxn]; int main(){ scanf("%d%d",&n,&m); for(int i=2;i<=n;i++)scanf("%lld",&a[i]),a[i]+=a[i-1]; for(int i...
Alice, Bob and Charlie are playing Card Game for Three, as below: * At first, each of the three players has a deck consisting of some number of cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged. * The players take turns. Alice goes first. * If the cu...
hands = {char:list(input()) for char in 'abc'} next_hand = 'a' while hands[next_hand]: next_hand = hands[next_hand].pop(0) print(next_hand.upper())
In 1862, the lord of Aizu was ordered to serve as a guardian of Kyoto. The Kyoto Shugoshoku is an important role to protect Kyoto at the end of the Edo period when security has deteriorated. You have to patrol the city by sharing it with the shogunate and other clan. However, when it came time to decide the sharing rou...
#include<iostream> #include<string> #include<algorithm> #include<vector> #include<cstdio> #include<cmath> #define pb(in,tmp) in.push_back(tmp) #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,b) loop(i,0,b) using namespace std; int main(){ int a,b; //cout<<1<<endl; while(cin>>a>>b){ int h[100000]={0}; h[a]++; h[b...
At Aizu Shingakujuku, students are divided into classes by conducting a proficiency test when they enter the cram school. The test consists of three subjects: Mathematics, English, and Japanese, and students are divided into A, B, and C classes. The level of class A is the highest and then decreases in order. The clas...
#include<iostream> #include<vector> using namespace std; int main(){ int n, pm, pe, pj, ave; // vector<int> ave; while(cin >> n, n){ for(int i = 0; i < n; i++){ cin >> pm >> pe >> pj; ave = (pm + pe + pj) / 3; if(pm == 100 || pe == 100 || pj == 100) cout << "A" << endl; else if((pm + pe)/2 >= 90) cout ...
We have had record hot temperatures this summer. To avoid heat stroke, you decided to buy a quantity of drinking water at the nearby supermarket. Two types of bottled water, 1 and 0.5 liter, are on sale at respective prices there. You have a definite quantity in your mind, but are willing to buy a quantity larger than ...
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); if (a <= 2 * b) { if (c % 1000 != 0) { if (c % 1000 <= 500 && b <=...
[0, 0] [0, 1] [1, 1] [0, 2] [1, 2] [2, 2] [0, 3] [1, 3] [2, 3] [3, 3] [0, 4] [1, 4] [2, 4] [3, 4] [4, 4] [0, 5] [1, 5] [2, 5] [3, 5] [4, 5] [5, 5] [0, 6] [1, 6] [2, 6] [3, 6] [4, 6] [5, 6] [6, 6] Consider the standard set of 28 western dominoes as shown in the above figure. Given a subset of the ...
#include<iostream> #include<cstdio> #include<set> #define REP(i,n) for(int i=0; i<(int)(n); i++) using namespace std; char d[30][3]; int n; set<int> ss[7]; bool solve(int cnt, char prev, int f){ if(cnt == n) return true; if(ss[prev-'0'].count(f)) return false; ss[prev-'0'].insert(f); REP(i,n) if(f & (1<<...
Let's think about a bar rotating clockwise as if it were a twirling baton moving on a planar surface surrounded by a polygonal wall (see Figure 1). <image> Figure 1. A bar rotating in a polygon Initially, an end of the bar (called "end A") is at (0,0), and the other end (called "end B") is at (0,L) where L is the l...
#include <cassert>// c #include <ctime> #include <iostream>// io #include <iomanip> #include <fstream> #include <sstream> #include <vector>// container #include <map> #include <set> #include <queue> #include <bitset> #include <stack> #include <algorithm>// other #include <complex> #include <numeric> #include <functiona...
Math teacher Mr. Matsudaira is teaching expansion and factoring of polynomials to his students. Last week he instructed the students to write two polynomials (with a single variable x), and to report GCM (greatest common measure) of them as a homework, but he found it boring to check their answers manually. So you are ...
#include <iostream> #include <vector> #include <string> using namespace std; int abs(int a){ return a > 0 ? a : -a; } int gcd(int a, int b){ return a%b ? gcd(b, a%b) : b; } int lcm(int a, int b){ return a/gcd(a,b)*b; } vector<int> mul(vector<int> a, vector<int> b){ vector<int> res(a.size()+b.size()-1, 0); for(int ...
Problem If you collect L pieces, Dragoso will appear and only one Dragoso ball will be fulfilled, scattered in a labyrinth. Starting from the entrance, collecting all the balls without stopping on the way, dedicating them to the altar in the labyrinth, and casting the spell as it is, Dragoso will appear and grant his ...
#include<iostream> #include<map> #include<algorithm> #include<queue> #include<vector> using namespace std; typedef pair<int,int> P; typedef pair<int,P> P2; int n,m,l,k; int u,v,c; int s,g,t; int b[7]; int dis[51][1<<7][10],vis[51][1<<7]; vector<P> G[51]; const int INF = 100000000; int main(){ while(cin >> n >> m ...
The postal system in the area where Masa lives has changed a bit. In this area, each post office is numbered consecutively from 1 to a different number, and mail delivered to a post office is intended from that post office via several post offices. Delivered to the post office. Mail "forwarding" is only done between sp...
#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,...
You are in a fantasy monster-ridden world. You are a slayer fighting against the monsters with magic spells. The monsters have hit points for each, which represent their vitality. You can decrease their hit points by your magic spells: each spell gives certain points of damage, by which monsters lose their hit points,...
#include<iostream> #include<sstream> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair #define pb push_back #define...
Dr. Kay Em, a genius scientist, developed a new missile named "Ikan-no-i." This missile has N jet engines. When the i-th engine is ignited, the missile's velocity changes to (vxi, vyi) immediately. Your task is to determine whether the missile can reach the given target point (X, Y ). The missile can be considered as ...
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #define eps 1.0e-8 #define INF 1e50 #define g 4.9 using namespace std; double X,Y; int n; struct G{ double x; double y; }; G d[1010]; double calc(double x) { double ans=0; for(int i=0;i<n;i++){ double t=(x*d[i].x/g+d[i].y/g)/2...
Problem C: Earn Big A group of N people is trying to challenge the following game to earn big money. First, N participants are isolated from each other. From this point, they are not allowed to contact each other, or to leave any information for other participants. The game organizer leads each participant, one by on...
#include<stdio.h> #include<algorithm> using namespace std; double dp[1100]; int main(){ int a,b; scanf("%d%d",&a,&b); dp[0]=1; for(int i=0;i<a;i++){ double ks=1; for(int j=1;j<=b&&i+j<=a;j++){ dp[i+j]+=dp[i]*ks/(a-i-j+1); ks*=(double)(a-i-j)/(a-i-j+1); } } printf("%.12f\n",dp[a]); }
Sunuke received a d-dimensional hypercube with a side length of l1 × ... × ld as a birthday present. Sunuke placed this rectangular parallelepiped so that the range of the i-th coordinate was 0 or more and li or less, and ate the part that satisfied x1 + ... + xd ≤ s. However, xi represents the i-th coordinate. If the ...
#include <bits/stdc++.h> using namespace std; template <class T, class F = multiplies<T>> T power(T a, long long n, F op = multiplies<T>(), T e = {1}) { assert(n >= 0); while (n) { if (n & 1) e = op(e, a); if (n >>= 1) a = op(a, a); } return e; } template <unsigned M> struct modular { using m = modu...
Example Input 5 5 8 1 3 5 1 2 4 2 3 3 2 4 3 1 5 7 Output 4
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <vector> using namespace std; #define debug(x) cerr<<#x<<'='<<x<<'\n' #define Int const int & const int N=110000; struct edge { int v, nxt, w; } e[N<<1]; bool pd[N]; int first[N], g[N], sz[N]; int n, tot, where, now, ans; struct...
M: Presents Mr. Shirahane prepared the following set as a surprise present for a certain devil. * Consists of different $ K $ natural numbers less than or equal to $ N $ * No matter which pair of two values ​​you choose from the set, one number is divisible by the other In fact, such a set has the property of robb...
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
Problem There are $ M $ type characters. Use them to create a string of length $ N $. How many strings are used that have $ K $ or more? Find too much divided by $ 998244353 $. Here, the difference between two strings of length $ N $ is defined as follows. * If the two strings are $ S = S_1S_2 \ ldots S_N $, $ T = T...
#include <bits/stdc++.h> using namespace std; typedef long long ll; constexpr ll MOD = 998244353; ll power(ll x, ll n){ x %= MOD; ll res = 1; while(n > 0){ if(n&1){ res *= x; res %= MOD; } x *= x; x %= MOD; n >>= 1; } return res; } ...
Find the tangent lines between a point $p$ and a circle $c$. Constraints * $-1,000 \leq px, py, cx, cy \leq 1,000$ * $1 \leq r \leq 1,000$ * Distance between $p$ and the center of $c$ is greater than the radius of $c$. Input The input is given in the following format. $px \; py$ $cx \; cy \; r$ $px$ and $py$ repr...
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;++i) #define all(a) a.begin(),a.end() typedef long long ll; typedef complex<double> Point; typedef vector<Point> VP; #define X real() #define Y imag() const double EPS = 1e-9; // ?¨±?????????^2 #define LE(n,m) ((n) < (m) + EPS) #define EQ(n,...
For a set $S$ of integers, perform a sequence of the following operations. Note that multiple elements can have equivalent values in $S$. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$. * delete($x$): Delete all $x$ from $S$. ...
#include<bits/stdc++.h> #define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i) #define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i) #define foreach(i, n) for(auto &i:(n)) #define pii pair<int, int> ...
There is an infinite binary tree which has following structure: 3 / \ 6 8 / \ / \ 11 13 15 ...
for _ in range(input()): x=int(raw_input()) i=1 p=0 while (p<=x): p=2**i +i i+=1 #print i,p>x if(p>x): i-=2 p=(2**i)+i #print i,p ps=abs(p-x) if (ps%2==0) and (ps<2**i): #print 'Yes' if (ps/2)%2==0: print 'LEFT' else: print 'RIGHT' else : print 'NO' #pri...
Shinchan is new to COUNTER STRIKE and he cannot differentiate between players of Terrorist and Counter Terrorist. Since he is new to COUNTER STRIKE so he used to kill his team members as he couldn't recognize them. Everyone got frustrated with him. One day he came up with a formula to recognize players by their user na...
x=input() for i in range(x): y=raw_input() c=0 l=[] for a in y: if a not in l: l.append(a) c=c+1 if c%2==0: print "Terrorist" if c%2!=0: print "Counter Terrorist"
Chef wrote some text on a piece of paper and now he wants to know how many holes are in the text. What is a hole? If you think of the paper as the plane and a letter as a curve on the plane, then each letter divides the plane into regions. For example letters "A", "D", "O", "P", "R" divide the plane into two regions so...
t=input() list=['A','Q','D','R','B','O','P'] while(t): S=raw_input() hole=0 for i in S: if i in list: if i=='B': hole+=2 else: hole+=1 print(hole) t-=1
You're given an array of N integer numbers. The maximal sum of the array is the maximal sum of the elements of a nonempty consecutive subarray of this array. For example, the maximal sum of the array [1, -2, 3, -2, 5] is 6 because the sum of the subarray [3, -2, 5] is 6 and it is impossible to achieve greater subarra...
#!/usr/bin/python def R(): return map(int, raw_input().split()) T = R()[0] for i in range(T): N = R()[0] A = R() all_negative = True max_element = None max_so_far = 0 max_ending_left = 0 # maximum subsequence ending at prev position max_skipped_one = 0 # maximum subsequence ending ...
On the occasion of 66^th Republic day, a young lad, Lemon Kumar (a.k.a Yaar Kumar), is revising his speech again and again to remember it. He found that some of the letters in his speech is repeated quite often. Being very fond of programming, like the Chef, he took it as a challenge and decided to find this letter. He...
import string for _ in range(int(raw_input())): string=str(raw_input()).lower() punctuation=['!','@','#',' ','$','%','^','&','*','(',')','-','=','+','[',']',"'",';','/''1','2','3','4','5','6','','7','8','9','0'] string1=[f for f in string if f not in punctuation] string=''.join(string1) dictionary={...
Problem description  The IPL Auctions are finally over and cricket legend Rahul Dravid now wants to find the most balanced team in the league. Each player is bought at some price X in the auction. Dravid defines the balance of each team as the largest price difference between any 2 players in that team. The most balanc...
t = input() for i in range(t): d = 9999999 index = 0 for j in range(10): mn = map(int,raw_input().split()) s = max(mn)-min(mn) if s<=d: d = s index = j+1 print index,d
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace. This "personal treasure" is a multis...
#include <bits/stdc++.h> using namespace std; const int maxn = 5e5 + 5; int w[15]; int a[maxn]; int n; int change(char *s) { int res = 0, tmp = 1; for (int i = n - 1; ~i; i--) { if (s[i] == '1') res += tmp; tmp *= 2; } return res; } int sum[maxn / 5][105]; int cnt[maxn / 5]; int get2(int x, int t) { i...
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ...
def heist(n,a): return max(a)-min(a)-n+1 n=int(input()) a=list(map(int,input().split())) print(heist(n,a))
We call a sequence of strings t1, ..., tk a journey of length k, if for each i > 1 ti is a substring of ti - 1 and length of ti is strictly less than length of ti - 1. For example, {ab, b} is a journey, but {ab, c} and {a, a} are not. Define a journey on string s as journey t1, ..., tk, such that all its parts can be ...
#include <bits/stdc++.h> template <class __TyFirst, class __TySecond> std::ostream& operator<<(std::ostream& out, const std::pair<__TyFirst, __TySecond>& o) { out << "(" << o.first << "," << o.second << ")"; return out; } template <typename _ForwardIterator> void logArray(_ForwardIterator _...
Vasya owns three strings s , a and b, each of them consists only of first k Latin letters. Let a template be such a string of length k that each of the first k Latin letters appears in it exactly once (thus there are k! distinct templates). Application of template p to the string s is the replacement of each character...
#include <bits/stdc++.h> using namespace std; template <typename T> void maxtt(T& t1, T t2) { t1 = max(t1, t2); } template <typename T> void mintt(T& t1, T t2) { t1 = min(t1, t2); } bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "URDL"; long long ln, lk, lm; void etp(b...
Ayoub had an array a of integers of size n and this array had two interesting properties: * All the integers in the array were between l and r (inclusive). * The sum of all the elements was divisible by 3. Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and...
#include <bits/stdc++.h> using namespace std; const int MAXN = 200001, MOD = 1000000007; int n, l, r; long long one = 0, two = 0, zero = 0, dp[MAXN][3]; int main() { cin >> n >> l >> r; for (; l % 3 != 0 && l <= r; l++) if (l % 3 == 1) one++; else if (l % 3 == 2) two++; for (; r % 3 != 0 && r ...
You are given a string s of length n consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we g...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); char[] c = sc.next().toCharArray(); int INF = 1_000_000_000; int[][] dp = new int[n][n+1]; for (int i=0;i<n;i++) { ...
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny. He has a special interest to create difficult problems for others to solve. This time, with many 1 × 1 × 1 toy bricks, he builds up a 3-dimensional object. We can describe ...
import sys, os, re, datetime from collections import * from bisect import * def mat(v, *dims): def submat(i): if i == len(dims)-1: return [v for _ in range(dims[-1])] return [submat(i+1) for _ in range(dims[i])] return submat(0) __cin__ = None def cin(): global __cin__ if __cin__ is None...