input
stringlengths
29
13k
output
stringlengths
9
73.4k
Dexter was good in finding the K th smallest number from a set of numbers. He thought he could solve any problem related to K th smallest number. His friend Pipi challenged him with a problem. He gave him various ranges of number, These numbers were arranged in increasing order(only distinct numbers to be taken into ac...
test = int(raw_input()) for i in range(test): n , q = [int(x) for x in raw_input().split()] arr = [] for i in range(n): arr.append([int(x) for x in raw_input().split()]) arr.sort() a = [0] b = [0] a[0] = arr[0][0] b[0] = arr[0][1] k = 0 for i in range(1 , n): if arr[i][0] > b[k]: k += 1 a.append(arr...
Monk has magical powers, by which he can compare any part of the strings and figure out if they're equal. His magical powers are faster than a super computer even. So, to prove his worth, he's given a string and he has to answer multiple queries based on the string. Every query will have four integers - L1, R1, L2, R2...
s=raw_input() l=len(s) q=int(raw_input()) for i in xrange(q): L1,R1,L2,R2=map(int,raw_input().split(" ")) a=s[L1-1:R1] b=s[L2-1:R2] if a==b: print "Yes" else: print "No"
Danny has a possible list of passwords of Manny's facebook account. All passwords length is odd. But Danny knows that Manny is a big fan of palindromes. So, his password and reverse of his password both should be in the list. You have to print the length of Manny's password and it's middle character. Note : Th...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n=input() dic={} for i in range(n): passw = raw_input() dic[passw]=1 try: if dic[passw[::-1]]==1: print len(passw), passw[len(passw)/2] except KeyError: continue
Roy is the owner of a flower plant farm and sells flower plants for a living. Now the problem with flower plants is that they wither in a night if not taken care of. So at the end of the day, to make flower plants wither-resistant Roy uses special fertilizers. There are N number of plants not sold on one particular...
def computeDP(totalPlants,lastDaysProfit,fertilizers,profit): # First we find what maximum profit Roy could gain dp = [[0 for x in xrange(lastDaysProfit+1)] for x in xrange(totalPlants+1)] for i in xrange(totalPlants+1): for j in xrange(lastDaysProfit+1): if i == 0 or j == 0: dp[i][j] = 0 elif fertilize...
Consider All lowercase Alphabets of the English language. Here we consider each alphabet from a to z to have a certain weight. The weight of the alphabet a is considered to be 1, b to be 2, c to be 3 and so on until z has a weight of 26. In short, the weight of the alphabet a is 1, and the weight of all other alphabets...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' z=raw_input() k=[] for i in z: ans=(ord(i)-96) k.append(ans) print sum(k)
Utkarsh lives in a strange country. The cities of the country are present on x axis. He is currently at a city at x = 0. He needs to reach another city at x = N. Utkarsh can move only in the positive x direction. Also due to massive traffic in the one dimensional country, at any time = T seconds, a person can make one ...
#Given a number N, find a number Y such as Y > N and Y is sum of first K natural numbers. # K is the answer to the problem. from math import sqrt, floor t = int(raw_input()) for i in range(t): n = int(raw_input()) x = n * 2 y = int(floor(sqrt(x))) k = (y * (y + 1)) / 2 if k >= n: print y else: y += 1 k = ...
An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; `R` stands for red and `W` stands for white. You can do the following two kinds of operations any number of times in any order: * Choose two stones (not nec...
N = int(input()) S = input() r = S.count('R') ans = r - S[:r].count('R') print(ans)
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below: * Consider writing a number on each vertex in the tree in the following manner: * First, write 1 on Vertex k. * Then, for each of the numbers 2, ..., N in this order, w...
def main(): M=10**9+7 N=10**5*2 fac=[0]*(N+1) fac[0]=b=1 for i in range(1,N+1):fac[i]=b=b*i%M inv=[0]*(N+1) inv[N]=b=pow(fac[N],M-2,M) for i in range(N,0,-1):inv[i-1]=b=b*i%M n,*t=open(0).read().split() n=int(n) e=[[]for _ in range(n)] for a,b in zip(*[map(int,t)]*2): ...
Given are a positive integer N and a string S of length N consisting of lowercase English letters. Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T. Constraints * 1 \leq N \leq 100 * S consists of lowercase English letter...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner obj=new Scanner(System.in); int n=obj.nextInt(); String g=obj.next(); if(n%2!=0){ System.out.println("No"); }else{ int p=n/2; int q=p; int h=0; boolean flag=true; for(;h<p;h++,q++){ if(g.charAt(h)!=g.charAt(q)){ flag=false; } } ...
You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D. Constraints * 1\leq A\leq B\leq 10^{18} * 1\leq C,D\leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: A B ...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long a = sc.nextLong(); long b = sc.nextLong(); long c = sc.nextLong(); long d = sc.nextLong(); long e = lcm(c,d); long count = b-a+1; count -= b/c - (a-1)/c; count -...
Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane. You can use the following theorem: Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths...
#include<iostream> using namespace std; int m,s,l,i,a; int main(){ cin>>a; while(a--){ cin>>l; if(m<l)m=l; s+=l;} puts(s>m*2?"Yes":"No");}
The number 105 is quite special - it is odd but still it has eight divisors. Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)? Constraints * N is an integer between 1 and 200 (inclusive). Input Input is given from Standard Input in the following...
#!/usr/bin/env python from collections import deque import itertools as it import sys import math sys.setrecursionlimit(10000000) N = input() if N < 105: print 0 elif N < 135: print 1 elif N < 165: print 2 elif N < 189: print 3 elif N < 195: print 4 else: print 5
Constraints * H is an integer between 2 and 50 (inclusive). * W is an integer between 2 and 50 (inclusive). * s_{i, j} is `.` or `#` (1 \leq i \leq H, 1 \leq j \leq W). * s_{1, 1} and s_{H, W} are `.`. Input Input is given from Standard Input in the following format: H W s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W} s_{2,...
from collections import deque h,w = map(int,input().split()) maze = [] visited = [[0]*(w) for _ in range(h)] mx = 0 for _ in range(h): s = input() mx += s.count('.') maze.append(list(s)) sy,sx = 0, 0 gy, gx = h-1, w-1 que = deque([(sy,sx,1)]) while que: y,x,c = que.popleft() if visited[y][x] != 0: ...
Ringo got interested in modern art. He decided to draw a big picture on the board with N+2 rows and M+2 columns of squares constructed in the venue of CODE FESTIVAL 2017, using some people. The square at the (i+1)-th row and (j+1)-th column in the board is represented by the pair of integers (i,j). That is, the top-le...
#include <bits/stdc++.h> using namespace std; const int N = 301010; const int MOD = 998244353; const int INV = (MOD + 1) >> 1; typedef long long ll; char S[N]; int fac[N << 2], inv[N << 2]; int v[N][2], h[N][2]; int pre[N], suf[N], p2[N]; int n, m, lim, ans; inline void Mod(int &x) { while (x >= MOD) x -= MOD; } in...
Input Format N K a_1 a_2 a_3 ... a_N Output Format Print the minimum cost in one line. In the end put a line break. Constraints * 1 ≤ K ≤ N ≤ 15 * 1 ≤ a_i ≤ 10^9 Scoring Subtask 1 [120 points] * N = K Subtask 2 [90 points] * N ≤ 5 * a_i ≤ 7 Subtask 3 [140 points] * There are no additional constraint...
#include<bits/stdc++.h> #define ll long long #define P pair<ll, ll> using namespace std; const ll inf = 1e18; int main(){ int n, k; cin >> n >> k; vector<ll>a(n); for(int i=0;i<n;i++) cin >> a[i]; ll ans = inf; for(int tmp=0;tmp<(1<<15);tmp++){ bitset<15>s(tmp); int cnt = 0; ...
There are N squares in a row, numbered 1 through N from left to right. Snuke and Rng are playing a board game using these squares, described below: 1. First, Snuke writes an integer into each square. 2. Each of the two players possesses one piece. Snuke places his piece onto square 1, and Rng places his onto square 2....
#include <iostream> #include <fstream> #include <set> #include <map> #include <string> #include <vector> #include <bitset> #include <algorithm> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <queue> #define mp make_pair #define pb push_back typedef long long ll; typedef long doubl...
Write a program which reads an integer n and prints the factorial of n. You can assume that n ≤ 20. Input An integer n (1 ≤ n ≤ 20) in a line. Output Print the factorial of n in a line. Example Input 5 Output 120
import java.util.Arrays; import java.util.Scanner; public class Main { private Scanner sc; public static void main(String[] args) { new Main(); } public Main() { sc = new Scanner(System.in); while (sc.hasNextLine() == true) { int nico = Integer.parseInt(sc.nextLine()); long ans = 1; for (in...
Prime numbers are widely applied for cryptographic and communication technology. A twin prime is a prime number that differs from another prime number by 2. For example, (5, 7) and (11, 13) are twin prime pairs. In this problem, we call the greater number of a twin prime "size of the twin prime." Your task is to crea...
r = 10001 sqrt = int(r**0.5) p = [1]*r twin = [0]*r p[0] = 0 p[1::2] = [0 for x in range(1,r,2)] for i in range(2,r,2): if p[i]: p[2*i+1::i+1] = [0 for x in range(2*i+1,r,i+1)] if p[i-2]: twin[i:i+300] = [i+1 for x in range(i,i+300)] while True: n = int(raw_input()) if n == 0: break print twin[n-1]-2,twin...
Finally, "Hayabusa2" will be launched at the end of this month. When Hayabusa came back four years ago, I think many people remember the excitement all over Japan. Seven years ago, "Kaguya" was launched and sent many clear images to the earth while orbiting the moon. <image> The figure above shows the orbit of the m...
#include <bits/stdc++.h> using namespace std; struct P{ double x,y,z; }; P operator + (P a,P b){ a.x += b.x; a.y += b.y; a.z += b.z; return a; } double pi = acos(-1); int main(){ double m,t; cin >> m >> t; m = m / 180 * pi; t *= 60; double tot = 0; for(double ms = 0 ; ms < t ; ms += 1.0){ P mo,ka; m...
problem Santa Claus came from the sky to JOI town this year as well. Since every house in JOI has children, this Santa Claus must give out presents to every house in JOI. However, this year the reindeer I am carrying is a little deaf and I can only get off the top of the building, so it seems that I have to devise a l...
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <map> #include <string> #define F first #define S second using namespace std; int n,m; int c; int f[22][22]; typedef pair<int,int> P; vector<P> v; int dx[] = {0,0,1,-1}; int dy[] = {1,-1,0,0}; bool used[33]; map<P,...
She was worried. The grades are not good. Although she forced her parents to enroll in a dormitory school, her talent never blossomed. Or maybe he didn't have the talent in the first place, but it was possible that he didn't want to think about it as much as possible. So she relied on the dubious brain training materi...
//27 #include<iostream> using namespace std; char s[501]; int i; bool cls(){ int ap[128]={}; bool r=true; for(int j=0;j<3;j++){ int f=1; if(s[i]=='~'){ f=-1; i++; } r&=ap[s[i]]*-1!=f; ap[s[i]]=f; i+=2; } i--; return r; } bool exp(){ if(s[i]=='\0'){ return false;...
At the risk of its future, International Cellular Phones Corporation (ICPC) invests its resources in developing new mobile phones, which are planned to be equipped with Web browser, mailer, instant messenger, and many other advanced communication tools. Unless members of ICPC can complete this stiff job, it will eventu...
#include<bits/stdc++.h> using namespace std; int N; struct Trie { struct node { node(){ memset(v,-1,sizeof(v)); ef = false; } node(char c):c(c){ memset(v,-1,sizeof(v)); ef = false; } ~node(){} char c; int v[28]; bool ef; }; node* root; void init(){ ...
Example Input 3 3 1 2 4 1 2 2 3 3 1 Output IMPOSSIBLE
#if 1 #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <queue> #include <stack> #include <array> #include <deque> #include <algorithm> #include <utility> #include <cstdint> #include <functional> #include ...
Problem Given the strings S and Q queries. The i-th query (0 ≤ i ≤ Q-1) is given the closed interval [li, ri] and the string Mi. Output how many character strings Mi exist in the substring from the li character to the ri character of S. Constraints * 1 ≤ | S | ≤ 100000 * 1 ≤ Q ≤ 100000 * 1 ≤ | Mi | ≤ 100000 (0 ≤ i ≤...
#include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #include <limits> #include <functional> #define re...
You were caught in a magical trap and transferred to a strange field due to its cause. This field is three- dimensional and has many straight paths of infinite length. With your special ability, you found where you can exit the field, but moving there is not so easy. You can move along the paths easily without your ene...
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <string> #include <cmath> #include <cassert> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define ...
There is a frog living in a big pond. He loves jumping between lotus leaves floating on the pond. Interestingly, these leaves have strange habits. First, a leaf will sink into the water after the frog jumps from it. Second, they are aligned regularly as if they are placed on the grid points as in the example below. <i...
#include <cstdio> #define REP(i,n) for(int i=0; i<(int)(n); i++) #define IN(x,s,g) ((x) >= (s) && (x) < (g)) #define ISIN(x,y,w,h) (IN((x),0,(w)) && IN((y),0,(h))) using namespace std; int h, w; int g[10][10]; int cnt; const int _dx[] = {0,1,0,-1}; const int _dy[] = {-1,0,1,0}; const char *toS = "URDL"; char ans[5...
The king demon is waiting in his dungeon to defeat a brave man. His dungeon consists of H \times W grids. Each cell is connected to four (i.e. north, south, east and west) neighboring cells and some cells are occupied by obstacles. To attack the brave man, the king demon created and sent a servant that walks around in...
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 500 + 5; const int M = 20; const int V = 500 * 15 + 5; const int MOD = (int)1e9 + 7; struct Matrix { long long a[V][M * 3]; long long& getEntry(int x, int y) { return a[x][y - x + M]; } bool haveEnt...
Problem Statement The Animal School is a primary school for animal children. You are a fox attending this school. One day, you are given a problem called "Arithmetical Restorations" from the rabbit teacher, Hanako. Arithmetical Restorations are the problems like the following: * You are given three positive integers...
#include <bits/stdc++.h> using namespace std; #define fi first #define se second #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define each(itr,v) for(auto itr:v) #define pb(s) push_back(s) #define mp(a,b) make_pair(a,b) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x...
Example Input 4 5 3 -10 -10 10 -10 10 10 -10 10 1 2 1 3 1 4 2 3 3 4 -20 0 1 0 20 0 Output No Yes No
#include<cstdio> #include<algorithm> #include<vector> #include<set> #define N_ 101000 #define sz(x) ((int)x.size()) using namespace std; int n, m; struct point { long long x, y; point operator -(const point &p)const { return { x - p.x,y - p.y }; } bool isPos() const{ return (x > 0) || (x == 0 && y > 0); } }w[N...
In 21XX, an annual programming contest, Japan Algorithmist GrandPrix (JAG) has become one of the most popular mind sports events. JAG is conducted as a knockout tournament. This year, $N$ contestants will compete in JAG. A tournament chart is represented as a string. '[[a-b]-[c-d]]' is an easy example. In this case, t...
#include<algorithm> #include<iostream> #include<cstring> #include<cstdio> using namespace std; int n,len; int cnt[30]; char s[100010]; int solve(int l,int r) { if(l==r) return s[l]-'a'+1; if(r-l+1==5) { int x=s[l+1]-'a'+1,y=s[r-1]-'a'+1; if(!cnt[x]&&!cnt[y]) return -1; if(cnt[x]&&cnt[y]) return -1; ...
Problem N people with IDs from 1 to N are about to sit in N-legged chairs with numbers from 1 to N. The person with ID i wants to sit in the chair pi. N people are lined up in a row in ascending order of ID, and the first person in the row takes the following actions. 1. If no one is sitting on the chair pi, sit on ...
#include <cstdio> #include <vector> #include <stack> int main() { int N, p; scanf("%d", &N); std::vector<int> s(N, -1); std::vector<std::stack<int>> G(N); for (int i = 0; i < N; i++) { scanf("%d", &p); s[p - 1] += 1; G[p - 1].push(i); } for (int i = 1; i < ...
The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure. <image> For a given chess board where $k$ queens are already placed, find ...
from itertools import product def setq(ri,ci,krc): for ir in range(8): if ir!=ri: if krc[ir*8+ci]=="Q": return False,krc else: krc[ir*8+ci]="X" for ic in range(8): if ic!=ci: if krc[ri*8+ic]=="Q": return False,k...
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively. Constraints * $0 \leq S \leq 86400$ Input An integer $S$ is given in a line. Output Print $h$, $m$ and $s$ separated by ':'. You do not n...
s=int(raw_input()) a=s/3600 s%=3600 b=s/60 s%=60 print str(a)+":"+str(b)+":"+str(s)
Let X be the set of all integers between 0 and n-1. Suppose we have a collection S1, S2, ..., Sm of subsets of X. Say an atom A is a subset of X such that for each Si we have either A is a subset of Si or A and Si do not have any common elements. Your task is to find a collection A1, ..., Ak of atoms such that every ...
# CodeChef # Practice # Easy # Breaking Into Atoms ntc = int(raw_input()) for cti in range(ntc): ec, sc = map(int, raw_input().split()) el = [0] * ec for si in range(sc): sb = 1 << si sl = map(int, raw_input().split()[1:]) for se in sl: el[se] |= sb print len(set...
Rohit just started his 3rd semester classes in DMS. One of the interesting parts of DMS is set theory. He has just learnt about Power Set of any set, which is the number of ways in which you can create a unique subset from the existing set. Two subsets are said to be different if atleast one element in both the subsets...
t= input() for _ in range(t): res= input() print pow(2, res, 1000000007)
While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If the quantity and price per item are input, write a program to calculate the total expenses. Input The first line contains an integer T, total number of test cases. Then follow T lines, each line contains inte...
DEBUG = False def print_debug(s): if DEBUG: print str(s); def calculate(quantity, price): return (quantity * price) * (0.9 if quantity > 1000 else 1.0) def run(): print_debug('Number of entries:') lines = int(raw_input()) while (lines > 0): print_debug("Entry in format '%f %f' as 'quantit...
Problem Statement Lelouch is one of the famous business men in Japan. One day on his way from 'Tokyo' to 'Kyoto', His vehicle is supposed to cross a CheckPoint. CheckPoint has N gates and at i th gate there are already X_i vehicles standing in a queue. There are only four types of Vehicles at the Check Point i.e Scoote...
import sys n = int(sys.stdin.readline()) sys.stdin.readline() times = {'S': 1, 'C': 2, 'B': 3, 'T': 4} minn = 1000000 minni = 0 for i in xrange(n): summ = sum([times[j] for j in sys.stdin.readline().split()]) if summ < minn: minn, minni = summ, i print minni + 1
Polo, the Penguin, likes numbers. He says that the goodness of a number is itself multiplied by the number of digits in it's decimal representation. For example, the goodness of the integer 474 is 474*3 = 1422. Help him to count the sum of goodness of all integers from L to R, inclusive. Since the answer can be too lar...
import sys import math t= int(sys.stdin.readline()) while(t>0) : t = t-1 l,r = sys.stdin.readline().split(' ') l = int(l) r = int(r) cat1 = int(math.log10(l)); cat2 = int(math.log10(r)); if cat1==cat2: sum = (r*(r+1)/2 - (l*(l-1)/2))*(cat1+1); print sum%1000000007 else: cat1 = cat1+1 num1 = pow(10,cat...
Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow)   Input Input will start with an integer T the count of test cases, each case will have an integer N.   Output Output each values, on a newline.   Constraints...
import math for _ in range(input()): n=input() s=int(math.floor(n//10)) print ((s*(s+1))/2)*10
Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he as...
#include <bits/stdc++.h> using namespace std; set<int> s, part[2]; int par[605], dep[605]; vector<int> v[605], a; int ask() { if (a.size() <= 1) return 0; printf("? %d\n", a.size()); for (int i : a) printf("%d ", i); printf("\n"); fflush(stdout); int ans; scanf("%d", &ans); assert(ans != -1); return a...
Don't you tell me what you think that I can be If you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct h...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; set<pair<int, int>> ps; vector<int> po(2 * n), sc(2 * n); for (int i = 0; i < 2 * n; i++) { cin >> po[i]; sc[i] = po[i]; } map<int, int> opp; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--...
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 N = 3e5 + 10; const int inf = 1e9; int gi() { int x = 0, o = 1; char ch = getchar(); while ((ch < '0' || ch > '9') && ch != '-') ch = getchar(); if (ch == '-') o = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); ...
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; vector<long long> v[N]; long long pre[N], ans[N], val[N], level[N]; bool p = 1; void dfs1(long long node, long long par) { level[node] = level[par] + 1; for (auto it : v[node]) { if (it != par) dfs1(it, node); } } void dfs2(long long node, l...
Little Petya loves training spiders. Petya has a board n × m in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to som...
#include <bits/stdc++.h> using namespace std; const int maxS = (1 << 6) + 5; const int maxn = 40 + 5; int n, m; int blankcnt[maxS], dp[maxn][maxS][maxS]; bool check(int S, int S1, int S2) { return ((S | (S << 1) | (S >> 1) | S1 | S2) & ((1 << m) - 1)) == ((1 << m) - 1); } int bitcount(int S) { int ret = 0;...
You are given a set of n points in a 2D plane. No three points are collinear. A pentagram is a set of 5 points A,B,C,D,E that can be arranged as follows. <image> Note the length of the line segments don't matter, only that those particular intersections exist. Count the number of ways to choose 5 points from the give...
#include <bits/stdc++.h> using namespace std; inline void update(long long &x, long long y) { x += y; } struct Point { long long x, y; Point() {} Point(long long a, long long b) : x(a), y(b) {} Point operator-(Point b) { return Point(x - b.x, y - b.y); } bool operator<(const Point &b) const { return (x !=...
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n. In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i...
def check(mid,arr,n,m): prev=0 for i in range(n): if(arr[i]>prev): t=m-(arr[i]-prev) if(t>mid): prev=arr[i] else: t=prev-arr[i] if(t>mid): return False return True n,m=map(int,input().split()) arr=list(map(int,input().split())) lo=0 hi=m while(lo<=hi): mid=(lo+hi)//2 if(check(mid,arr,n,m)):...
Vus the Cossack has n real numbers a_i. It is known that the sum of all numbers is equal to 0. He wants to choose a sequence b the size of which is n such that the sum of all numbers is 0 and each b_i is either ⌊ a_i ⌋ or ⌈ a_i ⌉. In other words, b_i equals a_i rounded up or down. It is not necessary to round to the ne...
import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class D { static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static MyScanner sc = new MyScanner(); public static void main(String[] args) { doTask(); ou...
This is an interactive problem You are given a grid n× n, where n is odd. Rows are enumerated from 1 to n from up to down, columns are enumerated from 1 to n from left to right. Cell, standing on the intersection of row x and column y, is denoted by (x, y). Every cell contains 0 or 1. It is known that the top-left ce...
#include <bits/stdc++.h> using namespace std; const int MAXN = 60; int N; int V[MAXN][MAXN]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> N; memset(V, -1, sizeof(V)); V[0][0] = 1; V[N - 1][N - 1] = 0; V[0][1] = 1; auto query = [&](int x1, int y1, int x2, int y2) { if (V[x...
You are given an undirected graph with n vertices and m edges. You have to write a number on each vertex of this graph, each number should be either 0 or 1. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge. You have to choose the numbers you will write on the ve...
#include <bits/stdc++.h> using namespace std; const int maxS = 1 << 21; const int maxn = 50; long long ans, con[maxn]; int n, m, fa[maxn], col[maxn], num[maxS]; int nl, nr, cnt1, cnt2 = 1; vector<int> G[maxn]; int find(int a) { return fa[a] == a ? a : fa[a] = find(fa[a]); } int check(int u) { for (int v : G[u]) { ...
This is an easier version of the problem. In this version, n ≤ 500. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believe...
#include <bits/stdc++.h> using namespace std; const long long INF = 2e18; long long mdl = 1e9 + 7; int n; string s; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; cin >> s; int cur = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') cur++; else cur--; } if (cur != 0)...
There is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first...
#include <bits/stdc++.h> using namespace std; const int MAXN = 60; const long long MOD[2] = {1000000000000000009ll, 1000000000000000031ll}; int n, q, v; int B[MAXN]; int R[MAXN]; long long ans; long long b[MAXN]; long long x[2][MAXN]; long long a[2][MAXN][MAXN]; long long inv[2][MAXN][MAXN]; char s[MAXN]; bool vis[MAXN...
You are given two integers n and m. Calculate the number of pairs of arrays (a, b) such that: * the length of both arrays is equal to m; * each element of each array is an integer between 1 and n (inclusive); * a_i ≤ b_i for any index i from 1 to m; * array a is sorted in non-descending order; * array b ...
#include <bits/stdc++.h> using namespace std; int mod = 1e9 + 7; long long binpow(long long a, long long n) { if (n == 0) return 1; if (n % 2 == 1) return (binpow(a, n - 1) * a) % mod; else { long long b = binpow(a, n / 2); return (b * b) % mod; } } int main() { std::cin.tie(0); std::ios::sync_w...
Input The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive. Output Output "YES" or "NO". Examples Input GENIUS Output YES Input DOCTOR Output NO Input IRENE Output YES Input MARY Output NO Input SMARTP...
z="QWERTYUIOPASDFGHJKLZXCVBNM" t="01101101001001010111101011" s = input() cur = '-' for i in s: for j in range(26): if z[j] == i: if cur == '-': cur = t[j] elif t[j] != cur: print('NO') exit(0) print('YES')
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
import sys num_lines = int(input()) for i in range(num_lines): cont = 0 resp = '' whole_number = sys.stdin.readline().strip('\n') length = len(whole_number) - 1 for idx, k in enumerate(whole_number): if k != '0': cont += 1 num = int(k) * 10 **(length - ...
This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x ...
import java.io.*; import java.util.*; public class e1 { public static PrintWriter out; public static InputReader in; public static int minx,maxx; public static void sub(int x, int arr[], int p, HashSet<Integer> set){ // int less = 0; ArrayList<Long> list = new ArrayList<Long>(); int parr[] = new int[p]; A...
Boboniu defines BN-string as a string s of characters 'B' and 'N'. You can perform the following operations on the BN-string s: * Remove a character of s. * Remove a substring "BN" or "NB" of s. * Add a character 'B' or 'N' to the end of s. * Add a string "BN" or "NB" to the end of s. Note that a strin...
#include <bits/stdc++.h> using namespace std; int n, a[500005], b[500005]; char s[500005]; int res = 1e9, xx, yy; int calc2(int x, int y) { if (x == 0 && y == 0) return 1000000000; int ans = 0; for (int i = 1; i <= n; i++) { if (x <= a[i] && y <= b[i]) ans = max(ans, max(a[i] - x, b[i] - y)); else i...
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
for _ in range(int(input())): a = int(input()) number = input() raze = [0,0] #odd,even breach = [0,0] #odd,even count = 0 while count<len(number): if count%2==0: if int(number[count])%2==0: raze[1]+=1 else: raze[0]+=1 ...
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
for _ in range(int(input())): a,b = map(int,input().split()) aa = a%(b+1);bb = b%(b+1) if(aa>=(b+1)/2 and bb>=(b+1)/2): print("YES") else: print("NO")
In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. <image>...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java....
You are given a tree consisting of n vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 ≤ i < j ≤ m) such that path_i and path_j have exactly one vertex in common. Input First line conta...
#include <bits/stdc++.h> #define all(a) a.begin(), a.end() #define sz(a) (int)a.size() using namespace std; typedef long long int ll; typedef long double ld; typedef pair<int,int> pii; void sol() { int N; cin >> N; vector<vector<int>> adj(N); for(int i = 0; i < N-1; i++) { int u, v; cin >> u >> v; u--; v--; ...
You are given a set of n segments on a line [L_i; R_i]. All 2n segment endpoints are pairwise distinct integers. The set is laminar — any two segments are either disjoint or one of them contains the other. Choose a non-empty subsegment [l_i, r_i] with integer endpoints in each segment (L_i ≤ l_i < r_i ≤ R_i) in such ...
#include<bits/stdc++.h> #define ll long long #define mp make_pair #define all(x) x.begin(),x.end() #define pii pair<int,int> template <typename T1,typename T2> inline void chmax(T1 &x,const T2 &b) {(x=x>b?x:b);} const int inf=1039714778; const ll llinf=1LL*inf*inf; using namespace std; int n; int l[2005]; int r[2005];...
Polycarp has n friends, the i-th of his friends has a_i candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all a_i to be the same. To solve this, Polycarp performs the following set of actions exactly once: * Polycarp chooses k (0 ≤ k ≤ n) arbitrary friends...
import sys,os,io from sys import stdin,stdout from math import log, gcd, ceil from collections import defaultdict, deque, Counter from heapq import heappush, heappop from bisect import bisect_left , bisect_right import bisect import math input = stdin.readline alphabets = list('abcdefghijklmnopqrstuvwxyz') def isPr...
Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them). Polycarpus wants to save these pictures o...
#include <bits/stdc++.h> using namespace std; int a, b; int L1[1 << 20], L2[1 << 20]; int pos[1 << 20]; int res = 0; int main() { memset(pos, -1, sizeof(pos)); scanf("%d%d", &a, &b); for (int i = 0; i < a; ++i) scanf("%d", &L1[i]); for (int i = 0; i < b; ++i) { scanf("%d", &L2[i]); pos[L2[i]] = i; } ...
The Fat Rat and his friend Сerealguy have had a bet whether at least a few oats are going to descend to them by some clever construction. The figure below shows the clever construction. <image> A more formal description of the clever construction is as follows. The clever construction consists of n rows with scales. ...
#include <bits/stdc++.h> using namespace std; long int table[51][51][51][51]; int maxWeights[51][51]; int n; int main() { memset(table, 0, sizeof table); memset(maxWeights, 0, sizeof maxWeights); scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &table[0][i][i][i]); for (int i = 0; i < n; i++) for ...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
import java.util.*; public class cf207d { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if(n <= 1000) System.out.println(1); else if(n <= 3000) System.out.println(2); else System.out.println(3); } }
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1...
import java.util.*; import java.io.*; public class MagicBox { /************************ SOLUTION STARTS HERE ************************/ static final double EPS = 1e-8; static int compare(double a , double b) { if(a <= b - EPS) return -1; else if(a >= b + E...
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this a...
import java.io.*; import java.util.*; import java.text.*; import static java.lang.System.out; public class acm { public static void main( String[ ] args ) { Scanner in = new Scanner( ) ; DecimalFormat df = new DecimalFormat( ".##########" ) ; int n = in.nextInt( ) ; double [ ] a = new double [ n ] ; for( in...
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree. The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtre...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const int N = 1e5 + 5; int n; vector<int> g[N]; long double dfs(int node, int par, int lvl) { long double ans = 1.0 / lvl; for (auto &i : g[node]) if (i != par) ans += dfs(i, node, lvl + 1); return ans; } int main() { ios_base::sync_wi...
You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (x, y) (0 ≤ x ≤ n, 0 ≤ y ≤ m). Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (...
from fractions import gcd n, m, x, y, a, b = map(int, input().split()) r = gcd(a, b) a, b = a // r, b // r r = min(n // a, m // b) a, b = a * r, b * r cx, cy = (a + 1) // 2, (b + 1) // 2 dx, dy = min(n - a, max(cx, x) - cx), min(m - b, max(cy, y) - cy) print(dx, dy, a + dx, b + dy) # Made By Mostafa_Khaled
It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to s centimeters. A flea has found herself at the center of some cell of the checked board of the size n × m centimeters (each cell is 1 × 1 centimeters). She can jump as she wishes for an arbitrary n...
#include <bits/stdc++.h> using namespace std; long long int r[1000002], c[1000002]; int main() { ios_base::sync_with_stdio(false); long long int n, m, s; cin >> n >> m >> s; long long int i, max1 = -1, max2 = -1, cnt = 0, cnt2 = 0; for (i = 1; i <= n; i++) { r[i % s]++; } for (i = 1; i <= m; i++) { ...
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: * choose indexes i and j (i ≠ j) that haven't been chosen yet; * round elemen...
import java.util.*; public class Jeff { public static void main (String [] arg) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double [] s = new double [(int)2*n]; boolean [] isInt = new boolean[(int)2*n]; int n0 = 0; long sumMin = 0; long sumMax = 0; double sumT = 0; for (int i = 0; i<...
You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix a are numbered from 1 to n ...
#include <bits/stdc++.h> using namespace std; long long int expo(long long int x, long long int n, long long int M) { long long int res = 1; while (n) { if (n % 2) { res = (res * x) % M; } x = (x * x) % M; n /= 2; } return res; } void solve() { long long int n, m; cin >> n >> m; vect...
Let's assume that * v(n) is the largest prime number, that does not exceed n; * u(n) is the smallest prime number strictly greater than n. Find <image>. Input The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases. Each of the following t lines of the input contains integer n (2 ≤ n ≤ ...
import java.io.*; import java.util.*; import java.math.BigInteger; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int p = n; int q = n + 1; while (!isPrime(p)) --p; ...
During a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three...
import java.io.*; import java.util.*; public class Solution { StreamTokenizer in; PrintWriter out; public static void main(String[] args) throws Exception { new Solution().run(); } public void run() throws Exception { in = new StreamTokenizer(new BufferedReader(new InputStreamRea...
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1 = 1; F2 = 1; Fn = Fn - 1 + Fn - 2 (n > 2). DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1, a2, ..., an. Moreover, there are m queries, each query has one of the two t...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; const long long MOD = 1e9 + 9; long long sum[N << 2], lazy1[N << 2], lazy2[N << 2], F[N]; inline void read(long long &x) { int f = 1; x = 0; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); ...
Little X has a tree consisting of n nodes (they are numbered from 1 to n). Each edge of the tree has a positive length. Let's define the distance between two nodes v and u (we'll denote it d(v, u)) as the sum of the lengths of edges in the shortest path between v and u. A permutation p is a sequence of n distinct int...
#include <bits/stdc++.h> using namespace std; int n, mn[1000000], root, hson[1000000]; int timer, size[1000000], sum[1000000]; int dfn[1000000], id[1000000], gra[1000000]; long long dis[1000000]; set<pair<int, int> > s; set<pair<int, int> >::iterator it; int read() { int x = 0, k = 1; char c; c = getchar(); whi...
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1 × b1 segments large and the second one is a2 × b2 segments large. Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself...
def decomp(a): cnt2 = 0 while a%2==0: a = a//2 cnt2 += 1 cnt3 = 0 while a%3==0: a = a//3 cnt3 += 1 return a,cnt2,cnt3 def cut(a,b,d,p): while d>0: if a%p==0: a = (p-1)*a//p d = d-1 elif b%p==0: b = (p-1)*b//p ...
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the...
import java.io.*; import static java.lang.Double.*; import static java.lang.Math.*; import java.util.*; import static javafx.scene.input.KeyCode.S; public class Mao { static Reader in=new Reader (); static long ans,mz=0,mx=(long) (pow(10,9)+7); static int a[],b[][]; static StringBuilder sd=new StringBuilder(); pu...
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting seq...
#include <bits/stdc++.h> using namespace std; long long in() { int32_t x; scanf("%d", &x); return x; } inline long long lin() { long long x; scanf("%lld", &x); return x; } const long long maxn = 2e5 + 10; const long long mod = 1e9 + 7; map<long long, long long> mp, where; long long fen[maxn]; inline long lo...
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk. Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite ...
a,b,c=raw_input().split() a=int(a) b=int(b) c=int(c) num = 0 while b<a : num = num + 1 b = b*c print num
BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one sep...
#include <bits/stdc++.h> using namespace std; int main() { int n, m = 0; cin >> n; string s[n]; for (int i = 0; i < n; i++) cin >> s[i]; char t; cin >> t; for (int i = 0; i < n; i++) s[i] += t, m += s[i].size(); m /= (n / 2); sort(s, s + n); for (int i = 0; i < n; i++) for (int j = i + 1; j < n;...
Limak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with h rows and w columns. Each cell is an empty square. He is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot. A cleaning robot has a...
import java.util.*; import java.io.*; public class f { public static void main(String[] arg) throws IOException { new f(); } long MOD = 1_000_000_007; public f() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int r ...
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands o...
#include <bits/stdc++.h> using namespace std; template <class T> inline T BM(T p, T e, T M) { long long int ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } ...
You are given an array of n elements, you must make it a co-prime array in as few moves as possible. In each move you can insert any positive integral number you want not greater than 109 in any place in the array. An array is co-prime if any two adjacent numbers of it are co-prime. In the number theory, two integer...
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main (String[...
Author has gone out of the stories about Vasiliy, so here is just a formal task description. You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: 1. "+ x" — add integer x to multiset A. 2. "- x" — erase one occurrence of integer x from multiset A. It's g...
import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CandidateCode { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); root=new TrieNode(); addDelete(0,fa...
This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and dec...
#include <bits/stdc++.h> using namespace std; int n, ar[4005], tr[4005]; int dp[2200][90][90]; int func(int, int, int), sub(int, int, int, int, int); int main() { memset(dp, -1, sizeof(dp)); scanf("%d", &n); for (int i = 1; i < n + 1; i++) scanf("%d", &ar[i]); for (int i = 1; i < n + 1; i++) tr[i] += tr[i - 1] ...
A stowaway and a controller play the following game. The train is represented by n wagons which are numbered with positive integers from 1 to n from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const double eps = 1e-6; char can[2][300]; int main() { int n, m, k; cin >> n >> m >> k; string sa, sb; cin >> sa >> sb; string a; cin >> a; int dir = 1; if (sb[0] == 'h') dir = -1; m--; k--; can[0][m] = 1; if (m == k) { ...
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y. Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s...
#include <bits/stdc++.h> using namespace std; bool check(long long x, long long y, long long p, long long q, long long t) { return p * t >= x && q * t - p * t >= y - x; } void solve() { long long x, y, p, q; scanf("%lld%lld%lld%lld", &x, &y, &p, &q); long long l = -1; long long r = (long long)1e9; if (!chec...
One day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor. The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole — at coordinate pj. jth hole...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXHOLE = 5000; const int MAXMOUSE = 5000; const int MAXLG = 12; int nmouse, nhole; int cnt[MAXHOLE]; int hole[MAXHOLE]; int mouse[MAXMOUSE]; long long mousesum[MAXMOUSE + 1]; int fst[M...
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it. The game consists of m steps. On each step the current leader with index i counts out ai...
#include <bits/stdc++.h> using namespace std; int a[105], v[105]; bool used[105]; int main() { int n, m; scanf("%d %d", &n, &m); scanf("%d", &v[1]); for (int i = 2; i <= m; i++) { scanf("%d", &v[i]); int dif = v[i] - v[i - 1]; if (dif <= 0) dif += n; if (used[dif] && a[v[i - 1]] != dif) { ...
You are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied: 1. Th...
#include <bits/stdc++.h> using namespace std; const int c = 200002; int n, f[c], rf[c], h, l, ki, ut; vector<int> sz[c]; vector<pair<int, pair<int, int> > > sol; bool v1[c], v2[c], cen[c]; void add(int x, int y1, int y2) { sol.push_back({x, {y1, y2}}); } void dfs1(int a) { v1[a] = true, rf[a] = 1; int maxi = 0; f...
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card. Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num...
#python3 #utf-8 from collections import Counter cards_nr = int(input()) number_counter = Counter() for _ in range(cards_nr): curr_number = int(input()) number_counter[curr_number] += 1 if len(number_counter) != 2: print('NO') else: num1, num2 = list(number_counter) if number_counter[num1] != numb...
You are given a sequence of integers a1, a2, ..., an. Let <image>, and <image> for 1 ≤ i < n. Here, <image> denotes the modulus operation. Find the maximum value of f(x, 1) over all nonnegative integers x. Input The first line contains a single integer n (1 ≤ n ≤ 200000) — the length of the sequence. The second lin...
#include <bits/stdc++.h> using namespace std; set<pair<long long, long long>> dp; long long a[200200]; void add(long long u, long long y) { auto it = dp.lower_bound(make_pair(u, -1)); if (it == dp.end() || it->first != u) { dp.insert({u, y}); return; } long long x = it->second; if (x >= y) return; d...
A lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerines — the leftovers from New Year celebration — he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun. Perun has an ultimate abi...
#include <bits/stdc++.h> using namespace std; struct Enemy { long long maxH; long long regen; long long curH; long long curT; long long getHealth(long long t) const { assert(t >= curT); return min(maxH, curH + (t - curT) * regen); } long long findTime(long long dam) const { if (curH > dam) { ...
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon. A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, th...
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + 9; const long long mod = 1e9 + 7; vector<bool> prime(MAX, 1); vector<int> spf(MAX, 1), primes; void sieve() { prime[0] = prime[1] = 0; spf[2] = 2; for (long long i = 4; i < MAX; i += 2) { spf[i] = 2; prime[i] = 0; } primes.push_back(2...
Given a tree with n nodes numbered from 1 to n. Each node i has an associated value V_i. If the simple path from u_1 to u_m consists of m nodes namely u_1 → u_2 → u_3 → ... u_{m-1} → u_{m}, then its alternating function A(u_{1},u_{m}) is defined as A(u_{1},u_{m}) = ∑_{i=1}^{m} (-1)^{i+1} ⋅ V_{u_{i}}. A path can also h...
#include <bits/stdc++.h> using namespace std; vector<int> krawedzie[200007]; long long waga[200007]; int ojciec[200007]; int warstwa[200007]; long long parz = 0; long long nparz = 0; long long wynik = 0; void dfs1(int u) { if (warstwa[u] % 2 == 0) { parz++; } else { nparz++; } for (int i = 0; i < krawed...
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
n=int(raw_input()) l=[] for i in range(n): s=raw_input() l.append(s) l.sort(key=len) flag=1 for i in range(len(l)): for j in range(i,len(l)): if l[i] not in l[j]: flag=0 if(flag==1): print("YES") for i in l: print i else: print("NO")
Given an array a of N integers a1, a2, a3, ... aN you have to find the longest alternating sub-sequence of this array . An alternating sequence b1, b2 ... bk, k ≥ 1 is a sequence that has the 2 following properties: 1.|b1|<|b2|<|b3|<.....<|bk| 2. The signs alternate between adjacent elements, i.e, if b1 > 0 then b2<...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' import math n=int(raw_input()) arr=map(int,raw_input().split(' ')) matrix=[1]*(n) for j in range(n): for i in range(j): if (arr[j] > 0 and arr[i] <0) and abs(arr[j]) > abs(a...
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers: •Emergency 911 •Vidhant 97625 99944 •Bob 91125 42682 In this case, it’s not possible to call Bob, because the central would direct your call to the emerg...
from sys import stdin t = int(stdin.readline()) for tt in xrange(t): n = int(stdin.readline()) a = [] for i in xrange(n): x = stdin.readline().strip() a.append(x) valid = 1 a.sort() for i in xrange(n-1): for j in xrange(i+1,i+2): if a[j].startswith(a[i]): valid = 0;break if valid==0: break if v...
Dee Dee went to market to buy some eggs. There are 2 type of egg cartons available in the shop. One type contains 6 eggs and the other type contains 8 eggs. Dee Dee wants to buy exactly N eggs. Calculate the minimal number of egg cartons she must buy. INPUT First line of input gives T, the number of test cases. T lin...
x=input() for i in range(0,x): y=input() c=0 t=y while True: if t%8==0: t-=8 c+=1 elif t%6==0: t-=6 c+=1 else: t-=8 c+=1 if t==0: print c break if t<6: print "-1" break