input
stringlengths
29
13k
output
stringlengths
9
73.4k
You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you ...
from sys import stdin #import math input = stdin.readline q = int(input()) for _ in range(q): n = int(input()) a = list(map(int, input().split())) a.sort() l = a[-1] a.pop() for i in range(2*n-1): d = {} for ii in range(2*n - 1): if ii == i: continue ...
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up. Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 1010; int L[N], R[N]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int q, ans = 0; string s, sr; cin >> s; sr = s; reverse(sr.begin(), sr.end()); cin >> q; while (q--) { string t; cin >> t; string a = t +...
<image> To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way: Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distributio...
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(0);cin.tie(0); #define endl '\n' typedef long long ll; const int MOD = 1e9 + 7; const int MAX = 1e5+10; ll inv(ll a, ll b=MOD) { return a > 1 ? b - inv(b%a, a)*b/a : 1; } ll fat[MAX]; ll choose(ll a, ll b) { if (a < b) return 0; ...
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery:...
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; int main() { const int MAX_P = 100000 + 1; bool p[MAX_P]; for (int i = 0; i < MAX_P; ++i) p[i] = true; p[0] = p[1] = false; for (int i = 2; i * i <= MAX_P; ++i) { if (p[i]) { for (int j = i + i; j < MAX_P; j += i) p[j] = false; ...
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help. A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers...
#include <bits/stdc++.h> using namespace std; int n, m, c, x; int a[100005]; long long mars[2 * 100005]; int main() { scanf("%d %d %d", &n, &m, &c); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= m; ++i) { scanf("%d", &x); mars[i] += x; mars[i + (n - m + 1)] -= x; } long lon...
One day Qwerty the Ranger witnessed two transport ships collide with each other. As a result, all contents of their cargo holds scattered around the space. And now Qwerty wants to pick as many lost items as possible to sell them later. The thing is, both ships had lots of new gravitational grippers, transported to sal...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long s = 0; bool f = 0; char ch = ' '; while (!isdigit(ch)) { f |= (ch == '-'); ch = getchar(); } while (isdigit(ch)) { s = (s << 3) + (s << 1) + (ch ^ 48); ch = getchar(); } return (f) ? (-s) : (s); } inline vo...
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current s...
n,k=map(int,input().split()) l=list(map(int,input().split())) f=l[k-1] if l[k-1:].count(f) == n-k+1: r = 0 for i in range(k-2,-1,-1): if l[k-1] != l[i]: break r+=1 print(len(l[:k-1-r])) else: print(-1)
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as m username pairs ai...
#include <bits/stdc++.h> using namespace std; const int MAXN = 10000 + 10; set<string> name; set<int> g[MAXN]; map<string, int> mm; int m, n, f[MAXN]; int main() { ios::sync_with_stdio(0); cin >> m; for (int i = 0; i < m; i++) { string s1, s2; cin >> s1 >> s2; if (name.find(s1) == name.end()) { ...
Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively. However, his...
#include <bits/stdc++.h> using namespace std; int inflow[200005], outflow[200005], cost[200005], A[200005], B[200005]; int ans[200005]; vector<pair<int, int> > adj[200005]; vector<pair<int, int> >::iterator it; int main() { memset(ans, -1, sizeof(ans)); int N, M; scanf("%d%d", &N, &M); for (int i = 0; i < M; ++...
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights. <image> Shaass puts the books...
import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) { FastReader sc = new FastReader(); int n=sc.nextInt(); int t[]=new int[n+1]; int w[]=new int[n+1]; for (int i=1;i<=n;i++){ t[i]=sc.nextInt(); ...
Princess Vlada enjoys springing in the meadows and walking in the forest. One day — wonderful, sunny day — during her walk Princess found out with astonishment that her shadow was missing! "Blimey!", — she thought and started her search of the shadow in the forest. Normally the Shadow is too lazy and simply sleeps und...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:100000000") int matrix[1000][1000]; int tmp[1000][1000]; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; queue<pair<int, int> > all; void go(int x, int y) { queue<pair<int, int> > q; tmp[x][y] = 1; q.push(make_pair(x, y)); all.p...
Iahub is playing an uncommon game. Initially, he has n boxes, numbered 1, 2, 3, ..., n. Each box has some number of candies in it, described by a sequence a1, a2, ..., an. The number ak represents the number of candies in box k. The goal of the game is to move all candies into exactly two boxes. The rest of n - 2 box...
#include <bits/stdc++.h> using namespace std; template <class T> inline void read(T &x) { x = 0; char c = getchar(); int f = 1; while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); } x *= f; } template <class T> inline voi...
You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r). Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]). Your task is to find a ...
#!/usr/bin/env python if __name__ == '__main__': n = int(raw_input()) nums = map(int, raw_input().split()) maks_len = 0 if len(nums) < 2: print len(nums) else: c = 0 for i in range(2, len(nums)): if nums[i] == nums[i - 1] + nums[i - 2]: c += 1 ...
Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible. ...
import java.io.*; import java.util.*; public class A { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(); int g = gcd(in.nextInt(), in.nextInt()); for (int i = 2; i < n; i++) ...
Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts: ...
#include <bits/stdc++.h> using namespace std; char s[] = "1001010111001010"; int main() { int n; cin >> n; cout << s[n - 1] << endl; return 0; }
Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. <image> Imagine that you are playing Cut the...
import java.io.*; import java.util.*; public class e111 { BufferedReader br; StringTokenizer in; PrintWriter out; Node main_root; Random q = new Random(0); int[] answ; class Node { Node l, r; int y, size, id, type; long x, sum; Node(long m, int id1, int t1) { x = m; id = id1; y = q.nextInt(1...
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand t...
s=raw_input() k=input() l=['January','February','March','April','May','June','July','August','September','October','November','December'] print l[(l.index(s)+k)%12]
Petya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an n × m table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty. Petya watches cars riding into the parking lot one...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long infLL = 0x3f3f3f3f3f3f3f3fLL; const int maxn = 2000 + 5; int n, m, k; char g[maxn][maxn]; int x[maxn], y[maxn]; int up[maxn][maxn], down[maxn][maxn]; int cur, ret[maxn]; void update(int c) { for (int i = 0; i < (n); ++i) up[...
Mr. Kitayuta's garden is planted with n bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the i-th bamboo is hi meters, and it grows ai meters at the end of each day. Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed beca...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops") #pragma GCC optimize("no-stack-protector,fast-math") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const long long N = 2e5 + 100, OO = 1e9 + 7, T = 22, M = 1e9 + 7, P = 6151, ...
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarp...
#include <bits/stdc++.h> using namespace std; const int MN = 100111; int n, M, T; int a[MN], bit[MN], res[MN]; int get(int u) { int res = 0; while (u > 0) { res += bit[u]; u -= ((u) & (-(u))); } return res; } void update(int u, int val) { while (u < MN) { bit[u] += val; u += ((u) & (-(u))); ...
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ...
n,k = map(int,input().split(" ")) i=0 res=k sh=0 while i<k: i+=1 mas=list(map(int,input().split(" ")))[1:] if mas[0]==1: j=0 while j<(len(mas)-1): if(mas[j]+1!=mas[j+1]): break else: j+=1 sh+=len(mas)-j-1 res+...
One day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money. The pawnbroker said that each watch contains a serial number ...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const int INF = (1 << 30) - 1; const long long mod = 190102321; const int MAXN = 200010; int n, m, k; char s[MAXN]; struct Hash { long long H[MAXN], B[MAXN]; long long TH[10][MAXN]; void init(char *s, int P, int len) { H[0] = 0; B[0] =...
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; int main() { set<int> done; vector<pair<int, int> > grads1, grads2; vector<long long> sols; int n, q; scanf("%d%d", &n, &q); vector<int> vals; vals.resize(n); for (int c = 0; c < n; c++) scanf("%d", &vals[c]); for (int c = 0; c < n - 1; c++) grads1.pus...
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine...
a, b = input(), input() ans = 0 index = a.find (b, 0) while index != -1: ans = ans + 1 index = a.find (b, index + len (b)) print (ans)
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities. Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting ea...
#include <bits/stdc++.h> using namespace std; int v[1001], u[1001], n, a, b, c, d, k; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); scanf("%d%d%d%d%d%d", &n, &k, &a, &b, &c, &d); if (n == 5) { if (k <= 5) { printf("-1"); return 0; } int e = 15 - (a + b +...
Sometime the classic solution are not powerful enough and we have to design our own. For the purpose of this problem you have to implement the part of the system of task scheduling. Each task should be executed at some particular moments of time. In our system you may set the exact value for the second, minute, hour, ...
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; int IT_MAX = 1 << 17; const long long MOD = 1000000007; const int INF = 1034567890; const long long LL_INF = 1234567890123456789ll; const double PI = acos(-1); const long double ERR = 1E-10; long long par[6]; long long M[13] = {0, 31, 28, 31,...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
n = int(input()) if 1 <= n <= 100: for i in range(n): word = input() if len(word) > 10: numWord = str(len(word[1:-1])) print(word[0] + numWord + word[-1]) else: print(word)
Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri,...
#include <bits/stdc++.h> using namespace std; class TaskC { public: vector<pair<long long, long long> > v; vector<long long> ans; long long n, m; void rec(long long i, long long mx) { long long tmx = mx; long long ed = 0; long long j = v[i].first; while (j <= v[i].second && ans[j]) { j++;...
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose t...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; public class P764B { public static void main(String[] args) { FastScanner scan = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = scan...
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 = 100010; vector<pair<long long, int>> adj[10 * MAXN]; long long dist[10 * MAXN]; int par[10 * MAXN]; int go1(int idx, int l, int r, int ds) { if (idx > 1) { int par = idx / 2; adj[par + ds].push_back({0, idx + ds}); } if (l == r) { adj[idx ...
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper...
<image> Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb. The cobweb is a set of n nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread c...
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; class stree { public: std::vector<std::pair<long long, long long>> t; int s; void build(int n, int v, int tl, int tr) { if (v == 1) { t.resize(n * 4); s = n; } if (tl == tr) t[v] = make_pair(0, 1); e...
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale. Maxim often visits h...
def gen(n,k): mini = min(n-k,1) maxi = min(n-k,2*k) if k==0: mini=0 print mini,maxi def main(): nums = map(lambda x:int(x),raw_input().split(' ')) gen(nums[0],nums[1]) if __name__ == "__main__": # while True: # main() main()
A sequence of n integers is written on a blackboard. Soon Sasha will come to the blackboard and start the following actions: let x and y be two adjacent numbers (x before y), then he can remove them and write x + 2y instead of them. He will perform these operations until one number is left. Sasha likes big numbers and ...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } pair<int, int> q[100000...
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1. Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0. You have to color the tree into the given colors using the smallest possible number of steps. On each step you can c...
from queue import * n=int(input()) parent={} child={} for i in range(1,n+1): parent[i]=0 child[i]=[] l=list(map(int,input().split())) for i in range(2,n+1): parent[i]=l[i-2] child[l[i-2]].append(i) l=list(map(int,input().split())) color={} for i in range(1,n+1): color[i]=l[i-1] q=Queue() q.put...
Arkady the air traffic controller is now working with n planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The i-th plane, small enough to be represented by a point, currently has a coordinate of xi and is moving with speed vi. It's guaranteed that xi·vi < ...
import java.io.*; import java.util.*; public class MainD { static final StdIn in = new StdIn(); static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n=in.nextInt(), w=in.nextInt(); Pair[] ps = new Pair[n]; for(int i=0; i<n; ++i) ps[i] = new Pair(in.next...
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution... Input The only line of input data contains the arith...
#include <bits/stdc++.h> using namespace std; char c[1010]; int n, as, nw; int main() { int i, j; scanf("%d%s", &as, c); n = strlen(c); for (i = 0; i < n;) { nw = c[i] - '0'; j = i + 1; while (isdigit(c[j])) nw = nw * 10 + c[j] - '0', ++j; if (c[i] == '+') as += nw; else as -= nw...
One university has just found out about a sport programming contest called ACM ICPC v2.0. This contest doesn't differ much from the well-known ACM ICPC, for example, the participants are not allowed to take part in the finals more than two times. However, there is one notable difference: the teams in the contest should...
#include <bits/stdc++.h> using namespace std; int n; double p[110]; double mval = -1.0; inline int iabs(int x) { return x < 0 ? -x : x; } int main() { scanf("%d", &n); for (int i = 0; i <= n; i++) scanf("%lf", &p[i]); for (int i = 0; i <= n; i++) { int a = n - 2 * i; if (a <= 0) break; for (int j = n;...
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed...
#include <bits/stdc++.h> using namespace std; const string gr[24] = {"123456", "234156", "341256", "412356", "143265", "432165", "321465", "214365", "546213", "462513", "625413", "254613", "452631", "526431", "264531", "645231", "351624", "516324", "1...
Hope you still have not forgotten about pig Benny. She is asking for help again. This time you have to answer some queries that Benny will give you. All actions happen in the Universe where each planet has its own id starting from 0. There are infinite amount of planets. To travel between different planets there ...
N,Q=map(int, raw_input().split()) arrD=map(int, raw_input().split()) if N==1: for iCase in xrange(Q): print "YES" if int(raw_input())%arrD[0]==0 else "NO" else: gcd=arrD[0] for i in xrange(1,N): b=arrD[i] while b: gcd,b=b,gcd%b if gcd>1: for i in xrange(N): arrD[i]/=gcd MAX=10000...
Jesse and Walter recently got a into a problem. They need to check if a compound can be converted to the other one. A compound is decoded into a binary strings of 0s and 1s. They have 2 binary strings. First string contains characters '0', '1' and '?', whereas second contains '0' and '1' only. As Jesse and Walter are b...
''' https://www.hackerearth.com/nit-calicut-codeburst-50/algorithm/compound-conversion-1/ ''' T = int(input()) negative_infinity = float("-inf") postive_infinity = float("inf") for tc in xrange(T): first = raw_input().strip() second = raw_input().strip() if len(first) != len(second): print(-1) ...
"RMS Lusitania" was one of the world biggest ship of her time.On the outbreak of the First World War in 1914, she was commandeered by the Admiralty as an armed merchant cruiser. When Lusitania left New York for Liverpool on what would be her final voyage on 1 May 1915, submarine warfare was intensifying in the Atlantic...
def find(W,wt,val,n): i=0 K=[] while i<n+1: K.append([0]*(W+1)) i+=1 i=0 while i<=n: j=0 while j<=W: if i==0 or j==0: K[i][j]=0 elif wt[i-1]<=j: K[i][j]=max(val[i-1]+K[i-1][j-wt[i-1]],K[i-1][j]) else: ...
Ikshu's love for binary numbers Ikshu recently learnt to generate random numbers. He is generating stream binary numbers. Uptil now he has generated N bits of the binary number. Now, he wants to know if there is a streak of contiguous 1's of length K. Help him to find the probability of existence of such a streak in ...
n, k = map(int, raw_input().strip().split()) array = [0 for _ in range(k)] array.append(1) powers = [2 ** i for i in range(n+1)] for i in range(k+1, n+1): array.append(powers[i - k - 1] - array[i - k - 1] + 2 * array[i-1]) num = array[-1] denom = powers[-1] while num % 2 == 0: num = int(num / 2) denom = int(den...
Marut loves good strings. According to him, good strings are those which contain either all alphabets of uppercase or lowercase. While he is preparing for his exams, he finds many bad strings in his book and wants to convert them to good strings. But he wants to do this in minimum number of operations. In one operatio...
def test(S): l=len(S) if not (l>=1 and l<=100): print 'Invalid Input' elif S.isdigit(): print 'Invalid Input' else: counterL=0 counterU=0 idx=0 invalidChar=0 while idx < l: if ord(S[idx]) >= 65 and ord(S[idx])<=90 : ...
Harold always boasted about his prowess with numbers. So one day Reese challenged him to a problem. He gave Harold two numbers X and Y and asked him to find out the N^th number of the series which began with X numbers of Y’s and the following elements are equal to the sum of the last X numbers in the series. Help Harol...
no_of_test_cases = input() for i in range(0, no_of_test_cases): l = [] values = None values = raw_input().split(" ") x = int(values[0]) y = int(values[1]) n = int(values[2]) l = [y] * x while len(l) < n: b = sum(l[-x:]) l.append(b) print l[-1]
Rahul has set upon the quest for a new logo of his company. He has created the following continuous logo: /\ / \ / /\ \ / / \ \ / / /\ \ \ \ \ \/ / / \ \ / / \ \/ / \ / \/ However, his sister, Rashi, likes the following discontinuous design more /\ / \ / /\ \ / / \ \ \ \ ...
## \ \ \/ / / ## \ \ / / ## \ \/ / ## \ / ## \/ ###n odd #n=7 n=int(input()) def fore(n): for i in range(n): if i % 2 == 0: strx = ((n-1-i)*" " + "/ "*(i//2) + "/\\" + (i//2) * " \\") print(strx) else: print(" " * (n-1-i) + (i//2+1)*'/ ' + (i//2+1...
Akshit and Rahul are playing a game. Initially, two positive integers A and B are written on a blackboard. The players take turns, starting with Akshit. On his or her turn, a player can replace A with A - kB for any positive integer k, or replace B with B - kA for any positive integer k. The first person to make one of...
def gcd(x,y): if ( x < y ): t = x x = y y = t if x % y == 0: return y else: return gcd(y,x%y) def isprime(n): i = 2 while i*i <= n: if n % i == 0: return False i = i + 1 return True t = int(raw_input()) for p in range(t): a,b,c,d = map(int,raw_input().split(" ")) count = 0 for i in ra...
Bangalore City, where peace prevails most of the time. Not everyone is a huge fan of peace, though. Certainly not Mr. XYZ, whose identity is not known to us - yet. Mr. XYZ has somehow managed to bring vampires and zombies to Bangalore City to attack and destroy the city. Fatal Eagle, an ordinary citizen of the city is...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' total = input() x = [] x = map(int, raw_input().split()) evenList = [] oddList = [] sumE = 0 sumO = 0 for i in x: if i%2 == 0 : evenList.append(i) evenList.sort() sumE = sumE + i...
There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N). For each k = 1,2,\dots,N, find the answer to the following question: Rng is in City k. Rng can perform the following move arbitrarily many t...
#include <bits/stdc++.h> using namespace std; //#include <atcoder/all> //using namespace atcoder; using ll=long long; using Graph=vector<vector<int>>; using pp=pair<ll,pair<ll,ll>>; #define MAX 1000000 #define MOD 998244353 #define INF 1000000000000000000 int main(){ int N; cin>>N; vector<pair<pair<int,int>,int>...
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person. The people are going to dance on two kinds of songs: salsa and rumba. * When a salsa i...
#include<bits/stdc++.h> #define mo 100000007 using namespace std; long long read(){ long long xx=0,flagg=1; char ch=getchar(); while((ch<'0'||ch>'9')&&ch!='-') ch=getchar(); if(ch=='-'){ flagg=-1; ch=getchar(); } while(ch>='0'&&ch<='9'){ xx=xx*10+ch-'0'; c...
We have an H \times W grid, where each square is painted white or black in the initial state. Given are strings A_1, A_2, ..., A_H representing the colors of the squares in the initial state. For each pair (i, j) (1 \leq i \leq H, 1 \leq j \leq W), if the j-th character of A_i is `.`, the square at the i-th row and j-t...
// #pragma GCC target("avx") // CPU 処理並列化 // #pragma GCC optimize("O3") // CPU 処理並列化 // #pragma GCC optimize("unroll-loops") // 条件処理の呼び出しを減らす // #define BEGIN_STACK_EXTEND(size) void * stack_extend_memory_ = malloc(size);void * stack_extend_origin_memory_;char * stack_extend_dummy_memory_ = (char*)alloca((1+(int)(((...
Given is a rooted tree with N vertices numbered 1 to N. The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i. Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0. Now, the following Q operations will be performed: * Operation...
import java.util.*; import java.io.*; public class Main { public static long[] ans; public static Map<Integer, List<Integer>> map; public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); ...
N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N. The i-th tile from the left is painted black if the i-th character of S is `0`, and painted white if that character is `1`. You want to repaint some of the tiles black or white, so that any two a...
S = str(raw_input()) n = len(S) pattern0 = ("10" * (n//2 + 1)) pattern1 = ("01" * (n//2 + 1)) count0 = 0 count1 = 0 for i in range(n): if pattern0[i] != S[i]: count0 += 1 if pattern1[i] != S[i]: count1 += 1 print min(count0, count1)
One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N. He is interested in properties of the sequence a. For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to ...
#include <bits/stdc++.h> typedef long long ll; using namespace std; int main() { int N, K; cin >> N >> K; vector<ll> a(N + 1); for (int i = 1; i <= N; ++i) { cin >> a[i]; } vector<ll> d(N + 1, 0); for (int i = 1; i <= N; ++i) { d[i] = d[i - 1] + a[i]; } vector<ll> v; for (int l = 0; l <= N - 1; ++l) { ...
Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j). There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i...
#023_B n = int(input()) s = [input() * 2 for _ in range(n)] ans = 0 for b in range(0, n): flg = True for i in range(n): for j in range(n): if s[i][b+j] != s[j][b+i]: flg = False break if flg: ans += 1 print(ans * n)
We have a sequence A of length N. On this sequence, we can perform the following two kinds of operations: * Swap two adjacent elements. * Select one element, and increment it by 1. We will repeatedly perform these operations so that A will be a non-decreasing sequence. Find the minimum required number of operati...
#include<bits/stdc++.h> using namespace std; #define REP(i,st,ed) for(register int i=st,i##end=ed;i<=i##end;++i) #define DREP(i,st,ed) for(register int i=st,i##end=ed;i>=i##end;--i) typedef long long ll; template<typename T>inline bool chkmin(T &x,T y){return (y<x)?(x=y,1):0;} template<typename T>inline bool chkmax(T &...
Snuke can change a string t of length N into a string t' of length N - 1 under the following rule: * For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t. There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operati...
import java.util.*; import java.util.function.BiFunction; import java.util.function.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); long j = 0 ; List<Character> ls = ne...
A tetromino is a figure formed by joining four squares edge to edge. We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively: a60bcb8e9e8f22e3af51049eda063392.png Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession...
#include <bits/stdc++.h> using namespace std; typedef long long LL; LL ans=0; int a,b,c,d,e,f,g; int x,y,z; int main(){ scanf("%d%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f,&g); ans=b; x=a,y=d,z=e; int t=(x&1)+(y&1)+(z&1); if (y&1) swap(x,y); if (z&1) swap(z,y); if (t>=2){ if (z>0) ans+=3,x--,y--,z--; } ans+=x/2*...
Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns. Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically ...
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; int map[500][500]; int ans1[500][500]; int main() { int mx,my; scanf("%d%d",&mx,&my); for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { char z; scanf(" %c",&z); if(z=='#')map[i][j]=ans1[i][j]=1; } } for(int i=0;i<mx;i++) { ...
Create a program that outputs all leap years between the year a and year b. The leap year conditions are as follows. However, 0 <a ≤ b <3,000. If there is no leap year in the given period, output "NA". * The year is divisible by 4. * However, a year divisible by 100 is not a leap year. * However, a year divisible by ...
#include<stdio.h> int main(void) { int y,y2; int i; int flg,flg2; flg=0; scanf("%d %d",&y,&y2); while(y!=0 && y2!=0){ if(flg==0){ flg=1; } else{ printf("\n"); } flg2=0; for(i=y;i<=y2;i++){ if(y%400==0){ printf("%d\n",y); flg2=1; } if(y%4==0){ if(y%100!=0){ printf("%d\...
Relative B man came to A child's house. He is 3 years old and loves singing. He is singing the song "Kobutanuki Tsuneko" (written and composed by Naozumi Yamamoto), which he learned from kindergarten. In this song, the four words "kobuta," "raccoon dog," "fox," and "cat" are arranged in order, and the last and first so...
#include<bits/stdc++.h> using namespace std; int N; string s[10000]; //UnionFind----------------------------- int par[26],sz[26]; void init(){ for(int i=0;i<26;i++){ par[i]=i; sz[i]=1; } } int find(int x){ return x==par[x]?x:par[x]=find(par[x]); } void unite(int x,int y){ x=find(x);y=...
Yae joins a journey plan, in which parties will be held several times during the itinerary. She wants to participate in all of them and will carry several dresses with her. But the number of dresses she can carry with her may be smaller than that of the party opportunities. In that case, she has to wear some of her dre...
#include <iostream> using namespace std; int main(){ int a,b; cin >> a >> b; int num=0; while(b>0){ b=b-a; num++; } cout << num << endl; return 0; }
There are a number of ways to shuffle a deck of cards. Riffle shuffle is one such example. The following is how to perform riffle shuffle. There is a deck of n cards. First, we divide it into two decks; deck A which consists of the top half of it and deck B of the bottom half. Deck A will have one more card when n is ...
#include<iostream> #include<queue> using namespace std; queue<int>Q[3]; int p, q; void solve(int a) { for (int i = 0; i < 1000; i++) { if (Q[i % 2].size() < a) { while (!Q[i % 2].empty()) { Q[2].push(Q[i % 2].front()); Q[i % 2].pop(); } } else { for (int j = 0; j < a;j++){ Q[2].push(Q[i % 2].front()); Q[i ...
One of the oddest traditions of the town of Gameston may be that even the town mayor of the next term is chosen according to the result of a game. When the expiration of the term of the mayor approaches, at least three candidates, including the mayor of the time, play a game of pebbles, and the winner will be the next ...
while True: n, p = map(int, raw_input().split()) wan = p if n == p == 0: break A = [0 for _ in xrange(n)] i = 0 while True: if p > 0: A[i] += 1 p -= 1 if A[i] == wan: print i break else: p += ...
You have probably learnt chemical equations (chemical reaction formulae) in your high-school days. The following are some well-known equations. 2H2 + O2 -> 2H2O (1) Ca(OH)2 + CO2 -> CaCO3 + H2O (2) N2 + 3H2 -> 2NH3 ...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; string st; int a; int get_num() { int num=0; while (a != st.size() && isdigit(st[a])) { num*=10; num+=st[a]-'0'; a++; } return num; } map<string ,int>mole(); map<string, int>uni_group(...
Problem N circular light sources are arranged on a two-dimensional plane. When a light source receives light, the light is emitted in a fan shape from the center point of the light source as shown in the figure below. <image> The center point of the light source is represented by (x, y) and the radius is represented ...
#include<iostream> #include<cmath> #include<algorithm> #include<vector> #include<iomanip> #include<complex> #include<cassert> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define inf (1<<28) #define EPS (1e-10) #define COUNTER_CLOCKWISE 1 #define CLOCKWISE -1 #define ONLINE_BACK 2 #define ONLINE...
Karakuri Doll Karakuri doll English text is not available in this practice contest. After many years of research, Karakuri puppeteer JAG has succeeded in developing a wonderful tea-drawing doll that combines traditional and latest techniques. This tea-drawing doll is placed in a teacup with tea in the kitchen (K) in...
#include <iostream> #include <vector> #include <tuple> using namespace std; using P = pair<int, int>; using PP = pair<P, int>; int W, H; int sy, sx, sd; int gy, gx, gd; bool field[16][64]; bool used[16][64][4][16][64][4]; bool used2[16][64][4]; constexpr int dx[] = {0, 1, 0, -1}; constexpr int dy[] = {-1, 0, 1, 0}; v...
A tatami mat, a Japanese traditional floor cover, has a rectangular form with aspect ratio 1:2. When spreading tatami mats on a floor, it is prohibited to make a cross with the border of the tatami mats, because it is believed to bring bad luck. Your task is to write a program that reports how many possible ways to sp...
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include <string> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> using namespace std; #define rep(i,j) REP((i), 0, (j)) #define REP(i,j,k) for(int i=(j);(i)<(k);++i) #de...
The Kingdom of Neva is home to two ethnic groups, the Totata and the Tutete. The biggest feature of the Totata tribe is that they eat sweet and sour pork with pineapple. However, the Tutete tribe eats vinegared pork in pineapple. These two peoples couldn't get along with each other, and the Totata and Tutete have been ...
#include <bits/stdc++.h> using namespace std; #define all(v) (v).begin(), (v).end() #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++) typedef pair<double, int> P; const double inf = 1e9; #define EPS (1e-10) #define equals(a, b) (fabs((a)-(b)) < EPS) ...
Palindrome Problem Statement Find the number of palindromes closest to the integer n. Note that the non-negative integer x is the number of palindromes, which means that the character string in which x is expressed in decimal notation and the character string in which it is inverted are equal. For example, 0,7,33,10...
#include<bits/stdc++.h> #define range(i,a,b) for(int i = (a); i < (b); i++) #define rep(i,b) for(int i = 0; i < (b); i++) #define all(a) (a).begin(), (a).end() #define show(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; const i...
This year too, the time has come for the National Programming Championships. In the district tournament where the right to participate in the national tournament is bet, 2n teams will face each other in a one-on-one winning tournament system. Team numbers 0, .. .2n − 1 are assigned to the tournament table, and the con...
#include<bits/stdc++.h> using namespace std; signed main(){ int n,m; cin>>n>>m; vector<long long int> a(m+1); for(auto &v:a) cin>>v; vector<int> b(m); for(auto &v:b) cin>>v; long long int res=0; vector<pair<pair<int,int>,long long int>> state; for(int i=0;i<m;i++){ state.push_back({{a[i],a[i+1]...
This issue is the same configuration issue as D: DAG Trio (Easy), with only the constraints being different. input $ N \ M $ $ a_1 \ b_1 $ $ a_2 \ b_2 $ $ \ vdots $ $ a_M \ b_M $ output Print "YES" or "NO" on the $ 1 $ line. Example Input 3 3 1 2 2 3 3 1 Output YES
#include<bits/stdc++.h> using namespace std; #define MAX_N 500 #define MAX_M 50000 struct edge{ int from,to,id; }; int N,M; int a[MAX_M],b[MAX_M]; bool flg[MAX_M]; vector<edge> G[MAX_N]; bool visited[MAX_N]; int depth[MAX_N]; int cnt[MAX_N]; int par[MAX_N]; vector<edge> bridges; vector<edge> edge_; void dfs(int...
E: Round-trip String story This is the world where all human beings have become competition programmers. In this world, there are many customs that you cannot think of in the present age. One of them is the custom of sending a character string when expressing gratitude to parents, especially mothers. There are region...
#include <bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) #define int long long using namespace std; typedef pair<int,int>P; typedef pair<P,int>P2; #define fi first #define se second typedef unsigned long long ull; struct RollingHash{ typedef unsigned long long ull; string S; ull B; int len; vector<u...
problem There are $ N $ propositions, named $ 1, 2, \ cdots, N $, respectively. Also, $ M $ information about the propositions is given. The $ i $ th information is "$ a_i $$". Given in the form "b_i $", which means that $ a_i $ is $ b_i $. ("If" is a logical conditional and the transition law holds.) $ For each propo...
#include <iostream> #include <string> #include <stdlib.h> #include <vector> #include <algorithm> using namespace std; int n, m; vector<int> G[305], revG[305]; vector<int> topo; bool used[305]; int scc[305]; void tpsort(int v) { used[v] = true; for(int i = 0; i < G[v].size(); i++){ if(!used[G[v][i]]) tpsort(G[v][...
You have N items that you want to put them into a knapsack. Item i has value vi, weight wi and limitation mi. 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 can select at m...
#include<bits/stdc++.h> using namespace std; int main(){ int n, W; cin >> n >> W; vector<int> v(n); vector<int> w(n); vector<int> m(n); for(int i = 0; i < n; i++) cin >> v[i] >> w[i] >> m[i]; vector<int> dp(W + 1, 0); for(int i = 0; i < n; i++){ //take key goods each for(int k = 0; m[i] > 0; k++){ in...
Find the difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, $A - B$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; a...
#include <bits/stdc++.h> using namespace std; //#include <boost/multiprecision/cpp_int.hpp> //using multiInt = boost::multiprecision::cpp_int; using ll = long long int; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; template <typename Q_type> using smaller_queue = priority_queue<Q_type, ...
Problem Statement Little Chef doesn't love math anymore. He loves Aleksandra. Sashen'ka is nice. They spend all the time together. Even their birthdays they are celebrating together, because they were born on the same day :) And now, this day is coming... Chef know that most of all Sasha loves numbers, that's why...
import sys from bisect import bisect_left def line_to_array(): return map(int, sys.stdin.readline().strip().split(' ')) def main(): """ x**y | y*log(x) | log(x)/x | |--log--> |--divide by (x*y)--> |--> f(n) = log(n)/n y**x | x*log(y) ...
One night Mr.X and Mr.Y were playing a game. To test Mr.Y's intelligence Mr.X gives him an interesting problem to solve. He gives him a number N and asks him to swap the digits in the number such that a smallest number M is obtained without leading zeroes. Mr.Y thinks this is an easy problem to solve and immediately gi...
for a in range(input()): ins = sorted(val for val in raw_input()) if ins[0]=="0": for x in range(1,len(ins)): if int(ins[x])>0: ins[0] = ins[x] ins[x] = "0" break if "".join(ins) == raw_input(): print "AC" else: ...
Golu is a student of Computer Engineering and he decided to make a project for himself.So he started working on URL shortner.While working on project he got confused.You are a good friend of Golu so he asked you for help. You have given a link and you have to convert it into a short link using algorithm given by Golu. ...
for _ in range(input()): s=raw_input() a=[0]*26 for i in s: if i>='a' and i<='z': a[ord(i)-97]+=1 m1=max(a) i=a.index(m1) a[i]=0 m2=max(a) j=a.index(m2) a[j]=0 m3=max(a) k=a.index(m3) a[k]=0 print 'ocul.in/'+str(chr(i+97))+str(m1)+str(chr(j+97))+str(m2)+str(chr(k+97))+str(m3)
A Little Elephant and his friends from the Zoo of Lviv like candies very much. There are N elephants in the Zoo. The elephant with number K (1 ≤ K ≤ N) will be happy if he receives at least AK candies. There are C candies in all in the Zoo. The Zoo staff is interested in knowing whether it is possible to make all the...
t=int(raw_input()) while t: t-=1 n,c=map(int,raw_input().split()) sum=0 inp2=raw_input().split() for i in range(n): sum+=int(inp2[i]) if sum<=c: print("Yes") else: print("No")
In poker, you have 5 cards. There are 10 kinds of poker hands (from highest to lowest): royal flush - ace, king, queen, jack and ten, all in the same suit straight flush - five cards of the same suit in sequence, such as 10,9,8,7,6 of clubs; ace can be counted both as the highest card or as the lowest card - A,2,3,4...
#kcahdog straights=['23456','34567','45678','56789','6789T','789JT','89JQT','9JQKT','AJKQT','2345A'] for u in range(input()): cards=raw_input().split() flush=True #check for flush for i in range(4): if(cards[i][1]!=cards[i+1][1]): flush=False cards.sort() #check for straights...
A straightforward question. Given an array of positive integers you have to print the number of subarrays whose XOR is less than K. Subarrays are defined as a sequence of continuous elements Ai, Ai+1, ..., Aj . XOR of a subarray is defined as Ai^Ai+1^ ... ^Aj. Symbol ^ is Exclusive Or. You can read more about i...
from sys import stdin raw_input = stdin.readline class Trie: def __init__(self): self.nextL = [-1] * 300000 self.nextR = [-1] * 300000 self.sizeL = [0] * 300000 self.sizeR = [0] * 300000 self.hash = 1 def insert(se...
There are n parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely r_i. When a parrot with respect level x starts chattering, x neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on...
#include <bits/stdc++.h> using namespace std; const int mxN = 1e5; int n, l[17][17][mxN], r[17][17][mxN]; pair<int, int> qry(int i, int l2, int r2) { int b = 31 - __builtin_clz(r2 - l2 + 1); return {max(l[i][b][l2], l[i][b][(r2 - (1 << b) + 1) % n] - (r2 - (1 << b) + 1 - l2)), max(r[i][b][(r...
You are a given a list of integers a_1, a_2, …, a_n and s of its segments [l_j; r_j] (where 1 ≤ l_j ≤ r_j ≤ n). You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select ...
#include <bits/stdc++.h> using namespace std; int n, m, s, k; int a[1501], aa[1501]; int z[1501], f[1501][1501]; int g[1501]; int st[1501], hz[1502]; int ef(int p) { int l = 1, r = st[0]; while (l != r) { int mid = l + r >> 1; if (st[mid] <= p) r = mid; else l = mid + 1; } return l; } bo...
The only difference between easy and hard versions is the constraints. Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th p...
import java.util.Scanner; public class Main { private static long[][] dp; private static long[] input = new long[1000]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i , j , n , k , x; long ans = - 1; n = scan.nextInt(); k = scan.nextInt(); x = sca...
Fedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array a_1, a_2, … a_n and a beautiful data structure. This data structure, given l and r, 1 ≤ l ≤ r ≤ n, could find the greatest integer d, such that d divides each of a_l, a_{l+1}, ..., a_{r}. Fed...
#include <bits/stdc++.h> using std::max; using std::min; const int inf = 0x3f3f3f3f, Inf = 0x7fffffff; const long long INF = 0x3f3f3f3f3f3f3f3f; __inline__ __attribute__((always_inline)) unsigned int rnd() { static unsigned int seed = 416; return seed += 0x71dad4bfu, seed ^= seed >> 5, seed += 0xc6f74d88u, ...
Niyaz has a tree with n vertices numerated from 1 to n. A tree is a connected graph without cycles. Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex. Niyaz does not like when vertices in the tree have too large degrees. For each x from 0 ...
#include <bits/stdc++.h> using namespace std; const long long INF = 0x3f3f3f3f; const int N = 3e5 + 100; bool debug = false; vector<pair<int, int> > vc[N]; set<pair<long long, int> > gg1[N], gg2[N], gg3[N]; set<pair<long long, int> >::iterator iit; int in[N], vis[N], ord[N]; long long dp[N][2], sum[N]; bool cmp(pair<in...
There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum ...
#include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; vector<long long> a, b; a.clear(); b.clear(); long long ans = 0; for (long long i = 2; i / 2 < n; i *= 2) { for (long long j = 1; j <= n; j += i) { for (long long k = j; k < j + i / 2; k++) { if (k > n) b...
In some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users. Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least o...
import sys n, m = map(int, input().split()) par = [0] * (n + 1) cnt = [0] * (n + 1) for i in range(n + 1): par[i] = i def find(a): if par[a] == a: return a par[a] = find(par[a]) return par[a] for i in sys.stdin.readlines(): x = list(map(int, i[:-1].split())) if x[0]: ta = find(x[1]) for i i...
A company of n friends wants to order exactly two pizzas. It is known that in total there are 9 pizza ingredients in nature, which are denoted by integers from 1 to 9. Each of the n friends has one or more favorite ingredients: the i-th of friends has the number of favorite ingredients equal to f_i (1 ≤ f_i ≤ 9) and y...
#include <bits/stdc++.h> using namespace std; struct P { int x, y, z; }; vector<int> v; int i, n, m, k, a, d, b, c; int e; int o[112222]; int l[113222][2]; int j[1]; int dx[10] = {0, 1, 0, -1, 1, 1, -1, -1}, dy[10] = {1, 0, -1, 0, 1, -1, 1, -1}, dz[10] = {0, 0, 0, 0, 1, -1}; int px[10] = {-1, 1, 1, -1, 1, 1, -1, ...
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems. Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following ...
#include <bits/stdc++.h> using namespace std; int n, s[200005], t[200005]; char ss[200005]; int main() { scanf("%s", ss); int n = strlen(ss); for (int i = 1; i <= n; i++) s[i] = ss[i - 1] - '0'; int tot = 0; for (int i = n; i >= 1; i--) { if (tot && s[i]) t[i] = 1; else t[i] = 0; if (s...
You are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board. A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met: * |x_...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i % 2 == 1) { if (j % 2 == 1) { cout << "W"; } else { cout << "B"; } } else { if (j % 2 == 1) { ...
There are n positive integers written on the blackboard. Also, a positive number k ≥ 2 is chosen, and none of the numbers on the blackboard are divisible by k. In one operation, you can choose any two integers x and y, erase them and write one extra number f(x + y), where f(x) is equal to x if x is not divisible by k, ...
#include <bits/stdc++.h> using namespace std; bitset<16 * 2002> dp[1 << 16]; int n, k; int a[16]; int weight[16]; int calc(int &x) { int c = 0; while (x % k == 0) x /= k, c++; return c; } int _calc(int x) { int c = 0; while (x % k == 0) x /= k, c++; return c; } void dfs(int s, int x) { if (__builtin_popco...
Let a be a matrix of size r × c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i ∈ [1, r], let b_i be the greatest common divisor of integers in the i-th ...
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') ...
This problem is different with hard version only by constraints on total answers length It is an interactive problem Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask tw...
#include <bits/stdc++.h> using namespace std; const long long maxn = 6e6; const long long inf = 1e18; const long long maxv = 2e8 + 100; const int miniinf = 1e9; const long double eps = 1e-6; const long long flowconst = 1e9; void init() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); } int main() { init(...
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass! On the field, there is a row of n units of grass, each with a sweetness s_i. Farmer John has m cows, each with a favorite sweetness f_i and a hunger value h_i. He would like to pick two disjoint subset...
#include <bits/stdc++.h> using namespace std; const long long const1 = 1e9 + 7; signed main() { long long n, m; cin >> n >> m; vector<long long> s(n); for (long long i = 0; i < n; i++) { cin >> s[i]; s[i]--; } vector<long long> f(m), h(m); vector<vector<long long> > p(n); for (long long i = 0; i...
Drazil likes heap very much. So he created a problem with heap: There is a max heap with a height h implemented on the array. The details of this heap are the following: This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed f...
#include <bits/stdc++.h> using namespace std; int a[(1 << 21) + 1]; int wid(int i) { if (a[2 * i] == 0 && a[2 * i + 1] == 0) { return i; } else { if (a[2 * i] > a[2 * i + 1]) { return wid(2 * i); } else { return wid(2 * i + 1); } } } void f(int i) { if (a[2 * i] == 0 && a[2 * i + 1] ...
Please notice the unusual memory limit of this problem. Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white. For each iteration of the game (the initial iteration is 0), the color of...
#include <bits/stdc++.h> using namespace std; struct compare { bool operator()(const pair<int, int>& l, const pair<int, int>& r) { if (l.first == r.first) { return l.second > r.second; } return l.first > r.first; } }; bool isgood(vector<vector<int>>& A, int i, int j) { if (i < A.size() - 1 && A[...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
for _ in range(int(input())): n=int(input()) print(max(1,n//2 + int(n%2)))
Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric. The piec...
#include <bits/stdc++.h> using namespace std; long long n, m, ans; char c[2005][2005]; long long up[2005][2005], down[2005][2005], le[2005][2005], ri[2005][2005]; int main() { scanf("%d%d", &n, &m); for (register int i = 1; i <= n; i++) scanf("%s", c[i] + 1); for (register int i = 1; i <= n; i++) for (registe...