problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white. Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po...
1
W, H, N = map(int, raw_input().split()) b_w = [0, W] b_h = [0, H] for i in range(N): # ta_list.append(map(int, raw_input().split())) x, y, a = map(int, raw_input().split()) if a == 1 and x > b_w[0]: b_w[0] = x elif a == 2 and x < b_w[1]: b_w[1] = x elif a == 3 and y > b_h[0]: ...
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
t=int(input()) for _ in range(t): n=int(input()) a=[int(s) for s in input().split()] for i in range(0,n): cnt=a.count(a[i]) if cnt>=3: print("YES") break elif i!=0 and i!=n-1 and cnt==2 and a[i]!=a[i+1] and a[i]!=a[i-1]: print("YES") br...
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
n=int(input()) for z in range(0,n): sum=0 piles=input().split(" ") for p in piles: sum+=int(p) print(sum//2)
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
3
n = int(input()) li = list(map(int,input().split(" "))) a = max(li) s=0 for i in li: s = s+(a-i) print(s)
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
def make(s,n): arr=[] for i in range(n): arr.append(7) for i in range(1,n): try: if s[i]=='G' and s[i-1]=='B': arr[i]=1 arr[i-1]=0 except: pass ss = '' for i in range(n): if arr[i]==0: ss = ss + 'G' ...
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k. You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu...
1
#! /Library/Frameworks/Python.framework/Versions/2.6/bin/python inp = raw_input().split() n = int(inp[0]) k = int(inp[1]) def countAbove(minElem,lookupSet): ans = 1 if (minElem*k in lookupSet): ans += countAbove(minElem*k,lookupSet) return ans if (k == 1): print n else: inp = raw_input().split() a = [int(in...
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
t=int(input()) for i in range(t): n=int(input()) l=list(map(int,input().split())) m=min(l) var=1 for qq in range(len(l)): if((l[qq]-m)%2!=0): var=0 break if(var==1): print("YES") else: print("NO")
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict o...
3
n=int(input()) l=[] for i in range(n): x=input().split() c=[] for j in range(2): c.append(x[j]) l.append(c) for i in range(n): if(l[i][1]=='rat'): print(l[i][0]) for i in range(n): if(l[i][1]=='woman' or l[i][1]=='child' ): print(l[i][0]) for i in range(n): if(l[i][1]...
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper. Help Kurt find the maximum possible product of digits among all integers from 1 to n. Input The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9). Output Print the...
3
#codeforces1143B_live gi = lambda : list(map(int,input().strip().split())) def p(m): ans = 1 for e in m: ans *= int(e) return ans def f(m): if m == "": return 1 if len(m) == 1: return int(m) if int(m[0]) == 1: return f("9"*(len(m)-1)) if m[0] == "0": return f(m[1:]) return max(p(str(int(m[0])-1)+"9"*(...
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
for _ in range(int(input())): x = int(input()) if x % 2 == 0: print(x >> 1, x >> 1) else: print(1, x-1)
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
n = 5 pos = [input().find('1') // 2 + 1 for i in range(n)] print([abs(n // 2 + 1 - i) + abs(n // 2 - idx) for idx, i in enumerate(pos) if i][0])
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,...
3
#!/usr/bin/python3 n = int(input()) tanya = [int(x) for x in input().strip().split()] stairs = 1 count_stairs = [] for i in range(1, n): if tanya[i] == 1: stairs += 1 count_stairs.append(tanya[i-1]) count_stairs.append(tanya[n-1]) print(stairs) for i in range(len(count_stairs)): print(count_st...
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha...
3
GI = lambda: int(input()); GIS = lambda: map(int, input().split()); LGIS = lambda: list(GIS()) def main(): m1 = input() m2 = input() def stot(s): h, m = map(int, s.split(':')) return h * 60 + m m1t = stot(m1) m2t = stot(m2) mm = (m2t + m1t) / 2 print('%02i:%02i' % divmod(...
Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations: * find(s, t): report the minimum element in as, as+1, . . . ,at. * update(i, x): change ai to x. Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 10000...
3
class RMQ: def __init__(self, length, ini_num = float("inf")): self.length = 1 self.ini_num = ini_num while self.length < length: self.length <<= 1 self.segtree = [ini_num] * (2 * self.length - 1) def update(self, index, n): leaf_index = index + self.length -...
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
1
n, m, a = raw_input().split() n = long(n) m = long(m) a = long(a) x = n / a if n % a != 0: x += 1 y = m / a if m % a: y += 1 print x * y
problem There are the following two-player card games. * This game uses a total of 2n cards with each integer from 1 to 2n written on it. Here, n is an integer between 1 and 100. * Deal n cards to each of the two. * Put cards into play alternately one by one according to the following rules. * If there are no cards i...
3
import bisect while True: n = int(input()) if not n: break cards = [None, None] cards[0] = sorted(map(int, (input() for _ in range(n)))) cards[1] = sorted(set(range(1, 2 * n + 1)).difference(cards[0])) turn = 0 field = 0 while True: idx = bisect.bisect(cards[turn], fiel...
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same tim...
3
import math a, b = map(int, input().split()) c, d = map(int, input().split()) while b != d: if min(b, d) > 20000: break if b > d: d += c else: b += a print(b if b == d else -1)
N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals. The preliminary stage consists of several rounds, which will take place as follows: * All the N contestants will participate in the first round. * W...
3
M = int(input()) d, c = zip(*[[int(x) for x in input().split()] for _ in range(M)]) n_digits = sum(c) # 桁数 sum_digits = sum(d[i] * c[i] for i in range(M)) ans = n_digits - 1 + (sum_digits - 1) // 9 print(ans)
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ash...
1
r=lambda:map(int,raw_input().split()) n,m=r() c=sorted(r()) from collections import defaultdict as d D=d(int) for i in m*[0]: D[raw_input()]+=1 v=sorted(D.values()) sm=0 sM=0 for i in range(len(v)): sm+=v[i]*c[len(v)-i-1] sM+=v[i]*c[-(len(v)-i)] print sm,sM
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
import math import os import sys import re import itertools import functools import operator a, b = input(), input() if a == b[::-1]: print('YES') else: print('NO')
Three people, A, B and C, are trying to communicate using transceivers. They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively. Two people can directly communicate when the distance between them is at most d meters. Determine if A and C can communicate, either ...
1
a, b, c, d = map(int,raw_input().split()) print "Yes" if (abs(a-b)<=d and abs(b-c)<=d) or abs(a-c)<=d else "No"
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of las...
3
inp=input() li=[] for i in inp: li.append(int(i)) sum1=sum(li[:3]) sum2=sum(li[3:]) if sum2>sum1: for i in range(3): li[i]=9-li[i] for i in range(3,6): li[i]=li[i] else: for i in range(3): li[i]=li[i] for i in range(3,6): li[i]=9-li[i] li.sort(reverse=True) dif=max(sum1,sum2)-min(sum1,sum2) cur=0 for i in ...
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 ...
1
n, a, b = map(int, raw_input().split()); print n - max(a + 1, n - b) + 1;
Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload. Minimum dimension of the picture can be L x L, where L is the length of the side of square. Now Roy has N photos of various dimensions. Dimension of a photo is denoted as W x H wh...
1
l=int(raw_input()) n=int(raw_input()) for i in range(n): a,b=map(int,raw_input().split()) if(a==b and a>l and b>l): print("ACCEPTED") elif(a<l or b<l): print("UPLOAD ANOTHER") elif(a>l or b>l): print("CROP IT") else: print("ACCEPTED")
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
3
n=int(input()) m=1 while 1 : if m*m>=n and (m-1)*2>=n-1: break else: m+=1 print(m) i=1 j=1 for x in range(n): if i<m: print(i,j) i+=1 else: print(i,j) j+=1
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()) c=0 for x in range(n): p,v,t=(int(x) for x in input().split()) res=p+v+t if (res>=2): c=c+1 print(c)
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
3
# -*- coding: utf-8 -*- """ Created on Sun Apr 7 14:36:58 2019 @author: Administrator """ input() print(*sorted(map(int,input().split())))
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in...
3
[N,V] = list(map(int,input().split())) j = N-1 i = 2 j -= min(N-1,V) cost = min(N-1,V) while(j > 0): j -= 1 cost += i i += 1 print(int(cost))
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ...
3
from math import * r,x,y,a,b=map(int,input().split()) z=(a-x)**2+(b-y)**2 d=z**0.5 d=ceil(d/(2*r)) print(d)
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means...
3
from collections import namedtuple import math if __name__ == "__main__" : n = int(input()) count = 0 arr = [] for i in range(0,n) : num = int(input()) if(num%2 == 0) : arr.append(int(num/2)) else: if(count%2 == 0) : arr.appen...
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
3
import sys def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): p1, p2 = input().split() n = int(input()) print(p1, p2) for i in range(n): s1, s2 = input().spli...
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
1
#!/usr/bin/env python [n, l, r] = map(int, raw_input().split()) def find_length(nr): if (nr <= 1): return 1 else: return 1+2*find_length(nr/2) def range_sum(nr, length, l, r): if (nr == 0): return 0 elif (nr == 1): if (r >= l): return 1 else: return 0 else: result = 0 ...
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st...
3
a = [] for _ in range(int(input())): p = 0 for o in input().split(): p += int(o) a.append(p) c = a[0] a = sorted(a, reverse=True) print(a.index(c) + 1)
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horse...
1
from sys import stdin,stdout t = int(stdin.readline()) while t > 0: n = int(stdin.readline()) s = map(int,stdin.readline().split()) s.sort() min = s[1] - s[0] for i in xrange(1,len(s)-1): if s[i+1] - s[i] < min: min = s[i+1] - s[i] stdout.write(str(min)+"\n") t -= 1
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
1
n,k = map(int,raw_input().split()) scores = map(int, raw_input().split()) res = 0 k-=1 for i in range(0,n): if scores[i] >= scores[k] and scores[i]>0: res+=1 print res
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls. Takahashi will distribute these 3N balls to N people so that each pe...
3
#!/usr/bin/env python3 import sys MOD = 998244353 # type: int def solve(N: int, S: str): # N = 2 * (10 ** 5) # S = 'R' * N + 'G' * N + 'B' * N c2n = {'R': 0, 'G': 1, 'B': 2} rgb = [[] for i in range(3)] for i, c in enumerate(S): c = c2n[c] rgb[c].append(i) S = [0] * N ...
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
n = int(input()) s = str(input()) if s.count('A') > s.count('D'): print("Anton") elif s.count('A') < s.count('D'): print('Danik') else: print('Friendship')
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a l...
3
def accounting(r,pl,p): for i in range(-1000, 1002, 1): if r * (i ** p) == pl: print(i) break else: print("No solution") r, pl, p = map(int, input().split()) accounting(r,pl,p)
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: * Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) * Type 2: answer the number of different characters occurring in the substring of S betwee...
3
N = int(input()) S = input() L = 20 M = [1<<i for i in range(L)] T = [[0]*m for m in M] o = ord('a') for i, c in enumerate(S): T[-1][i] = 1<<(ord(c)-o) for l in range(L-2, -1, -1): for i in range(M[l]): T[l][i] = T[l+1][i*2] | T[l+1][i*2+1] def q(layer, n, l, r): length_block = (1<<(L-1))//...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
a=input() s=set(a) if len(s)%2==1: print("IGNORE HIM!") else: print("CHAT WITH HER!")
Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n). If Nikolay is currently in some room, he c...
3
for _ in range(int(input())): n=int(input()) s=input() t=s[::-1] try: temps=s.index('1')+1 tempt=t.index('1')+1 temps=(n-temps)+1 tempt=(n-tempt)+1 res=max(temps,tempt) res=res*2 except ValueError: res=n print(res)
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
3
n,k=map(int,input().split()) L=list(map(int,input().split())) res=0 while n!=0 and L[0]<=k: L.pop(0) res+=1 n-=1 while n!=0 and L[n-1]<=k: L.pop() res+=1 n-=1 print(res)
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
3
inp=input() inp=inp.split(' ') inp1=input() inp1=inp1.split(' ') i=0 data=[] while i<len(inp1): if int(inp[1])%int(inp1[i])==0: data.append(int(inp1[i])) i=i+1 j=int(max(data)) print(int(int(inp[1])/j))
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can reach huge...
3
a = input() b = input() if len(a)>len(b):b = '0'*(len(a)-len(b)) + b else:a = '0'*(len(b)-len(a)) + a for i in range(0,len(a)): if(a[i]>b[i]): print('>') exit() elif(b[i]>a[i]): print('<') exit() print('=')
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N? Constraints * 2 \leq N \leq 10^6 * All values in input are integers. Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 3 Output 3 Input 100 ...
3
N=int(input()) S=N-1 ret=0 for i in range(1,N+1): ret+=S//i print(ret)
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input T...
3
# print ("Input n, t--all on one line, separated by spaces") n,t = (int(x) for x in input().split()) start = 1 found = False for i in range(n-1): start *= 10 finish = start * 10 for i in range(start, finish): if i % t == 0: print(i) found = True break if not found: print(-1)
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days! In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week. Alice is going to paint some n...
3
t=int(input()) for _ in range(t): n,r=[int(x) for x in input().split()] p=min(n-1,r) ans=(p*p+p)//2 if r>=n: ans+=1 print(ans)
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
# -*- coding: utf-8 -*- """ Created on Thu Nov 7 18:59:35 2019 @author: uditg """ n=int(input()) array=input().split(" ") array=[int(array[i]) for i in range(n)] posi=[each for each in array if each>=0] neg=[each for each in array if each<0] print(sum(posi)-sum(neg))
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0. Each heater has a va...
3
def solve(house, r): last = -1 house[0] = -1 if house[0] == 0 else 0 for i in range(1, len(house)): if house[i] == 1: house[i] = i else: house[i] = house[i - 1] count = 0 while last < len(house)-1: left = max(-1, last - r + 1) right = last + r ...
A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied: * S is a palindrome. * Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome. * The string consisting of the (N+3)/2-st through N-th charact...
3
s=input() n=len(s)//2 print("YNeos"[s[:n]!=s[-n:]::2])
Consider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds. A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel ex...
3
n = int(input()) count = 0 arr = [int(x) for x in input().split()] brr = [int(x) for x in input().split()] c = [0 for i in range(0,100001)] i = 0 j = 0 while i < n: if c[arr[i]]==1: i+=1 continue if arr[i]==brr[j]: i+=1 j+=1 continue else: c[brr[j]]=1 ...
Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n. The Koch curve is well known as a kind of fractals. You can draw a Koch curve in the following algorithm: * Divide a given segment (p1, p2) into three equal segments. * Replace the middle segment by the two sides of...
3
import math def plot(x,y): print(f"{x:.8f} {y:.8f}") def koch(n,x1,y1,x2,y2): if n==0: plot(x1,y1) return ax=(2*x1+x2)/3 ay=(2*y1+y2)/3 bx=(x1+2*x2)/3 by=(y1+2*y2)/3 cx=(bx-ax)*(1/2)-(by-ay)*(math.sqrt(3)/2)+ax cy=(bx-ax)*(math.sqrt(3)/2)+(by-ay)*(1/2)+ay koch(n-1,x...
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead. "What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" ...
3
s = input() st = ['ABC','ACB','BCA','BAC','CAB','CBA'] for i in range(len(s)-2): if s[i:i+3]in st: print("Yes") exit(0) print("No")
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
n=list(input()) v=['a','e','i','o','u','y','Y','A','E','I','O','U'] i=0 p=[] for i in n: if(i not in v): p.append(i) for i in p: print('.',end='') print(i.lower(),end='')
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only. The distance between two letters is defined as the difference between their positions in the alphabet. For example, <image>, and <image>. Also, the distance between two nice strings is defined as t...
3
def STR(): return list(input()) def INT(): return int(input()) def MAP(): return map(int, input().split()) def MAP2():return map(float,input().split()) def LIST(): return list(map(int, input().split())) def STRING(): return input() import string import sys from heapq import heappop , heappush from bisect import * from...
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
# https://codeforces.com/contest/1373/problem/B import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ # do magic here t = int(input()) for _ in range(t): string = input() stack = [] ans = 0 for x in string: if not len(stack): stack.append(x) else: ...
Vasya came up with a password to register for EatForces — a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits. But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin l...
3
for _ in [0]*int(input()): s=list(input());l=[-1]*4;r=range(len(s)) for i in r:l[(s[i]>'9')+(s[i]>'Z')]=i for i in r: j=l.index(-1) if j<3and i not in l:s[i]='0As'[j];l[j]=i print(''.join(s))
The Chef likes to stay in touch with his staff. So, the Chef, the head server, and the sous-chef all carry two-way transceivers so they can stay in constant contact. Of course, these transceivers have a limited range so if two are too far apart, they cannot communicate directly. The Chef invested in top-of-the-line t...
1
# -*- coding: utf-8 -*- """ Created on Wed Mar 16 12:29:47 2016 @author: matteoarno """ import sys data = sys.stdin.readlines() t = int(data.pop(0)) output = [] for i in range(t): r = int(data.pop(0)) chef = map(int,(data.pop(0).split(' '))) head = map(int,(data.pop(0).split(' '))) sous = map(int,(d...
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
3
print('Yes' if input().count('AC') > 0 else 'No')
per nextum in unam tum XI conscribementis fac sic vestibulo perlegementum da varo. morde varo. seqis cumula varum. cis per nextum in unam tum XI conscribementis fac sic seqis decumulamenta da varo. varum privamentum fodementum da aresulto. ...
3
from math import * stack = [] for _ in range(11): stack.append(int(input())) for i in range(11): var = stack.pop() a = sqrt(abs(var)) b = (var ** 3) * 5 res = a + b if res <= 400: print(f'f({var}) = {res:.2f}') else: print(f'f({var}) = MAGNA NIMIS!')
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. <image> You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times...
3
string = input() n = len(string) cnt_link = int(0) cnt_pearl = int(0) for x in string: if x == '-': cnt_link += 1 elif x == 'o': cnt_pearl += 1 if cnt_pearl == 0: print('YES') elif cnt_link % cnt_pearl == 0: print('YES') else: print('NO')
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite. * There exists a non-negative integer j such that the concatenation of i copies of t is a...
3
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) S = input().rstrip() T = input().rstrip() S,T # Sの方が長くする LS = len(S) LT = len(T) n = (LT + (-LT) % LS) // LS S *= (n+1) S = S[:LS+LT] MOD = 10 ** 16 + 61 base = 12345 base_inv = pow(base,MOD-2,MOD) power = [1] * (LS+LT) power_inv = [1] * (LS+LT) ...
There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i. Find the number of different values that the median of X_1, X_2, \cdots, X_N can take. Constraints * 2 \leq N \leq 2 \times 10^5 * 1 \leq A_i \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard ...
3
n=int(input()) a = [0]*n b = [0]*n for i in range(n): a[i], b[i] = map(int, input().split()) a.sort() b.sort() youso = int(n/2) if n % 2 != 0: print(b[youso]-a[youso]+1) else: print((b[youso]+b[youso-1])-(a[youso]+a[youso-1])+1)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) for i in range(0,n): b = input() if len(b) > 10: print(b[0] + str(len(b[1: len(b) - 1])) + b[len(b) - 1]) else: print(b)
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows: * The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.) * Each time the player wins a round, depending on which hand he/she use...
3
n,k=map(int,input().split()) r,s,p=map(int,input().split()) t=list(input()) for i in range(k,n): if t[i]==t[i-k]: t[i]="a" print((t.count("r")*p)+(t.count("s")*r)+(t.count("p")*s))
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot...
3
#!/usr/bin/python -SOO x,n = map(int,input().strip().split()) s = set(range(1,x)) for _ in range(n): xs = list(map(int,input().strip().split())) if xs[0] == 2: s.remove(xs[1]) else: s.remove(xs[1]) s.remove(xs[2]) m,i= 0,0 s = sorted(s) while i < len(s): if i==len(s)-1: m...
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
#!/usr/bin/python # -*- coding: utf-8 -*- men = input() + input() mixed = input() if len(men) != len(mixed): print('NO') exit() else: for c in men: if men.count(c) != mixed.count(c): print('NO') exit() print('YES')
There are N empty boxes arranged in a row from left to right. The integer i is written on the i-th box from the left (1 \leq i \leq N). For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it. We say a set of choices to put a ball or not in the boxes is good when the following con...
3
n = int(input()) a = list(map(int, input().split())) ans = a[:] for i in reversed(range(n)): ans[i] = sum(ans[i :: i + 1]) % 2 print(sum(ans)) print(*[i + 1 for i in range(n) if ans[i]])
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
1
n = input() s = raw_input() s1 = [] s2 = [] for i in range(n): s1.append(int(s[i])) for i in range(n,2*n): s2.append(int(s[i])) s1.sort() s2.sort() f1 = 1; f2 = 1; for i in range(n): if s1[i] <= s2[i]: f1 = 0; for i in range(n): if s1[i] >= s2[i]: f2 = 0; if f1 or f2: print "YES" else: print "NO"
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid f...
3
t = int(input()) for ti in range(t): n = int(input()) grid = [] for tn in range(n): grid.append(input()) bord = [ grid[1][0], grid[0][1], grid[n-1][n-2], grid[n-2][n - 1] ] ans = [] for ls in [ [ '0', '0' , '1' , '1'], ['1', '1', '0', '0' ]]: ans = [] for i in range(4)...
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
3
a, b = map(int, input().split()) i = 0 while a > 0: a -= 1 i += 1 a = i while a > 0 and a >= b: i = i + a // b a = a // b + a % b print(i)
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 — the base of the ladder; * k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
3
def main(): T = int(input()) for _ in range(T): n = int(input()) a = [int(s) for s in input().split()] a.sort() print(min(a[-2] - 1, n - 2)) if __name__ == '__main__': main()
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
1
n = int(raw_input()) total = sum(map(int,raw_input().split())) print '%.5f' %(float(total)/n)
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
1
hld=[] for x in xrange(2): hld.append(raw_input()) if (hld[0])[::-1]==hld[1]: print "YES" else: print 'NO'
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
s = int(input()) a = s%2 while True: if a == 0: if s == 2: print('NO') break else: print('YES') break else: print('NO') break
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
import string input() i=input().strip().lower() if len(set(string.ascii_lowercase))-len(set(i)): print('NO') else: print('YES') # http://codeforces.com/problemset/problem/520/A
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling. Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t...
3
import sys input = sys.stdin.readline from collections import Counter t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) c = list(Counter(a).values()) c.sort(reverse=True) k = list(Counter(c).values()) # print(c) # print(k[0]) if k[0] == 1: ...
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if...
3
for _ in " "*int(input()): a=int(input()) if a<4 or a in [5,7,11]:print(-1) else:print((a//4)-((a%4)%2!=0))
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
n = int(input()) sum = 1 for i in range(n): a, b = map(int, input().split()) if a == b: print(0) elif b > a: print(2 - ((b - a) % 2)) else: print((1 + (a - b) % 2))
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
3
a=int(input())-1 c=["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"] while(a>=5): a=(a-5)//2 print(c[a])
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
import math n=int(input()) if(n%2==0): print(int(math.ceil(n/2))) else: print(int(math.ceil(n/2))*(-1))
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. T...
3
n=int(input()) mod=1000000007 print(int((pow(3, n, 4*mod)+3*(-1)**n)/4)%(4*mod))
Coach Ankit is forming a team for the Annual Inter Galactic Relay Race. He has N students that train under him and he knows their strengths. The strength of a student is represented by a positive integer. The coach has to form a team of K students. The strength of a team is defined by the strength of the weakest stude...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' xFac = [1] * 100001 xFacInv = [1] * 100001 mod = 1000000007 def nCr(n,r): return (((xFac[n] * xFacInv[r]) % mod) * xFacInv[n-r]) % mod def xFacMod(): for i in range(1, len(xFac)): ...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
3
z=int(input()) x=input().split() y=[int(i)for i in x] m=0 n=0 i=0 while i < z: if y[i] % 2 ==0: a=i m+=1 else: b=i n+=1 i+=1 if m>n: print(b+1) else: print(a+1)
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
3
m,n = [int(x) for x in input().split()] tes = min(m,n) if(tes%2==0): print ("Malvika") else: print ("Akshat")
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market. She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and al...
3
n,p=[int(i)for i in input().split()] i=0 a=[] while i<n:a.append("half"!=input());i+=1 s=c=0 for x in a[::-1]:s+=c*p+x*p//2;c=c*2+x print(s)
There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N. For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j. If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not. Find ...
3
#!/usr/bin/env pypy3 def I(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(map(int, input().split())) def main(): mod=10**9+7 N,K=MI() a=[[]for _ in range(N)] for i in range(N): a[i]=LI() adj=[[]for _ in range(N)] for i in range(N): f...
There are N points on the 2D plane, i-th of which is located on (x_i, y_i). There can be multiple points that share the same coordinate. What is the maximum possible Manhattan distance between two distinct points? Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-...
3
N=int(input()) xy = [] d0, d1 = [],[] for _ in range(N): x,y=map(int,input().split()) d0.append(x-y) d1.append(x+y) print(max(max(d0)-min(d0), max(d1)-min(d1)))
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
input() scores = input() scoresList = scores.split() biggest = None smallest = None amazing = 0 count = 0 for i in scoresList: if count == 0: biggest = int(i) smallest = int(i) if count != 0: if int(i) > biggest: biggest = int(i) amazing += 1 if int(i)...
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. Input The ...
3
n,k = list(map(int,input().split())) for i in range(n): for j in range(n): if j == i: print(k,end=' ') else: print(0,end=' ') print()
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) k1,k2,k3=0,0,0 for i in range(n): l=list(map(int,input().split())) k1+=l[0] k2+=l[1] k3+=l[2] if(k1==0 and k2==0 and k3==0): print("YES") else: print("NO")
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen...
3
import sys from math import sqrt import math input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().spli...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n = int(input()) items = [] count = 0 for _ in range(n): items.append(input()) for item in items: if item == "Tetrahedron": count += 4 elif item == "Cube": count += 6 elif item == "Octahedron": count += 8 elif item == "Dodecahedron": count += 12 elif item == "I...
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
1
from sys import stdin rint = lambda: int(stdin.readline()) for _ in range(int(input())): n = rint() print('%d\n%s' % (n - 1, ' '.join(map(str, range(2, n + 1)))))
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w = int(input()) if (w % 2) == 0 and w // 2 >= 2: print('YES') else: print('NO')
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
3
glas = ['a', 'e', 'i', 'o', 'u', 'y'] n = int(input()) s = input() res = s[0] for i in range(1, len(s)): if s[i] in glas and s[i - 1] in glas: pass else: res += s[i] print(res)
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighb...
3
# https://codeforces.com/problemset/problem/165/A import sys #-----------------------------------------------------------------------------# try: sys.stdin = open('inputs.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass finally: input = sys.stdin.readline print = sys.stdout.write #-----...
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
3
n,c = map(int,input().split(" ")) t = list(map(int,input().split(" "))) m = 0 ans = 1 if n > 1: for i in range(n-1): if t[i+1] - t[i] > c: m = i+1 # print(m) ans = n-m print(ans)
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). A sequence a is a subsegment of a...
3
n,m=map(int,input().split()) fact=[1] for i in range(1,n+1): fact.append((fact[-1]*i)%m) ans=0 val=n for i in range(1,n+1): t=(((val*val)%m)*(fact[i]%m)*(fact[n-i]%m))%m ans=(ans+t)%m val=(val-1)%m print(ans)
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
3
def solve(): print(max(min(a, b) * 2, max(a, b)) ** 2) return t = int(input()) for i in range(t): a, b = [int(i) for i in input().split()] solve()