problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
word=input() word = word.lower() wordlist=list(word) b=[] for wor in wordlist: wor=str(wor) if wor!='a' and wor!='e' and wor!='i' and wor!='o' and wor!='u' and wor!='y': wor='.'+wor b.append(wor) print(''.join(b))
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
3
n=int(input()) arr=list(map(int,input().split())) sum=sum(arr) tar=sum/2; tar2=int(tar) if tar-tar2: tar2+=1 get=0 i=1 for x in arr: get+=x if get>=tar2: break i=i+1 print(i)
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ...
3
s=input();print(max(s)*s.count(max(s)))
You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). ...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems. Polycarp has a list of n contests, th...
3
from collections import Counter n=int(input()) l=sorted(list(map(int,input().split()))) t=0 i=0 while i<n: if l[i]>=t+1: t+=1 i+=1 print(t)
A bipartite graph G = (V, E) is a graph in which the vertex set V can be divided into two disjoint subsets X and Y such that every edge e ∈ E has one end point in X and the other end point in Y. A matching M is a subset of edges such that each node in V appears in at most one edge in M. Given a bipartite graph, find ...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 3 4 6 0 0 0 2 0 3 1 1 2 1 2 3 output: 3 """ import sys def dfs(current, matching, visited): for target in range(y_num): if not visited[target] and target in adj_table[current]: visited[target] = True ''' Matching[target] = ...
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once. A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character...
3
t = int(input()) for _ in range(t): s = input() d = [0 for i in range(3)] gl,ll = 10**6,10**6 l,r = 0,0 char = ['1','2','3'] while(l<=r): if d[0]<1 or d[1] < 1 or d[2] < 1: if r < len(s): d[int(s[r])-1] += 1 r += 1 else: ...
There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.) What is the area of this yard excluding the roads? Find it. Constraints * A is an ...
3
A,B=[int(i) for i in input().split()] print(A*B-A-B+1)
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
3
n, a, b = map(int, input().strip().split()) if a + b >= n: print(n-a) else: print(n-(n-b)+1)
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec...
3
a = int(input()) b = list(map(int, input().split())) for i in range(len(b)): if i == 0: print(abs(b[i] - b[i + 1]), abs(b[i] - b[len(b) - 1])) elif i == len(b) - 1: print(abs(b[i] - b[i - 1]), abs(b[i] - b[0])) else: print(min(abs(b[i] - b[i - 1]), abs(b[i] - b[i + 1])), max(abs(b[i...
You are given an integer K. Print the string obtained by repeating the string `ACL` K times and concatenating them. For example, if K = 3, print `ACLACLACL`. Constraints * 1 \leq K \leq 5 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print the s...
3
k = int(input()) for _ in range(k): print("ACL", end = "")
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
3
def tits(a,b,n): for i in range(n): if a[i]> b[i]: return -1 gh = [[] for i in range(20)] for i in range(n): gh[ord(a[i]) - ord("a")].append(ord(b[i]) - ord("a")) gh[ord(b[i]) - ord("a")].append(ord(a[i]) - ord("a")) visit = [False for i in range(20)] def dfs(adj,visit,u): visit[u]= True for i in adj...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
from collections import Counter n=int(input()) r=0 groups=Counter(input().split()) taxi_req=groups['4']+groups['2']//2 z=groups['3']-groups['1'] if z<0: #number of 1s greater than number of 3s taxi_req+=groups['3'] z=-z taxi_req+=z//4 r=z%4 else: taxi_req+=groups['1'] taxi_req+=z a=(gro...
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria. Initially, on day 1, there is one bacterium with mass 1. Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass m/2 each. For example, a ba...
3
t = int(input()) import math for _ in range(t): n = int(input()) keta = math.floor(math.log2(n)) a = [0] * keta if keta >= 2: for i in range(keta): a[i] = 2 ** i sa = n - (2 ** keta - 1) a[keta-2] = min(sa//2,a[keta-2]) a[keta-1] = ...
Chef recently saw the movie Matrix. He loved the movie overall but he didn't agree with some things in it. Particularly he didn't agree with the bald boy when he declared - There is no spoon. Being a chef, he understands the importance of the spoon and realizes that the universe can't survive without it. Furthermore, h...
1
def f(): n,m=map(int, raw_input().split()) matrix = [] for i in range(n): matrix.append(raw_input().lower()) for i in range(n): index = -1 while True: index = matrix[i].find('s', index+1) if index==-1: break if (index+4<m and ma...
Try guessing the statement from this picture: <image> You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d. Input The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases. Each test case contains one integer d (0 ≤ d ≤ 10^3). ...
3
def diff(a,b,d): return abs(a+b-d) eps = 10**(-6) for _ in range(int(input())): n = int(input()) if(n==0): print("Y 0 0") continue if(n==1 or n==2 or n==3): print("N") continue l , h , flag = 0 , n , False while l <= h and h!=0: a = (l+h)/2; b = n-a; # print(a,b) if diff(a,b,a*b) <= eps and diff(a...
Given are three integers A_1, A_2, and A_3. If A_1+A_2+A_3 is greater than or equal to 22, print `bust`; otherwise, print `win`. Constraints * 1 \leq A_i \leq 13 \ \ (i=1,2,3) * All values in input are integers. Input Input is given from Standard Input in the following format: A_1 A_2 A_3 Output If A_1+A_2+A_...
3
print('win' if sum(map(int,input().split())) <= 21 else 'bust')
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
1
n = input() l = [] sq = 0 for i in xrange(n): l.append(tuple(map(int, raw_input().split()))) if (n == 1): print -1 exit() if (n == 2): if (l[0][0] == l[1][0] or l[0][1] == l[1][1]): print -1 exit() else: sq = abs((l[0][1] - l[1][1]) * (l[0][0] - l[1][0])) else: for i in xrange(n): for j in xrange(n): i...
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given n nonnegative integers a_1, a_2, ..., a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 ≤ i ≤ n, the elements a_{i - 1} and a_...
3
n = int(input()) arr = list(map(int, input().split(" "))) even_pos = arr[::2] odd_pos = arr[1::2] arr = even_pos + odd_pos+ even_pos m = (n+1)//2 s = sum(arr[:m]) s_max = s for i in range(n): s -= arr[i] s += arr[m+i] s_max = max(s, s_max) print(s_max)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
vowels=['a','A','e','E','i',"I",'o',"O",'u',"U",'y','Y'] word=list(raw_input()) finalword=[] for i in range(len(word)): if word[i] in vowels: pass else: finalword.append('.') if word[i].isupper(): finalword.append(word[i].lower()) else: finalword.append(word[i]) final='' for i in...
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1. Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}. Let's say string t is good if its left cyclic shift is equal to its right cyclic shift. You are given str...
3
for _ in range(int(input())): s = input() n = len(s) if(n==1 or n==2): print(0) else: dic = {} for i in range(n): if(s[i] in dic): dic[s[i]]+=1 else: dic[s[i]]=1 mx = 0 for i in dic.keys(): mx = m...
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
3
n = int(input()) nums = list(zip(map(int, input().split()), range(0,100))) xmin = min(nums) xmax = max(nums) #print(nums) #print(xmin, xmax) a = abs(xmax[1] - xmin[1]) b = abs(xmax[1]) c = abs(n - xmax[1] - 1) d = abs(xmin[1]) e = abs(n - xmin[1] - 1) print(max(a, b, c, d, e))
Did you ever hear about 'Dragon Food' ? Its used to refer to the chocolates bought for your loved ones :). Po offers dragon food to master Shifu, who is a famous cook in the valley of food. In return, Shifu hands over the dragon scroll to Po, which is said to hold the ingredients of the secret recipe. To open the drago...
1
def count1s(n, x): count = 0 for i in xrange(n): if x & (1 << i): count += 1 return count cases = int(raw_input()) for _dummy in range(cases): n, a, b = map(int, raw_input().split()) #print n, a, bin(a), b, bin(b) a = count1s(n, a) b = count1s(n, b) numzeros = abs(n - (a+b)) ans = (2**n)-1 - ((2**numze...
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
for case in range(int(input())): x = input() ans = (int(x[0]) - 1) * 10 if len(x) >= 1: ans += 1 if len(x) >= 2: ans += 2 if len(x) >= 3: ans += 3 if len(x) >= 4: ans += 4 print(ans)
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, th...
1
# -*- coding: UTF-8 -*- # from itertools import * # from collections import defaultdict # def gcd(a,b): # while b > 0: a,b = b, a%b # return a # def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"): # return ((num == 0) and "0" ) or ( baseN(num // b, b).lstrip("0") + numerals[num % b]) # St...
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
1
for i in xrange(5): try: print abs(i - 2) + abs(raw_input().split().index('1') - 2) except: pass
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov...
3
t = int(input()) for i in range(t): n = int(input()) S = list(input()) A = [0, 0] ans = 0 for i in range(n): if S[i] == '(': A[0] += 1 else: A[1] += 1 a = A[1] - A[0] if a > ans: ans = a print(ans)
You are given a following process. There is a platform with n columns. 1 × 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all ...
3
n, m = map(int, input().split()) count = [0]*(n+1) columns = list(map(int, input().split())) for c in columns: count[c] += 1 min_ = 1000 for i in range(1, n+1): min_ = min(min_, count[i]) print(min_)
There are N integers, A_1, A_2, ..., A_N, written on the blackboard. You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written. Find the maximum possible greatest common divisor of the N integers on the blackboard afte...
3
from fractions import gcd N = int(input()) A = list(map(int, input().split())) L = [0] * (N+1) R = [0] * (N+1) for i in range(1, N+1): L[i] = gcd(L[i-1], A[i-1]) R[-i-1] = gcd(R[-i], A[-i]) M = [gcd(L[i], R[i+1]) for i in range(N)] print(max(M))
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th...
1
#! /usr/bin/env python #coding=utf-8 h, m = map(int, raw_input().split(':')); H = h; while True: M = H / 10 + 10 * (H % 10); if M < 60 and (H != h or m < M): break; H = (H + 1) % 24; print "%02d:%02d" %(H, M);
Quan_Lank is a great team with some uncommon interests in programming. Sometimes the team loves to solve strings puzzles, sometimes game puzzles and sometimes metrix type puzzles . Yesterday they have added a new interest to their list that is 'number theory' as they have solved some amazing puzzles related to number t...
1
t = input() while t > 0: n = input() if(n == 1): print 1 t = t-1 continue ans = 0 i = 1 while i*i <= n: if n%i == 0: x = i y = n/i # print str(x) + " " + str(y) temp = n flag = 0 while x > 0: temp = n while temp > 0: if temp%10 == x%10: ans += 1 flag = 1 brea...
Takahashi loves the number 7 and multiples of K. Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.) If the sequence contains no multiples of K, print `-1` instead. Constraints * 1 \leq K \leq 10^6 * K is an integer. Input Input is giv...
3
k=int(input()) if k%2==0 or k%5==0: print(-1) exit() ans=1 num=7%k while num!=0: num=(10*num+7)%k ans+=1 print(ans)
Alice and Bob are controlling a robot. They each have one switch that controls the robot. Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up. Bob started holding down his button C second after the start-up, and released his button D second...
3
a,b,c,d = map(int, input().split()) t = min(b,d) -max(a,c) print(max(t,0) )
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) s=0 for i in range(0,n): a,b,c=input ().split() a=int(a) b=int(b) c=int(c) k=a+b+c if(k>=2): s=s+1 print (s)
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co...
3
from math import * from copy import * from string import * # alpha = ascii_lowercase from random import * from sys import stdin from sys import maxsize from operator import * # d = sorted(d.items(), key=itemgetter(1)) from itertools import * from collections import Counter # d = dict(Counter(l)) import math n=i...
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example: * the following numbers are composite: 1024, 4, 6, 9; * the following numbers are not composite: 13, 1, 2, 3, 37. You are given a positive integer n. Find two composite integers a,b such that a-b=n. I...
3
n = int(input()) N = int(1e9) def p(x): for i in range(2, int(x**0.5)+1): if (x % i == 0): return 1 return 0 for i in range(4, N): if (p(i) == 1 and p(i+n) == 1): print(i+n, i) break
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
for i in range(int(input())): x, y, z = map(int, input().split()) a = 0 b = 0 c = 0 d = 0 if(x != y and y != z and x != z): d = 1 elif(y == z and x > y): d = 1 elif(x == z and x < y): d = 1 elif(x == y and z > x): d = 1 else: if(x == y and ...
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
import sys if __name__ == '__main__': name1 = input().strip('\n\r\t ') name2 = input().strip('\n\r\t ') letters = input().strip('\n\r\t ') d = {} for c in letters: if c not in d: d[c] = 0 d[c] += 1 for line in name1, name2: for c in line: ...
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act...
3
n = int(input()) a = list() for i in range(n): a.append(int(input())) res = 0 h = 0 for i in range(n-1): res+=(a[i]-h)+1 if a[i] > a[i+1]: res+=a[i]-a[i+1] res+=1 h = a[i+1] else: res+=1 h=a[i] res+=1 res+=(a[n-1]-h) print(res)
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s=input() u=0 l=0 for i in s: if(i.isupper()): u+=1 else: l+=1 if(u>l): print(s.upper()) else: print(s.lower())
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2·x); * append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasil...
1
import sys sys.setrecursionlimit(10000) resp = [] a, b = map(int, raw_input().split()) def dfs(x, ant): if x == b: resp.append(x) return True elif 2*x <= b and dfs(2*x, x): resp.append(x) return True elif 10*x+1 <= b and dfs(10*x+1, x): resp.append(x) return...
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar...
3
n = int(input()) for i in range(n): f = int(input()) g = input() ans = "" ans1 = "" for j in g: if(int(j)%2 == 1 and len(ans)!=2): ans+=j if(len(ans)<2): print(-1) else: ans1 += ans[0] ans1 += ans[1] print(ans)
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
3
n=int(input()) sx=set() sy=set() for i in range(n): x,y=map(int,input().split()) sx.add(x) sy.add(y) if len(sx)!=2 or len(sy)!=2:print(-1) else:print((max(sx)-min(sx))*(max(sy)-min(sy)))
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
[s, t, u, v] = sorted(list(map(int, input().split()))) # a+b, b+c, a+c, a+b+c if s == t == u: ret = int(s/2) print(ret, ret, ret) else: a = int((s + t - u)/2) b = int((s + u - t)/2) c = int((t + u - s)/2) print(a, b, c)
You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 ≤ i ≤ n). Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers...
3
for i in range(int(input())): int(input()) l = input().split() print("NO" if len(set(l))==len(l) else "YES")
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
3
n = int(input()) s = 0; for i in range(n): s += (n-i)*i s += n print(int(s))
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 ...
3
n, m = map(int, input().split()) answer = 0 face_detector = [input() for i in range(n)] for i in range(n): for j in range(m): if face_detector[i][j] == 'f': if i > 0: if j > 0: if face_detector[i-1][j] == 'a': if face_detector[i-1][j-1] == 'c': if face_detector[i]...
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur mult...
3
n=int(input()) s=0 for i in range(n): a=str(input()).split() x1=int(a[0]) y1=int(a[1]) x2=int(a[2]) y2=int(a[3]) s+=(x2-x1+1)*(y2-y1+1) print(s)
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
3
s=input() t=input() c = "bcdfghjklmnpqrstvwxyz" v = "aeiou" ans=0 if(len(s)!=len(t)): print("No") else: for i in range(len(s)): if ((s[i] in c) and (t[i] in c)): ans=ans+1 elif((s[i] in v) and (t[i] in v)): ans=ans+1 else: print("No") break...
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: * All scores are integers ...
3
n_tests = int(input()) for i in range(n_tests): students, nota_max = [int(i) for i in input().split()] notas = [int(i) for i in input().split()] soma = 0 for j in notas: soma = soma + j if soma >= nota_max: break if soma >= nota_max: print(nota_max) el...
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≤ a < b ≤ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
from sys import stdin, stdout """ n = stdin.readline() arr = [int(x) for x in stdin.readline().split()] stdout.write(str(summation)) """ for test in range(int(stdin.readline())): n = int(stdin.readline()) if n%2==1 : print((n-1)//2) else : print(n//2)
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
w = [ 'Anton', 'Danik', 'Friendship' ] i = int(input()) a = input() if a.count('A') > int(i) / 2: print(w[0]) elif a.count('A') == int(i) / 2: print(w[2]) else: print(w[1])
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
""" codeforces solution by 8sq - 2020/08/11 18:26:34 """ def solve(): n, m = map(int, input().split()) b = [input() for _ in range(n)] bottom = b[-1][:-1] right = "".join([r[-1] for r in b[:-1]]) print(bottom.count("D") + right.count("R")) def main(): cases() def cases(): for _ in range(i...
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only m times. You are allowed t...
1
import sys input = sys.stdin.readline n, m, k = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = (a[-1] * k + a[-2]) * (m / (k+ 1)) + ((m % (k + 1)) * a[-1]) print ans
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve th...
3
for _ in range(int(input())): N = int(input()) A = list(map(int,input().split())) d = [] sum_ = 0 for i in A: d.append([i,0]) sum_ += i for i in range(N - 1): a,b = map(int,input().split()) d[a - 1][1] += 1 d[b - 1][1] += 1 d.sort(reverse = True) a...
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
if __name__ == "__main__": n = int(input()) numbers = input() ones = 0 for e in numbers: if e == "1": ones += 1 zeros = n - ones result = abs(ones - zeros) print(result)
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array s...
3
for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) X = sum(A) if X % n: print(-1) continue X //= n print(3 * n - 3) for i in range(1, n): print(1, i + 1, (-A[i]) % (i + 1)) print(i + 1, 1, (A[i] - 1) /...
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ...
1
from __future__ import division, print_function # import threading # threading.stack_size(2**27) # import sys # sys.setrecursionlimit(10**7) from sys import stdin, stdout import bisect #c++ upperbound import math import heapq i_m=9223372036854775807 def modinv(n,p): return pow(n,p-2,p) def cin(): ret...
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
3
def DecimalToBinary(a): s=[] while a >= 1: s.append(a%2) a=a//2 return s def find_sum(a,p,sum): for i in range(len(a)): if a[i]//(2**p) > 0: for j in range(p): a[i]=a[i]//2 sum=sum+a[i]%2 return sum t=int(input()) l=[] for i in range(t...
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se...
3
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import sys def sol(n, pos, l, r): total = 0 if l == 1 and r == n: return 0 if l == 1: return abs(pos-r) +1 if r == n: return abs(pos-l) + 1 if pos < l: ...
Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible. ...
1
import fractions as fr T = int(raw_input()) a = map(int,raw_input().split()) print reduce(fr.gcd,a)*T
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The si...
3
n = int(input()) a = [1, 2, 4, 3] b = [1, 3, 4, 2] c = [1, 4] ans = 1 + c[n % 2] + b[n % 4] + a[n % 4] print(ans % 5)
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
3
N = int(input()) ans = 0 for i in range(N-2): ans += (i+2)*(i+3) print(ans)
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
import sys def make_row(line): return list(map(int, line.split(' '))) def steps_to_make_beautiful(matrix): done = False r = 0 for row in matrix: c = 0 for item in row: if item == 1: done = True break; c = c + 1 if done: ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
str_1 = input().lower() str_2 = input().lower() if str_1 > str_2: print(1) elif str_1 < str_2: print(-1) elif str_1 == str_2: print(0)
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ...
3
import sys input = lambda: sys.stdin.readline().strip("\r\n") n = int(input()) w = list(map(int, input().split())) one = w.count(100) two = w.count(200) # print(one) # print(two) if (one * 0.5 == two) or (two % 2 == 0 and one % 2 == 0) or (two % 2 == 1 and one % 2 == 0 and one >= 2): print("YES") else: print(...
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and ...
3
a, b = input().split() best = a[0] + b[0] for i_a in range(len(a)): for i_b in range(len(b)): cur = a[0:i_a+1] + b[0:i_b+1] if cur < best: best = cur print(best)
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn. The variance α2 is defined by α2 = (∑ni=1(si - m)2)/n where m is an average of si. The standard deviation of the scores is the square root of their variance. Constraints * n ≤ 1000 * 0 ≤ si ≤ 100 Inpu...
1
import sys mode = 0 for line in sys.stdin: if mode == 0: n = int(line.strip('\n')) if n == 0: break mode = 1 elif mode == 1: x = [float(i) for i in line.strip('\n').split()] ave = sum(x) / n std = (sum([(i-ave)**2 for i in x])/n)**0.5 print std m...
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...
1
for _ in range(input()): x,y,p,q=map(int,raw_input().split()) if not p: print -1 if x else 0 elif p==q: print -1 if x!=y else 0 else: t=max((x+p-1)/p,(y-x+q-p-1)/(q-p)) print q*t-y
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
def count(a): digits = list(str(a)) delta = int(min(digits)) * int(max(digits)) return a + delta, delta t = int(input()) while t > 0: t -= 1 a, k = [int(x) for x in input().split()] for i in range(k-1): a, d = count(a) if d == 0: break print(a)
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
""" Author : thekushalghosh Team : CodeDiggers """ import sys,math input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s) - 1]) def i...
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a. Will the robot be able to build the fence Emuskald...
1
n = input() res = [] zero = 0.00000057 for i in xrange(n): a = input() if a != 180 and abs((360.0 / (180 - a)) - (360 / (180 - a))) < zero: res.append('YES') else: res.append('NO') for i in res: print i
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
1
mat = [] for i in xrange(5): mat.append(map(int, raw_input().split())) for j in xrange(5): if mat[i][j] == 1: ans = abs(2 - i) + abs(2-j) print ans
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: 1. They are equal. 2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2...
1
from sys import stdin def sorting(a): if len(a)%2==1: return a a1 = sorting(a[:len(a)/2]) a2 = sorting(a[len(a)/2:]) return a1+a2 if a1<a2 else a2+a1 a = raw_input().split()[0] b = raw_input().split()[0] if sorting(a)==sorting(b): print "YES" else: print "NO"
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n ...
3
# Code by Sounak, IIESTS # ------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threa...
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c...
3
i,j = map(int,input().split()) t = 0 while True: if i == 1 and j == 1: break k = min(i,j) if k == i: i = i + 1 j = j - 2 else: j = j + 1 i = i - 2 t = t + 1 if (i <=0) or (j <= 0): break print(t)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a,b,c=[int(input())for i in'abc'];print(max(a*b*c,a*(b+c),(a+b)*c,a+b+c))
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
3
N = int(input()) A = [int(a) for a in input().split()] M = A.count(0) A2 = [a%2 for a in A] O = A2.count(1) E = N - M - O O = (N+1)//2 - O E = N//2 - E C = [M] for a in A: C.append(C[-1] - (a == 0)) X = [[999] * (N+2) for _ in range(N)] Y = [[999] * (N+2) for _ in range(N)] if A[0] % 2: X[0][O] = 0 elif A[0]:...
It's now the season of TAKOYAKI FESTIVAL! This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i. As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points. There are \frac{N...
3
n = int(input()) a = list(map(int, input().split())) sqsum = sum(i*i for i in a) ans = (sum(a)*sum(a) - sqsum) //2 print(ans)
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
for qq in range(int(input())): s = [list(input()) for i in range(9)] if s[0][0]=="9": s[0][0] = "1" else: s[0][0] = chr(ord(s[0][0])+1) if s[3][1]=="9": s[3][1] = "1" else: s[3][1] = chr(ord(s[3][1])+1) if s[6][2]=="9": s[6][2] = "1" else: s[6][2] = chr(ord(s[6]...
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions ...
3
a = int(input()) b = int(input()) if (a - b) % 2 == 1: print("-1") exit(0) x = (a - b) // 2 y = a - x print(x, y)
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ...
3
s = [] l = input() c = 0 for i in l: if len(s) == 0 or len(s) == 1: s.append(i) else: if i == s[c-1] == s[c-2]: continue elif i == s[c-1] and s[c-2] == s[c-3]: continue else: s.append(i) c = c + 1 print("".join(s))
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a...
3
'''input 3 4 5 1 0 3 2 2 2 100 1 1 8 0 ''' import sys # from math import ceil read = lambda: list(map(int,sys.stdin.readline().strip().split())) for i in range(int(input())): n,d = read() a = read() count = a[0] for ind in range(1,n): temp = a[ind] quo,rem = divmod(d,ind) if quo...
The flag of Berland is such rectangular field n × m that satisfies following conditions: * Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. * Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color. ...
3
def matrixTranspose( matrix ): if not matrix: return [] return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ] def f(x): #print(x) bool=True b,r,g=0,0,0 col=['e'] for row in x: if all(el=='R' for el in row): r+=1 if col[-1] != 'r': ...
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ...
3
## necessary imports import sys input = sys.stdin.readline # from math import ceil, floor, factorial; def ceil(x): if x != int(x): x = int(x) + 1; return x; # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if...
Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of len...
1
n = int(raw_input()) l = [int(i) for i in raw_input().split()] ans = -1 for i in range(n): for j in range(n): for k in range(n): if l[i] == l[j] + l[k] and i != j and j != k and i != k: ans = ' '.join(str(i+1) for i in [i, j, k]) print ans
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa...
3
a,b,c,d = map(int, input().split()) mi, mid, ma = sorted((a,b,c)) secs = max(-((mid - mi) - d), 0) secs += max(-((ma - mid) - d), 0) print(secs)
Snuke has an integer sequence A of length N. He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen. Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the ma...
3
import bisect def getlist(): return list(map(int, input().split())) #処理内容 def main(): N = int(input()) A = getlist() B = [0] for i in range(N): B.append(B[-1] + A[i]) #print(B) ans = float("inf") for i in range(2, N - 1): Q = B[i] x = bisect.bisect_left(B, Q // 2) P = max(B[x], B[1]) P = min(P, B[i ...
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] a.sort() l = [] for i in range(n-1): l.append(abs(a[i+1] - a[i])) l.sort() print(l[0])
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math a=input() mod=int(1e9+7) ans=int(0) sum=0 def pow(c): ans=1 c=int(c) base=2 while c: if c%2==1: ans=(ans*base)%mod base=(base*base)%mod c=int(c/2) return ans for s in(a): if s=='b': if sum>=1: ...
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
1
n= input("") arr= raw_input("").split(' ') largest=0 ans= "YES" for i in range(n): arr[i]= int(arr[i]) for i in range(n): if arr[i]>largest: index=i largest= arr[i] for i in range(index): if arr[i+1]-arr[i]<0: ans= "NO" break if ans != "NO": for i in range(index...
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
3
import sys lines = [line for line in sys.stdin] gs =['S','H','C','D'] js = list(map(str,range(1,14))) all=[g + " " +j for g in gs for j in js] for g in lines[1:]: g=g.strip() all.remove(g) for g in all: print(g)
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as...
3
import sys n = int(input()) a = list(map(int, input().split())) d = [] for i in range(1,n): d.append(abs(a[i] - a[i - 1])) evencur = 0; sgn = 1; ans = 0; for i in range(len(d)): evencur += d[i] * sgn; sgn *= -1; ans = max(evencur, ans) if evencur < 0: evencur = 0; sgn = 1; evencur = ...
For an integer N, we will choose a permutation \\{P_1, P_2, ..., P_N\\} of \\{1, 2, ..., N\\}. Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i. Find the maximum possible value of M_1 + M_2 + \cdots + M_N. Constraints * N is an integer satisfying 1 \leq N \leq 10^9. Input Input is giv...
3
a = int(input()) sub = a*(a-1)//2 print(sub)
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
n=int(input()) arr=[] dic={} for i in range(n): arr.append([int(i) for i in input().split()]) if(arr[-1][1] not in dic): dic[arr[-1][1]]=1 else: dic[arr[-1][1]]+=1 ans=0 for i in range(n): if(arr[i][0] in dic): col=arr[i][0] p=dic[col] ans+=p print(ans)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
x = input() print("YES" if '0000000' in x or '1111111' in x else "NO")
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases. A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase ha...
3
for i in range(int(input())): a = int(input()) k, w = 1, 1 counter = 1 a -= 1 while a >= 4*k + 2*w : counter += 1 k = 4*k + 2*w w = 2*w a -= k print(counter)
Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively. An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to ...
3
import math A,B,H,M = map(int, input().split()) C2=A*A+B*B-2*A*B*math.cos(math.pi*((H*60+M)-12*M)/360) print(math.sqrt(C2))
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$. A column vector with m elements is represented by the following equation. \\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\] A $n \times m$ matrix with $m$ column ve...
3
n,m = map(int,input().split()) a = [list(map(int,input().split())) for x in range(n)] b = [int(input()) for x in range(m)] for x in range(n): c = 0 for y in range(m): c += a[x][y]*b[y] print(c)
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves...
1
n = int(raw_input()) matriz = [] vis = [] count = 0 for i in range(n): x,y = map(int,raw_input().split()) matriz.append([x,y]) def dfs(z): if z in vis : return else : vis.append(z) for i in range(len(matriz)): if matriz[i] != z : if matriz[i][0] == z[0] or matriz[i][1] == z[1]: ...