input
stringlengths
29
13k
output
stringlengths
9
73.4k
On the way to Lanka, Ram and co encountered another interesting path. The path was laid with numbered rocks which were to be jumped over. The number denoted the maximum jump length that could be made by the person standing on that rock. For instance, if Ram was standing on a rock numbered 2, he could either make a jump...
t = int(raw_input()) while t: n = int(raw_input()) arr = [int(i) for i in raw_input().split()] dp = [0]*n for i in range(1,len(arr)): for j in range(i): if j + arr[j] >=i: if dp[i]==0: dp[i] = dp[j]+1 else: dp[i] = min(dp[j]+1,dp[i]) print dp[n-1] t-=1
Recently Ram got to know about a secret place where he can play many games to win lot of prize. Games are very easy, so he can easily win high prize, but he can play a limited number of games. He want to win the maximum amount of prize.So he wants to choose games, such that the prize money is maximum. Assume that he w...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=input() while t>0: t-=1 n,k=map(int,raw_input().split()) l=[int(i) for i in raw_input().split()] l.sort() p=l[::-1] s=0 if k>n: print sum(l) else: fo...
Miraya and her best Alice friend are now ending their studies and they are willing to work together in a software company, but before this Alice will be tested by the Miraya through the following procedure, Miraya is obviously Computer Science person while her best friend belongs to Arts. However, as Miraya didn't want...
def solve (bhavik): if (bhavik == 1): return 0 else: return (bhavik * bhavik)/2 - 1 t = input() for _ in xrange(t): n = input() ans = solve(int(n)) print ans
You are given an two integers i and j such that i ≤ j. Task is to find the sum of all integers from i to j (both inclusive). For example: i = 3 j = 5 then sum from i to j will be 3+4+5 = 12 Input: Single line containing two space separated integers i and j. Output: Print out the sum of integers from i to j (bo...
a,b=map(long,raw_input().split()) n=b-a+1 print (a+b)*n/2
Problem Statement As they say, small is cute and beautiful. Given N distinct positive integers, find the smallest number that can be formed by concatenating all of them. Input Format The first line of the input file contains a positive integer N. Then N lines follow. Each line contains a single positive integer K. Ou...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' def func(a,b): if(len(a) != len(b)): #a = int(a) #b = int(b) str1 = a + b str2 = b + a ...
Little PandeyG is a curious student, studying in HEgwarts. Being smarter, faster and displaying more zeal for magic than any other student, one by one he managed to impress the three hidden witches of the school. They knew his secret desire to be a warrior, so each of them gave him some super power to use if he's up fo...
def main(): for _ in xrange(input()): v=[] s=set() n=input() ans=0 v.append(n) i=0 f=0 j=1 while(f==0): if(n==1): break if(f==1): break ans+=1 for k in xrange(i,j): x = -1 y = -1 z = -1 if(v[k]%3==0): x=v[k]/3 ...
Given are integers a,b,c and d. If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y? Constraints * -10^9 \leq a \leq b \leq 10^9 * -10^9 \leq c \leq d \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the follo...
lines = map(int,input().split()) a,b,c,d = lines print(max(a*c,a*d,b*c,b*d))
The Kingdom of Takahashi has N towns, numbered 1 through N. There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i. Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K...
n, k = map(int, input().split()) a = list(map(int, input().split())) s = [] ord = [-1] * (n+1) v = 1 while ord[v] == -1: ord[v] = len(s) s.append(v) v = a[v-1] c = len(s) - ord[v] l = ord[v] ans = 0 if k < l: ans = s[k] else: k -= l k %= c ans = s[l+k] print(ans)
We have a string S of length N consisting of uppercase English letters. How many times does `ABC` occur in S as contiguous subsequences (see Sample Inputs and Outputs)? Constraints * 3 \leq N \leq 50 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: N S ...
n = input() print(input().count('ABC'))
There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N. We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V...
n,m,p = map(int, input().split()) edge = [] inv_link = [[] for _ in range(n)] link = [[] for _ in range(n)] for i in range(m): a,b,cost = list(map(int,input().split())) edge.append([a-1,b-1,p-cost]) link[a-1].append(b-1) inv_link[b-1].append(a-1) def bell(edges, start,num_v): cost = [float('inf')]...
On the Planet AtCoder, there are four types of bases: `A`, `C`, `G` and `T`. `A` bonds with `T`, and `C` bonds with `G`. You are given a letter b as input, which is `A`, `C`, `G` or `T`. Write a program that prints the letter representing the base that bonds with the base b. Constraints * b is one of the letters `A`...
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); if(s.equals("A")) System.out.println("T"); else if(s.equals("T")) System.out.print...
You are given an integer N. Determine if there exists a tuple of subsets of \\{1,2,...N\\}, (S_1,S_2,...,S_k), that satisfies the following conditions: * Each of the integers 1,2,...,N is contained in exactly two of the sets S_1,S_2,...,S_k. * Any two of the sets S_1,S_2,...,S_k have exactly one element in common. ...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int k=2; while(k*(k-1)/2 < n) k++; if(k*(k-1)/2 != n){ cout << "No" << endl; return 0; } int a[500][500]; int b[500]; for(int i=1; i<=k; i++)b[i]=0; int x=1; for(int i=1; i<=k; i++)...
Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order. From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized. If there are multiple pairs that maximize the value, any of them is accepted. Constraints * 2 ...
#coding:utf-8 N=input() A=map(int,raw_input().split()) A.sort() n=A[-1] med=n/2 p=0 mi=1145141919810 for i,a in enumerate(A): b=min(a,n-a) if abs(b-med) < mi: p=i; mi=abs(b-med) print("%d %d"%(n,A[p]))
Sitting in a station waiting room, Joisino is gazing at her train ticket. The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive). In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with `+` or `-` so that the formula holds. The given in...
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ solve(); } public static void solve(){ Scanner sc = new Scanner(System.in); int z = sc.nextInt(); int x = z; int a = x/1000; x -= x/1000*1000; int b = x/100; x -= x/100*100; int c = x/10; x -= x/...
You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0 ; i < n ; i++) a[i] = sc.nextInt(); boolean[][] dp = new boolean[101][10010]; dp[0][0] = true; for(int i = 0 ; i < n ; i++...
You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times: * Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`. Constrain...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); s = s.replaceAll("eraser", "").replaceAll("erase", "").replaceAll("dreamer", "").replaceAll("dream", ""); if(s.equals("")) { System.out.println("YES"); } else ...
Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct. He is sorting this sequence in increasing order. With supernatural power, he can perform the following two operations on the sequence in any order: ...
n,*a=map(int,open(0)) print(len(set(a[::2])^set(sorted(a)[::2]))//2)
Books are indexed. Write a program which reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers. You can assume that a word consists of at most 30 characters, and the page number is less than or equal to 1000. The number of pairs of a word and a page number ...
import java.util.Arrays; import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); ArrayList<String> str = new ArrayList<String>(); while(scan.hasNext()){ str.add(scan.nextLine()); } ...
Food contains three nutrients called "protein", "fat" and "carbohydrate", which are called three major nutrients. It is calculated that protein and carbohydrate are 4 kcal (kilocalories) and fat is 9 kcal per 1 g (gram). For example, according to the table below, the number 1 cake contains 7 g of protein, 14 g of fat a...
import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true){ final int n = sc.nextInt(); if(n == 0){ break; } int[][] items = new int[n][4]; for(in...
You are a famous adventurer and have already won two dungeons. You got a new dungeon map with some walkways and a treasure trove. The map shows the value of the treasure in each treasure chest. You can enter the dungeon from any treasure chest and escape the dungeon from any treasure chest. From invasion to escape, yo...
# include <iostream> # include <algorithm> #include <array> # include <cassert> #include <cctype> #include <climits> #include <numeric> # include <vector> # include <string> # include <set> # include <map> # include <cmath> # include <iomanip> # include <functional> # include <tuple> # include <utility> # include <stac...
There are two cameras which observe the up line and the down line respectively on the double lane (please see the following figure). These cameras are located on a line perpendicular to the lane, and we call the line 'monitoring line.' (the red line in the figure) <image> Monitoring systems are connected to the cam...
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ int i, n, m, x, max; vector<int> data; while(1){ cin >> n >> m; if(n == 0 && m == 0) break; for(i=0; i<n+m; ++i){ cin >> x; data.push_back(x); } sort(data.begin(), data.end()); for(i=...
The Balance of the World The world should be finely balanced. Positive vs. negative, light vs. shadow, and left vs. right brackets. Your mission is to write a program that judges whether a string is balanced with respect to brackets so that we can observe the balance of the world. A string that will be given to the p...
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()){ String s = sc.nextLine(); if(s.equals(".")) break; Stack<Character> count = new Stack<>(); boolean flag = t...
Do you know the famous series of children's books named "Where's Wally"? Each of the books contains a variety of pictures of hundreds of people. Readers are challenged to find a person called Wally in the crowd. We can consider "Where's Wally" as a kind of pattern matching of two-dimensional graphical images. Wally's ...
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <set> #include <map> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; st...
G, a college student living in a certain sky city, has a hornworm, Imotaro. He disciplined Imotaro to eat all the food in order with the shortest number of steps. You, his friend, decided to write a program because he asked me to find out if Imotaro was really disciplined. Input H W N area Input is given in H + ...
/* * h.cc: */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functi...
In 1936, a dictator Hiedler who aimed at world domination had a deep obsession with the Lost Ark. A person with this ark would gain mystic power according to legend. To break the ambition of the dictator, ACM (the Alliance of Crusaders against Mazis) entrusted a secret task to an archeologist Indiana Johns. Indiana ste...
#include <algorithm> #include <cmath> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> #include <cassert> #include <func...
This is a story of a world somewhere far from the earth. In this world, the land is parted into a number of countries ruled by empires. This world is not very peaceful: they have been involved in army race. They are competing in production of missiles in particular. Nevertheless, no countries have started wars for yea...
#include <cstdio> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloa...
``Domino effect'' is a famous play using dominoes. A player sets up a chain of dominoes stood. After a chain is formed, the player topples one end of the dominoes. The first domino topples the second domino, the second topples the third and so on. You are playing domino effect. Before you finish to set up a chain of d...
#include<cstdio> #include<complex> #include<vector> #include<cmath> #include<utility> #include<algorithm> using namespace std; const double eps=1e-9; template<class T> bool eq(T a,T b){ return abs(a-b)<eps; } template<class T> int sgn(T a){ return eq(a,0.0)?0:(a>0?1:-1); } typedef complex<double> Point; typedef...
At the school where the twins Ami and Mami attend, the summer vacation has already begun, and a huge amount of homework has been given this year as well. However, the two of them were still trying to go out without doing any homework today. It is obvious that you will see crying on the last day of summer vacation as it...
#include <bits/stdc++.h> typedef long long LL; #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; int main(void) { for(;;){ int n; cin >> n; if(!n) return 0; vector<int> a,b; a.resize(n); b.resize(n); ...
D: Rescue a Postal Worker story You got a job at the post office, which you have long dreamed of this spring. I decided on the delivery area I was in charge of, and it was my first job with a feeling of excitement, but I didn't notice that there was a hole in the bag containing the mail because it was so floating tha...
#include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <vector> #include <list> #include <stack> #include <queue> #include <map> #include <set> #include <bitset> #include <cl...
problem The point $ P $ is placed at the origin on the coordinate plane. I want to move the point $ P $ to a position where the Manhattan distance from the origin is as far as possible. First, the string $ S = s_1s_2 \ cdots s_ {| S |} $ ($ | S | $ is the number of characters in $ S $) is given. The point $ P $ is mo...
#define _USE_MATH_DEFINES #include <cstdio> #include <cstdlib> #include <iostream> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <queue> #include <map> using namespace std; typedef pair<long long int, long long int> P; long long int INF = 1e18; long long int MOD = 1e9 + 7; lon...
Great performance strategy Taro, an examinee, participated in an N-day study camp. In this training camp, M subjects are tested every day, and after the training camp, a report card with all the test scores is distributed. The report card consists of N sheets of paper, and on the i-th sheet, only the subject names and...
#include<bits/stdc++.h> using namespace std; using Int = long long; using ll = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b)a=b;}; template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b)a=b;}; struct SCC{ vector<vector<int> > G, R, T, C; vector<int> vs, used,...
Set Given the sequence a_1, a_2, .., a_N. How many values ​​are there in this sequence? input N a_1 a_2 ... a_N output Output the number of types of values ​​in the sequence. Constraint * 1 \ leq N \ leq 10 ^ 5 * 1 \ leq a_i \ leq 10 ^ 9 Input example 6 8 6 9 1 2 1 Output example Five Example ...
#include<deque> #include<queue> #include<vector> #include<algorithm> #include<iostream> #include<set> #include<cmath> #include<tuple> #include<string> #include<chrono> #include<functional> #include<iterator> #include<random> #include<unordered_set> #include<array> #include<map> #include<iomanip> #include<assert.h> #inc...
There is a sequence $A = a_0, a_1, ..., a_{n-1}$. You are given the following information and questions. * relate$(x, y, z)$: $a_y$ is greater than $a_x$ by $z$ * diff$(x, y)$: report the difference between $a_x$ and $a_y$ $(a_y - a_x)$ Constraints * $2 \leq n \leq 100,000$ * $1 \leq q \leq 200,000$ * $0 \leq x, y <...
#include <bits/stdc++.h> using namespace std; class disjoint_set { public: vector<int> rank, prt, ptl; disjoint_set (int size) { rank.resize(size); prt.resize(size); ptl.resize(size); for (int i = 0; i < size; i++) { prt[i] = i; rank[i] = 0; ptl[i] = 0; } } int find (int ...
Multiplication of Big Integers II Given two integers $A$ and $B$, compute the product, $A \times B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the product in a line. Constraints * $-1 \times 10^{200000} \leq A, B \leq 10^{200000}$ Sample Input 1 5 8 Sa...
#include <bits/stdc++.h> #define FOR(i,a,b) for (int i=(a);i<(b);i++) #define FORR(i,a,b) for (int i=(a);i>=(b);i--) #define pb push_back #define mp make_pair #define fi first #define se second #define pcnt __builtin_popcount #define tzcnt __builtin_ctzl #define sz(x) (int)(x).size() #define maxs(x,y) x=max(x,y) #defin...
We are very near to our goal now. The enemy is being weakened continuously. But alas, sensing his fall, the hacker has spread a worm into our network. It is consuming all our files at a tremendous rate and must be stopped at all costs. The only way to stop it is to enter a specific code number in to the worm. It is up ...
#! /usr/bin/python # imports import sys import StringIO class Problem(object): def __init__(self, reader): self.reader = reader def run(self): testCaseCount = int(self.reader.readline().strip()) for testCase in range(testCaseCount): data = ...
Chef likes to watch movies very much.A movie of his favorite actress has recently released and he wants to go to cinema hall with his friends to watch the movie. But he will book tickets for him and his friends only if he gets the seats in his desired block size. eg. if he has 9 friends, then he has to book 10 tickets,...
import sys times=input() while times: times-=1 a,b=[int(x) for x in sys.stdin.readline().strip().split()] c,d=[int(x) for x in sys.stdin.readline().strip().split()] p=a t=[] while p: p=p-1 l=list(sys.stdin.readline().strip()) t+=[l] i=0 count=0 count2=[] while i<a-c+1: j=0 while j<b-d+1...
Given a number n , find its factorial. Input There is a single positive integer T on the first line of input. It stands for the number of numbers to follow. Then there are T lines, each containing exactly one positive integer number N, 1 ≤ N ≤ 10000 Output For every input number N, output a single line contain...
import math t = input(); for i in range(t): x = input(); print math.factorial(x);
Leonid is developing new programming language. The key feature of his language is fast multiplication and raising to a power operations. He is asking you to help with the following task. You have an expression S and positive integer M. S has the following structure: A1*A2*...*An where "*" is multiplication operation. ...
import math t = int(input()) for _ in range(t): M,S = raw_input().split() M = int(M) S = S.split('*') ans = 1 for i in range(0, len(S), 3): ans = (ans * pow(int(S[i]), int(S[i+2]), M)) % M print(ans)
Some programming contest problems are really tricky: not only do they require a different output format from what you might have expected, but also the sample output does not show the difference. For an example, let us look at permutations. A permutation of the integers 1 to n is an ordering of these integers. So the n...
while True: n=int(raw_input()) if n==0: break else: A=[] A = map(int,raw_input().split()) j=1 flag=0 for i in A: if j!=A[i-1]: flag=1 break j+=1 if flag == 0: print "ambiguous" else: print "n...
For Turbo C++ Users : Read the following document before attempting the question : For C and C++ users, use long long instead of int. For Java users, use long. Problem description Data here, Data There. Data Everywhere. Which one is mine though? Main Proconist Dhruv has been given the task of encrypting a clas...
for i in range(input()): n=input() if n%26!=0: r=(n/26)+1 else: r=n/26 print r
Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i. Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j. Games in the shop are ordered from left to right, Maxim tries to buy every game i...
#include <bits/stdc++.h> using namespace std; int main() { long long int shell_length; long long int wallet_length; cin >> shell_length >> wallet_length; std::vector<long long int> vct(shell_length); for (long long int &i : vct) cin >> i; std::deque<long long int> wallet; while (wallet_length--) { lon...
You are given a matrix of size n × n filled with lowercase English letters. You can change no more than k letters in this matrix. Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is f...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = 0; c = getchar(); } while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); return f ? x : -x; } long long n,...
At a break Vanya came to the class and saw an array of n k-bit integers a_1, a_2, …, a_n on the board. An integer x is called a k-bit integer if 0 ≤ x ≤ 2^k - 1. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himse...
#include <bits/stdc++.h> using namespace std; inline char nc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } template <typename T = int> inline T nxt() { char c = nc(); T x = 0; int f = ...
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i. You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with l...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5, M = 6e5 + 5; int n, m, k, x, y, w; int tot = 1, to[M], v[M], nex[M], head[N]; long long dis[N]; bool vis[N]; struct node { int dot; long long dis; }; struct cmp { bool operator()(node a, node b) { return a.dis > b.dis; } }; priority_queue<node, ...
Makoto has a big blackboard with a positive integer n written on it. He will perform the following action exactly k times: Suppose the number currently written on the blackboard is v. He will randomly pick one of the divisors of v (possibly 1 and v) and replace v with this divisor. As Makoto uses his famous random num...
import java.util.*; import java.io.*; public class Practice { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static fina...
The only difference between easy and hard versions is the constraints. Polycarp has to write a coursework. The coursework consists of m pages. Polycarp also has n cups of coffee. The coffee in the i-th cup Polycarp has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can dri...
import java.util.*; public class coffeeeeeeyoy { static Long[] a; static int n; static long k; public static void main(String[] args) { Scanner scan=new Scanner(System.in); n=scan.nextInt(); k=scan.nextInt(); a=new Long[n]; long sum=0L; for(int i=0;i<n;i++) { a[i]=scan.nextLong(); sum+=a[i]; } ...
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
n = int(input()) a = list(map(int, input().split(' '))) ans = 1 length = 2 while length <= n: for i in range(0, n // length): b = a[i * length: (i + 1) * length] ok = True for j in range(len(b) - 1): if b[j] > b[j + 1]: ok = False break if ...
The only difference between easy and hard versions is constraints. Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them. E...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2 * (2e5 + 5); const int MOD = 998244353; int n, m; int sumK = 0; int k[MAXN]; vector<pair<int, int> > oriSp; bool canFin(const int day) { vector<int> ks(k, k + MAXN); vector<int> sp(MAXN, 0); for (int i = 0; i < m; ++i) { const int d = oriSp[i].f...
Heidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a care...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; const int MAXM = 1000005; int n, m; int a[MAXM], b[MAXM], w[MAXM]; pair<int, int> p[MAXM]; int par[MAXN]; int nadi(int x) { if (par[x] == x) return x; return par[x] = nadi(par[x]); } bool spoji(int x, int y) { x = nadi(x); y = nadi(y); if ...
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ...
import math n = int(input()) l=list(map(int,input().split())) hcf = l[0] for i in l[1:]: hcf = math.gcd(hcf,i) count = 0 for i in range(1, int(math.sqrt(hcf))+1): if hcf % i == 0 : count += 2 if hcf == 1: print(count - 1) else: if int(math.sqrt(hcf)) * int(math.sqrt(hcf)) == hcf : count -= 1 pr...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has an array consisting of n numbers. He wants to perform m operations of two types: * add...
#include <bits/stdc++.h> using namespace std; int n, m; int ans; int a[1000000]; int tree[1000000]; int b[50] = { 0, 4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777, 4444, 4447, 4474, 4477, 4744, 4747, 4774, 4777, 7444, 7447, 7474, 7477, 7744, 7747, 7774, 7777, }; int f[...
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at lea...
from math import ceil t = int(input()) slow = {"S": "R", "R": "P", "P": "S"} for _ in range(t): n = int(input()) a, b, c = map(int, input().split()) s = input() slow2 = {"S": a, "R": b, "P": c} res = 0 ans = [''] * n for i in range(n): if slow2[s[i]] > 0: res += 1 ...
The well-known Fibonacci sequence F_0, F_1, F_2,… is defined as follows: * F_0 = 0, F_1 = 1. * For each i ≥ 2: F_i = F_{i - 1} + F_{i - 2}. Given an increasing arithmetic sequence of positive integers with n elements: (a, a + d, a + 2⋅ d,…, a + (n - 1)⋅ d). You need to find another increasing arithmetic se...
#include <bits/stdc++.h> using namespace std; const long long T = 614945049; const long long MOD = 1000000000; long long n, a, d; inline void File() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); } signed main() { scanf("%lld %lld %lld", &n, &a, &d); cout << (T * a % MOD * 15 * (MOD / 10) + 1) << "...
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; inline long long mod(long long n, long long m) { long long ret = n % m; if (ret < 0) ret += m; return ret; } long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); } long long exp(long long a, long long b, long long m) { if (b == 0) return 1;...
This is an interactive problem. After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost! The United States of America can be modeled as a tree (why though) ...
#include <bits/stdc++.h> using namespace std; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } const long double EPS = 1e-10; const long lo...
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one ...
#include <bits/stdc++.h> char s[100010]; int calc(int x) { int a[10]; for (int i = 0; i < 8; i++) { a[i] = x & 1; x >>= 1; } int ret = 0; for (int i = 0; i < 8; i++) ret = ret << 1 | a[i]; return (ret); } int getmod(int x) { x %= 256; if (x < 0) x += 256; return (x); } int main() { gets(s); ...
Note that the only differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if all versions are solved. Slime is interested in sequences. He defined good positive integer sequences p of length n as follows: * For each k>1 that presents in p, there should be at ...
#include <bits/stdc++.h> #pragma GCC optimize("O2") using namespace std; const int N = 5e3 + 10; const long long mod2 = 1e9 + 7; const long long mod = 998244353; const long long inf = 8e18; const int LOG = 22; long long pw(long long a, long long b, long long M) { return (!b ? 1 : (b & 1 ? (a * pw(a * a %...
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the ...
#include <bits/stdc++.h> using namespace std; struct pnt { int x, y; } p[10]; int h[10]; int s1[10]; int s2[10]; bool fnd; int dist2(pnt a, pnt b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } bool squ(pnt a, pnt b, pnt c, pnt d) { int dab = dist2(a, b); int dbc = dist2(b, c); if (dbc != d...
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 ≤ j ≤ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the...
import java.io.*; import java.util.*; public class Rating{ public static Scanner in=new Scanner(System.in); public static void rotate(StringBuffer s) { char tmp=s.charAt(0); s.delete(0, 1); s.append(tmp); } public static void main(String args[]) { int T_T=in.nextInt(); String s[...
Another dull quarantine day was going by when BThero decided to start researching matrices of size n × m. The rows are numerated 1 through n from top to bottom, and the columns are numerated 1 through m from left to right. The cell in the i-th row and j-th column is denoted as (i, j). For each cell (i, j) BThero had t...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; template <class C> void mini(C &a4, C b4) { a4 = min(a4, b4); } template <class C> void maxi(C &a4, C b4) { a4 = max(a4, b4); } template <class TH> void _dbg(const char *sdbg, TH h) { cerr << sdbg << '=' << h << endl; } template <class TH, c...
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da...
import java.io.*; import java.util.*; public class Dance { public static void main(String[]args) { Scanner sc = new Scanner(System.in); long n ; n = sc.nextLong(); System.out.println(fact(n)/((int)Math.pow(n/2,2)*2)); } public static long fact(long n) { long f=1; for(int i=1;i<=n;i++) { f = f...
You are given a string s of 0's and 1's. You are allowed to perform the following operation: * choose a non-empty contiguous substring of s that contains an equal number of 0's and 1's; * flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; * reverse the substring. For exa...
/** * * 这就是 Legendary Grandmaster 级别的贪心题🐎? * * 解释题意:每次选择一段连续的字串,进行如下的变换 * - 子串满足 1 的数量和 0 的数量相等 * - 将子串的每一位都取反 * - 将子串的顺序翻转为倒序 * 现在要求求出这个 01 串可以变换达到的字典序最小的串 * * 贪心做法: * * 发现:如果子串是 10 型或者 01 型,这种变换将毫无意义 * 启发:将所有的 0 替换为 -1,统计前缀和,并以此建图: * - 对于每一个前缀和的值建立节点 * - 这个节点只会连接到 -1(0)和 +1(1)的节点 * - 得到的图一定包含一条完整的欧拉路...
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. <image> You ...
#include <iostream> #include <set> #include <cmath> #include <queue> #include <algorithm> #include <vector> #include <map> #include <string.h> #include <cstdlib> #include <bitset> #include <unordered_map> #include <iomanip> #include <unordered_set> #include <sstream> using namespace std; #define ll long long ll mod=1e...
Yuu Koito and Touko Nanami are newlyweds! On the wedding day, Yuu gifted Touko a directed tree with n nodes and rooted at 1, and a labeling a which is some DFS order of the tree. Every edge in this tree is directed away from the root. After calling dfs(1) the following algorithm returns a as a DFS order of a tree root...
#include <bits/stdc++.h> #define ll long long #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() #define vi vector<int> #define pii pair<int, int> #define rep(i, a, b) for(int i = (a); i < (b); i++) using namespace std; template<typename T> using minpq = priority_queue<T, vector<T>, greater<T>>; ...
This is the easy version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved. Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows a...
/* v:r:1BRBI.7J. jIJ27IUYUuri:7:::::::v7::ri..::irRBb71P2qKbu7i.::... :vIKr:i:rRS:::XXJur:iLIsS7LLrr1r r .:JBRBL.:r. ...:iiuIIr:.r:..... .iir:.:. .:2I7i.2g7Pgd2IJ:.. rYr .:..i:...i5vsi:i2j11r7Yiir: i.:rSRgZXi7irir:::r7ivZ5ii5s.r7iii::i:Yv::i.......i7bSJRdqDbX7ii:....:qr..:ir:irr::s2j7r1q15b77uv7r: :..sgi7Xs:irir...
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation...
#include <bits/stdc++.h> using namespace std; const int inf = 1 << 28; const double INF = 1e12, EPS = 1e-9; const int mod = (int)1e9 + 7; int n, k; long long dp[2][2], ans; void run() { string a, b; cin >> a >> b >> k; dp[0][0] = 1; n = a.size(); if (b.size() != n) { cout << 0 << endl; return; } i...
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
n = int(input()) string = input() times = list(map(int, string.split())) a = min(times) if times.count(a) == 1: print(times.index(a) + 1) else: print("Still Rozdil")
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their p...
#include <bits/stdc++.h> using namespace std; int Get() { char c; while (c = getchar(), c < '0' || c > '9') ; int X = 0; while (c >= '0' && c <= '9') { X = X * 10 + c - 48; c = getchar(); } return X; } const double eps = 1e-7; int main() { int N = Get(), M = Get(), Total = 0; static int K[10...
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, b...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solver { public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter("output.txt"); // br = new BufferedReader(new InputStreamReader(S...
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line. Input The single line contains two integers n and m...
import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.lang.reflect.*; import java.util.*; public class B { final int INF = (int) 1e5; @SuppressWarnings("unused") public B () { int N = sc.next...
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number. For example, let's say that Vitaly's favourite digits are ...
MOD=10**9+7 a,b,n=list(map(int,input().strip().split(' '))) #there are i a's. n-i b's def check(a,b,x): temp=x%10 if temp!=a and temp!=b: return 0 while(x>0): temp=x%10 if temp!=a and temp!=b: return 0 x=x//10 return 1 fact=[1] infact=[1] temp=1 intemp=1...
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)...
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=s.n...
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d re...
import java.util.*; import java.io.*; public class Main { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder out = new StringBuilder(); public static void main(String[] args){ int ink = nextInt(); int[] cost = nextIntArrayFrom...
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1. In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time ti at section ai. If you are at s...
#include <bits/stdc++.h> using namespace std; int n, m, d, a[400], b[400], t[400], now, last, L, R, l, Q[150010]; long long dp[2][150010]; void f1(long long x) { while (L <= R && Q[L] < x) L++; } void f3(int l) { while (L <= R && dp[last][Q[R]] < dp[last][l]) R--; Q[++R] = l; } void f2(long long y) { while (l <...
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation: F1 = 1, F2 = 2, Fi = Fi - 1 + Fi - 2 (i > 2). We'll define a new number sequence Ai(k) by the formula: Ai(k) = Fi × ik (i ≥ 1). In this problem, your task is to calculate the following sum: A1(k) + A2(k) + ... ...
#include <bits/stdc++.h> using namespace std; struct matrix { long long m[90][90]; matrix() { memset(m, 0, sizeof m); } long long *operator[](int i) { return m[i]; } friend matrix operator*(const matrix &a, const matrix &b) { matrix r; for (int i = (0); i < (90); ++i) for (int j = (0); j < (90); +...
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Eac...
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int c=sc.nextInt(),d=sc.nextInt(), n=sc.nextInt(), m=sc.nextInt(), k=sc.nextInt(); if(((n*m)-k) <= 0) { System.out.println(0); return; } else { System.out.println(Math.min(c * (((n...
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him. Help Andrey choose...
#include <bits/stdc++.h> using namespace std; vector<double> s; int n; double cal(int i) { double res = 0; for (int j = i; j < n; j++) { double temp = 1; for (int k = i; k < n; k++) { if (k == j) temp *= s[j]; else temp *= (1 - s[k]); } res += temp; } return res; } in...
Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("rep...
MOD = 10**9+7 s = raw_input() n = int(raw_input()) query = [['',s]]+[raw_input().split('->') for i in range(n)] value = {} pow10 = {} for i in range(10): value[str(i)] = i pow10[str(i)] = 10 for i in range(n,-1,-1): newValue = 0 newPow10 = 1 for d in query[i][1]: newValue = (newValue*pow...
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of...
#include <bits/stdc++.h> using namespace std; vector<int long long> vis; vector<vector<int long long> > a; int long long ans = 0; void dfs(int long long i, int long long step, int long long father) { if (step == 2) { vis[i]++; if (vis[i] >= 2) ans += vis[i] - 1; return; } for (long long j = 0; j < a[i...
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
n, m = map(int, input().split()) s = 1 c = n - 1 arr = [0] * n i = 0 while i <= c: r = 0 j = s while j <= n and r < m: if j < n: r += 2 ** (n - j - 1) j += 1 #print(s, j, r, m) if j > s and j != n + 1: r -= 2 ** (n - j) m -= r j -= 1 arr[i] = j whi...
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous. Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of piece...
#include <bits/stdc++.h> using namespace std; const int INF = 1000000000; const int MOD = INF + 7; const int MAXN = 51; string s[MAXN]; bool val[MAXN][MAXN]; int main() { int n; while (cin >> n) { vector<pair<int, int> > pieces; for (int i = 0; i < n; i++) { cin >> s[i]; for (int j = 0; j < n; j...
Archaeologists found some information about an ancient land of Treeland. We know for sure that the Treeland consisted of n cities connected by the n - 1 road, such that you can get from each city to any other one along the roads. However, the information about the specific design of roads in Treeland has been lost. The...
#include <bits/stdc++.h> using namespace std; int N, M, V[1005]; bitset<1005> T, A[1005], E[1005], G[1005]; int IN() { int x = 0, ch; for (; (ch = getchar()) < '0' || ch > '9';) ; for (; ch >= '0' && ch <= '9'; (ch = getchar())) (x *= 10) += ch - '0'; return x; } int main() { N = IN(); for (int i = 1; i...
Duff is mad at her friends. That's why she sometimes makes Malek to take candy from one of her friends for no reason! <image> She has n friends. Her i-th friend's name is si (their names are not necessarily unique). q times, she asks Malek to take candy from her friends. She's angry, but also she acts with rules. Whe...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; template <typename T> inline void read(T &AKNOI) { T x = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') flag = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); } ...
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one...
#include <bits/stdc++.h> using namespace std; int n, m, k; string s[10][10]; int cnt = 0; int dx[6] = {-1, 0, 0, 0, 0, 1}; int dy[6] = {0, 0, -1, 1, 0, 0}; int dz[6] = {0, 1, 0, 0, -1, 0}; void dfs(int x, int y, int z) { s[z][x][y] = '#'; ++cnt; for (int i = 0; i < 6; ++i) { int nx = x + dx[i], ny = y + dy[i]...
Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting...
from functools import reduce def c(n, m): return 0 if n>m or n<0 else reduce(lambda a,b: a*b, range(m-n+1, m+1), 1)//reduce(lambda a,b: a*b, range(1,n+1), 1) n = int(input()) print(sum([c(i, n)*c(i-1, 2) for i in range(1, 4)])*sum([c(i, n)*c(i-1, 4) for i in range(1, 6)]))
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally: Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) ...
#include <bits/stdc++.h> using namespace std; long long n, k, tot, num, now, a[200001], f[200001]; int main() { cin.sync_with_stdio(false); cin >> n >> k; for (int i = 0; i <= n; i++) cin >> a[i]; now = -1; for (int i = 0; i <= n; i++) { f[i] += a[i]; if (i != n) { f[i + 1] += f[i] / 2; f[...
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
#!/usr/bin/env python3 if __name__ == '__main__': n = int(input()) for _ in range(n): handle, prev, curr = input().split() prev = int(prev) curr = int(curr) if prev < 2400: continue if curr > prev: print('YES') break else: # for...
After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem. You are given integer k and array a1, a2, ..., an of n integers. You are to find non-empty subsequence of array elements su...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1005, MAXD = 1e4 + 10; int n, dp[MAXN][MAXD]; long long sum[MAXN][MAXD]; vector<long long> d, p; long long k, a[MAXN]; int prv[MAXN][MAXD]; long long GCD(long long a, long long b) { return !a ? b : GCD(b % a, a); } int getind(long long val) { return lower...
Alfred wants to buy a toy moose that costs c dollars. The store doesn’t give change, so he must give the store exactly c dollars, no more and no less. He has n coins. To make c dollars from his coins, he follows the following algorithm: let S be the set of coins being used. S is initially empty. Alfred repeatedly adds ...
#include <bits/stdc++.h> using namespace std; int a[200005]; int main() { int n, m, x, f; set<int> v; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d", &x); a[x]++; } for (int i = 0; i <= n; i++) { if (a[i]) v.insert(i); } for (int i = 1; i < n; i++) { x = n, f = n; if...
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment ex...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.io.BufferedReader; import java.ut...
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. Input The first line contains the positive integer x (1 ≤ ...
#include <bits/stdc++.h> using namespace std; long long int digits[20]; long long int digitsclone[20]; int dc = 0; long long int arrofarr[20][20]; int main() { long long int input; cin >> input; if (input < 10) { cout << input; return 0; } while (input != 0) { digits[dc] = input % 10; digitscl...
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are n carrots arranged in a...
#include <bits/stdc++.h> using namespace std; const int MAXN = 3 * 1e5 + 10; int max(int a, int b) { if (a > b) return a; return b; } int min(int a, int b) { if (a < b) return a; return b; } int a[MAXN] = {0}; int b[MAXN] = {0}; int c[MAXN] = {0}; int main() { int n; cin >> n; int maxi = 0; for (int i =...
Karen just got home from the supermarket, and is getting ready to go to sleep. <image> After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection. She recalled that she used to play with those cards as a child, and, although...
#include <bits/stdc++.h> using namespace std; struct pt { int x, y, z; bool operator<(const pt t) const { return z > t.z; } } P[500050]; int N, X, Y, Z; map<long long, long long> con; long long cnt; void upd(long long x, long long y) { auto I = con.lower_bound(x); if (y <= I->second) return; long long last = ...
Once, Leha found in the left pocket an array consisting of n integers, and in the right pocket q queries of the form l r k. If there are queries, then they must be answered. Answer for the query is minimal x such that x occurs in the interval l r strictly more than <image> times or - 1 if there is no such number. Help...
#include <bits/stdc++.h> using namespace std; const int N = 300000 + 77, SQ = 547; int n, q, a[N], Ql[N], Qr[N], Qk[N], P[N], A[N], T[N]; mt19937 rng; bool CMP(int x, int y) { if (Ql[x] / SQ < Ql[y] / SQ) { return 0; } if (Ql[x] / SQ > Ql[y] / SQ) { return 1; } return Qr[x] < Qr[y]; } int Random(int l...
Arkady words in a large company. There are n employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees. Each employee has an integer rank. The CEO has rank eq...
#include <bits/stdc++.h> using namespace std; struct edge { int to, next; } e[1000005]; int head[1000005], dep[1000005], fa[1000005]; int top[1000005], sz[1000005], pos[1000005]; long long ans[1000005], s1[1000005], s2[1000005]; vector<int> v[1000005]; int tot, rt, n, T; void adde(int x, int y) { e[++tot] = (edge){...
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Mor...
#include <bits/stdc++.h> using namespace std; const int MAXN = 3e5 + 10; long long dp[MAXN << 1]; long long dp1[MAXN << 1]; int n, a, b, c, d, start, len; struct Act { int t, type; bool operator<(const Act& other) const { if (t != other.t) return t < other.t; return type > other.type; } bool operator==(...
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on t...
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P90D { abstract class AWidget { long width, height; public abstract void setBorder(int border); public abstract void setSpacing(int spacing); public abstract void pack(AW...
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c...
# -*- coding: utf-8 -*- """ Created on Thu Feb 15 21:01:05 2018 @author: DNARNAprotein """ """ CODEFORCES http://codeforces.com/contest/932/problem/A """ def pikachu(a,c,n): #c is original string prefixes=[a[0:i+1] for i in range(n+1)] suffixes=[a[i:n+1] for i in range(n+1)] maxi=0 for i in range(n//...
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning. Mahmoud knows that the i-th word can be sent with cost ai. For each word in his messa...
#!/usr/bin/env python n, k, m = [int(x) for x in raw_input().split()] s = raw_input().split() d = {s[x]: x + 1 for x in xrange(len(s))} c = [0] + [int(x) for x in raw_input().split()] r = [0] * (n + 1) p = [i for i in xrange(n + 1)] def find(a): temp = a while p[temp] != temp: temp = p[temp] p[a] = temp c[temp] =...
There are n players numbered from 0 to n-1 with ranks. The i-th player has rank i. Players can form teams: the team should consist of three players and no pair of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let i, j, k be the ranks of players in the tea...
#include <bits/stdc++.h> using namespace std; int n, m, arr[200000][2], idx[200000], nl[200000], nr[200000], prn[200000]; unsigned long long a, b, c, sl[200000], sr[200000], prm[200000], r; vector<int> qr[200000], ql[200000]; vector<unsigned long long> qrs[200000], qls[200000]; struct TRIANGLE { int n, *idx, *idv; ...