problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b. Constraints * 0 < a, b ≤ 2,000,000,000 * LCM(a, b) ≤ 2,000,000,000 * The number of data sets ≤ 50 Input Input consists of several data sets. Each data set contains a and b separated by a single spa...
1
def gcd(x, y): if y == 0L: return x elif x < y: return gcd(y, x) else: ny = x % y return gcd(y, ny) while True: try: inpt = map(long, raw_input().split()) g = gcd(inpt[0], inpt[1]) h = inpt[0] * inpt[1] / g print str(g) + ' ' + str(h) except: break
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import math for _ in range(int(input())): a,b,c,d=map(int,input().split()) if b>=a: print(b) else: if c-d<=0: print(-1) else: print(b+ math.ceil((a-b)/(c-d))*c)
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
3
total = int(input()) arr = list(map(int, input().split())) result = [0]*int(total) index = total - 1 previous_number = 0 current_start = 0 for x in range(len(arr)): if(x == 0): previous_number = arr[0] result[index] = arr[0] index -= 1 elif(arr[x] > previous_number): current_star...
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). Input The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. Output Print "YES" (without the quot...
3
word = input() ab = {} ba = {} for i in range(len(word)-1): if word[i]+word[i+1]=='AB': ab[i] = 1 elif word[i]+word[i+1]=='BA': ba[i] = 1 f = 0 for i in ab: for j in ba: if j!=i-1 and j!=i+1: f = 1 break if f==1: break if f==0: print("NO") else...
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
n=int(input()) o=[-1 for i in range(n+1)] a=list(map(int,input().split())) b=list(map(int,input().split())) d={} for i in range(n): o[a[i]]=i for i in range(n): x=o[b[i]] if x-i>=0: if x-i in d: d[x-i]+=1 else: d[x-i]=1 else: if n+x-i in d: d[n...
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da...
3
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(n-r)) def factorial(n): if n==0: return 1 else: init = 1 for i in range(1, n + 1): init *= i return init n=int(input()) d=n//2 ways=factorial(d-1) combination=ncr(n,d)//2 ans=combination*ways*ways print(an...
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
for nt in range(int(input())): n=int(input()) l=list(map(int,input().split())) flag=0 d={} for i in range(n): if l[i] not in d: d[l[i]]=[i] else: d[l[i]].append(i) for i in d: if len(d[i])>2: print ("YES") flag=1 break elif len(d[i])==2: if d[i][1]-d[i][0]>1: print ("YES") flag=1...
Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her. Constraints * 1≦A,B≦10^9 * op is either `+` or `-`. Input The input is given from Standard Input in the following format: A op B Outpu...
1
input1 = raw_input() split_input = input1.split() if(split_input[1] == u'+'): print int(split_input[0]) + int(split_input[2]) else: print int(split_input[0]) - int(split_input[2])
A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result. He knows that the con...
1
x,t,a,b,da,db=map(int,raw_input().split()) def judge(): if 0==x: return True for t1 in range(t): if x==a-da*t1: return True for t2 in range(t): if x==a-da*t1+b-db*t2: return True if x==b-db*t2: return True return False print 'YES' if judge() else 'NO'
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A. An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik. Constraints * 1 ≤ n ≤ 100000 * 0 ≤ ai ≤ 109 Input n a0 a1 : ...
3
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_D&lang=ja from bisect import bisect_left import sys read = sys.stdin.read readline = sys.stdin.readline readlines = sys.stdin.readlines def main(): N,*A = map(int, read().split()) LIS = [A[0]] for a in A: if a > LIS[-1]: ...
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
3
c, a, b = map(int, input().split()) S = a*c//2 print(S)
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin...
3
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from heapq import * def main(): n,m=map(int,input().split()) a=[list(map(int,input().split())) for _ in range(m)] edges,j,b=[[]]*m,1,sorted(range(m),key=lambda x:a[x][0]*10000000000-a[x][1]) ...
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()) x=0 y=0 z=0 for i in range(n): x1,y1,z1=map(int,input().split(' ')) x+=x1 y+=y1 z+=z1 if(x==0 and y==0 and z==0): print('YES') else: print('NO')
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition: (※) After each turn, (the number of times the player has played Paper)≦(the number of times the ...
3
s = input() g = s.count("g") p = s.count("p") print(len(s)//2-p)
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
a = [] for _ in range(int(input())): k = input() if len(k)>10: a.append(k[0]+str(len(k)-2)+k[len(k)-1]) else: a.append(k) for i in range(len(a)): print(a[i])
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
1
import fractions A=map(int,raw_input().split()) turn = 0 while A[2] > 0: c = fractions.gcd (A[turn], A[2]) A[2] -= c turn += 1 turn %= 2 if turn == 1: print 0 else: print 1
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
3
import bisect import itertools import math import random from collections import Counter, deque, defaultdict from functools import reduce from operator import xor mod = 10 ** 9 + 7 def lmi(): return list(map(int, input().split())) def main(): t = int(input()) for _ in range(t): x1, y1, x2, y2 = l...
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
3
n = int(input()) bil = [int(x) for x in input()] print('YES' if bil.count(4) + bil.count(7) == n and sum(bil[:n//2]) == sum(bil[n//2:]) else 'NO')
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'...
3
n , m , a = map(int,input().split()) Sa = a ** 2 if n % a == 0 and m % a == 0: X = n * m //Sa elif n % a != 0 and m % a == 0: X = (n // a) * (m // a) + m // a elif n % a == 0 and m % a != 0: X = (n // a) * (m // a) + n // a else: X = (n // a) * (m // a) + n // a + m // a + 1 print(X)
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
n=input() s=0 p=0 for i in range(len(n)-1): if n[i+1]==n[i]: s+=1 else: s=0 if s>=6: print("YES") break else: p+=1 if p==len(n)-1: print("NO")
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl...
3
import math x, y = input().split(' ') x, y = int(x), int(y) if x*math.log10(y)<y*math.log10(x): print('>') elif x*math.log10(y)==y*math.log10(x): print('=') else: print('<')
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu...
3
s = list(input().strip()) i = 0 cnt = ("".join(s)).count("VK") indices = [] while i < len(s) - 1: if s[i] == 'V' and s[i+1] == 'K': indices.append(i) indices.append(i+1) i += 2 else: i += 1 for i in range(len(s)-1): if (s[i] == 'V' and s[i+1] == 'V') or (s[i] == 'K' and...
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
1
n,k,l,c,d,p,gas,sol = map(int,raw_input().split()); print min(k*l/gas,p/sol,c*d)/n
Input The input contains a single integer a (0 ≤ a ≤ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
#000010 #000010 #000101 #011000 #100011 #110010 n = bin(int(input()))[2:] while len(n) < 6: n = '0' + n print(int(n[0] + n[5] + n[3] + n[2] + n[4] + n[1], 2))
There are two infinite sources of water: * hot water of temperature h; * cold water of temperature c (c < h). You perform the following procedure of alternating moves: 1. take one cup of the hot water and pour it into an infinitely deep barrel; 2. take one cup of the cold water and pour it into an infin...
3
from sys import stdin for _ in range(int(stdin.readline())): h,c,t = map(int,stdin.readline().split()) if t>=h: print(1) continue if t <= (h+c)/2: print(2) continue n = 1/(1-2*((h-t)/(h-c))) x = round(n) if x%2==0: y = x-1 ex = 2*t*y*(y+2)-2*((y//2...
E869120's and square1001's 16-th birthday is coming soon. Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces. E869120 and square1001 were just about to eat A and B of those pieces, respectively, when they found a note attached to the cake saying that "the same person should not t...
3
a, b=map(int,input().split()) print("Yay!" if 16/a >=2 and 16/b >=2 else ":(")
Problem statement JOI decided to start a new social game from tomorrow. In this social game, you can log in up to once a day, and you will get A coins each time you log in. Also, if you log in for 7 consecutive days from Monday to Sunday, you will get an additional B coins each time. No other coins will be given. ...
3
A,B,C=map(int,input().split(" ")) count=0 while C>0: count+=1 C-=A if count%7==0: C-=B print(count)
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
t = int(input()) while (t > 0): t -= 1 n = int(input()) students = [int(x) for x in input().split()] if (n < 4): print("YES") continue i = students.index(1) students += students success = 1 direction = students[i + 2] - students[i + 1] if (abs(direction) != 1): ...
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
from math import ceil for _ in range(int(input())): a, b, c, d = map(int, input().split()) if a <= b: print(b) elif c <= d: print(-1) else: a -= b ans = b + c * ceil(a/(c-d)) print(ans)
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
t=int(input()) while t: t-=1 a,b,n,s=map(int,input().split()) print(['NO','YES'][max(s%n,s-n*a)<=b])
You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not...
1
from math import ceil n=int(raw_input()) b=map(float,raw_input().split()) pos=0 neg=0 for i in xrange(n): if b[i]/1>0: pos=pos+1 if b[i]/(-1)>0: neg=neg+1 m=int(ceil(n/2.0)) if pos>=m: print 1 elif(neg>=m): print -1 else: print 0
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i × 1 (that is, the width is 1 and the height is a_i). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will...
3
def roof(n, lengths): lengths.sort(reverse=True) for i in range(n): if i+1 > lengths[i]: return i elif i+1 == lengths[i]: return i+1 return i+1 if __name__ == '__main__': q = int(input()) for i in range(q): n = int(input()) lengths = list(m...
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
m,n=list(map(int,input().split())) plist=sorted(list(map(int,input().split()))) div=[] if n-m>0: for i in range(n-m+1): div.append(plist[i+m-1]-plist[i]) print(min(div)) else: print(plist[-1]-plist[0])
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...
1
for _ in range(input()): n=input() a=[ord(i)-97 for i in raw_input()] b=[ord(i)-97 for i in raw_input()] flag=1 for i in range(n): if b[i]-a[i]<0: flag=0 if flag==0: print -1 continue ct=0 for i in range(20): flag=0 minn=10**18 ...
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)...
1
x=input() if(x%2==0):print x/2 else:print x/2-x
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...
1
while(True): try: a = int(input()) c = [] for i in range(a): c.append(raw_input()) for x in range(a): if len(c[x])<=10: print(c[x]) else: print(str(c[x][0]) + str(len(c[x])-2) + str(c[x][-1])) except: ...
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
s=input() s=s.lower() a=list(s) d="" for x in a: if x!='a' and x!='e' and x!='i' and x!='o' and x!='u' and x!="y": d=d+"."+x; print(d)
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
s = input() if (s.isupper()) or (s[0].islower() and s[1:].isupper()) or (s[0].islower() and len(s) == 1): print(s.swapcase()) else: print(s)
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract 1 from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to 1, in other wo...
3
def make(t,a): r=0 neg=0 zero=0 for i in range(t): if a[i]!=0: r += abs(a[i]) - 1 if a[i]<0: neg += 1 else: zero +=1 r+=1 if neg != 0 and (neg%2 != 0 or neg==1) and zero==0: r += 2 print(r) def main(): ...
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order. You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions. Find the maximum value ...
1
''' usage: python prob4.py ''' import sys import os import math def main(argv=None): line=raw_input() line=line.strip() nVertices=int(line) x=[] y=[] for i in range(nVertices): line=raw_input() line=line.strip() parts=line.split() x.append(int(parts[0])) ...
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
n = int(input()) a = input().split() l = [] d = [] for i in a: l.append(int(i)) for i in sorted(l): d.append(str(i)) print(' '.join(d))
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s= input() new_s = '' for i in range(len(s)): if s[i]=='h' and new_s == '': new_s = 'h' elif s[i]== 'e' and new_s == 'h': new_s = 'he' elif s[i]== 'l' and new_s == 'he': new_s = 'hel' elif s[i]== 'l' and new_s == 'hel': new_s = 'hell' elif s[i]== 'o' and new_s == 'hel...
You're given an array a of length n. You can perform the following operation on it as many times as you want: * Pick two integers i and j (1 ≤ i,j ≤ n) such that a_i+a_j is odd, then swap a_i and a_j. What is lexicographically the smallest array you can obtain? An array x is [lexicographically smaller](https://...
3
n = int(input()) xs = list(map(int, input().split())) if len(set(x % 2 for x in xs)) != 1: xs.sort() print(' '.join(map(str, xs)))
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player sp...
3
n=int(input()) n=n//2 print(n*3)
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time pla...
3
n, x = (int(x) for x in input().split()) s = abs(sum(int(x) for x in input().split())) print((s + x - 1) // x)
Xavier asks his friend to perform a particular task.The task is to find out the ASCII value of each character of a given STRING and then add them up to find the weight of the given string as 'W',now after finding out the weight his task is to divide the weight of string W with the length of string 'L'such that the fina...
1
t=int(raw_input()) for i in range(0,t): s=raw_input() l=list(s) l.reverse() f=0 for k in range(0,len(s)): f=f+ord(s[k]) res=f//len(s) if(res%2==0): print s else: out="" for h in range(0,len(s)): out=out+l[h] print out
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r...
3
''' Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. ''' ''' Welcome to GDB Online. GDB online...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
x=list(input()) count=0 for i in range(26): if chr(ord('a')+i) in x: count+=1 print(count)
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'...
3
import math data = [int(x) for x in input().split(' ')] n = data[0] m = data[1] a = data[2] print(math.ceil(n / a) * math.ceil(m / a))
Hooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp! Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years? According to Polycarp, a positive integer is beautiful if it consists of ...
3
for i in range(int(input())): e=int(input()) total=0 radix=1 pointer=1 test=0 while e>=test: test=int(str(pointer)*radix) if test<=e: total+=1 pointer+=1 if not(pointer)%10: pointer=1 radix+=1 print(total)
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
def isLucky(n): s=str(n) if '1' in s or '2' in s or '3' in s or '5' in s or '6' in s or '8' in s or '9' in s or '0' in s: return False return True def isAlmostLucky(n): for i in range(4,(n//2)+1): if not n%i: if isLucky(i): print("YES") return...
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise. Vova thinks that people in the i-th flats are distur...
3
n=int(input()) A=list(map(int,input().split())) c=0 for i in range(1,n-1): if(A[i]==0 and A[i-1]==1 and A[i+1]==1): A[i+1]=0 c+=1 print(c)
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
s=input() if set(str(s.count('4')+s.count('7')))-set(('4','7')): print("NO") else: print("YES")
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret! A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ...
3
import math,sys from sys import stdin,stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda:int(input()) li = lambda:list(map(int,input().split())) def solve(): n=I() a=li() if(len(set(a))==1): print(n) else: print(1) for _ in range(I()): solve...
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, ...
3
k = int(input()) s = input() l = len(s) if l % k != 0: print(-1) else: s = sorted(s) rt = '' for i in range(0, l, k): if s[i] != s[i+k-1]: print(-1) break rt += s[i] else: for i in range(0, k): print(rt, end='') print()
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
from math import * data = raw_input() points = data.split(" ") m = int(points[0]) n = int(points[1]) a = int(points[2]) tilew = int(ceil(n*1.0 / a)) tileh = int(ceil(m*1.0 / a)) tiles = tilew * tileh print tiles
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th m...
3
#Bhargey Mehta (Junior) #DA-IICT, Gandhinagar import sys, math, queue, bisect #sys.stdin = open('input.txt', 'r') MOD = 998244353 sys.setrecursionlimit(1000000) n, k = map(int, input().split()) a = list(map(int, input().split())) w = list(map(int, input().split())) x = [0 for i in range(n+1)] y = [0 for i in range(n+1...
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version. Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell ...
3
from collections import defaultdict import sys input=sys.stdin.readline for _ in range(int(input())): n=int(input()) grid=[] for i in range(n): grid.append(list(input().strip())) arr=[0,0,0] for i in range(n): for j in range(n): if(grid[i][j]=='X'): arr[(i...
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
1
from sys import stdin R = lambda: map(int, stdin.readline()[:-1].split()) n, q = R() a = [0] * n cnt = 0 state = [0] * (n << 1) def check(u1, d1, u2, d2): if state[u1] and (state[d1] or state[d2]): return 1 if state[u2] and (state[d1] or state[d2]): return 1 return 0 while q: q -= 1 ...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
s =input() s=s.replace("WUB",' ') s = s.strip() while ' ' in s: s=s.replace(' ',' ') print(s)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
from sys import stdin,stdout for _ in range(int(stdin.readline())): n=int(stdin.readline()) # r,c=list(map(int, stdin.readline().split())) s=input();ans='';p=0 for i in range(0,n): sub=s[i:i+n] ans+=sub[p] p+=1 print(ans)
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
hm=int(input()) for i in range(hm): n=int(input()) print((n-1)//2)
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Mar...
3
n,m = map(int,input().split()) l = list(map(int,input().split())) am = m max = am for i in range(n): temp = am c = 0 if temp>l[i]: c = temp//l[i] temp-=l[i]*c for j in range(i+1,n): if temp+l[j]*c>max: max = temp+l[j]*c print(max)
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
for _ in range(int(input())): n= int(input()) arr = list(map(int,input().split())) i=su=cr=0 k=-(2*(10**5)+1) maxi=k flag=True while i<n: cur=arr[i] j=i while j<n and cur*arr[j]>0: cur = max(cur,arr[j]) j+=1 su+=cur i=j print(su)
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s. You are asked to choose some integer k (k > 0) and find a sequence a of length k such that: * 1 ≤ a_1 < a_2 < ... < a_k ≤ |s|; * a_{i-1} + 1 < a_i for all i from 2 to k. The characters at positions a_1, a_2, ...,...
3
for _ in range(int(input())): s = list(input()) ssort = sorted(s) if s == ssort: ans = "YES" elif len(s) <= 3: ans = "YES" else: remove1 = True ans = "YES" for i in range(len(s)-1): if remove1: if s[i] == '1' and s[i+1] == '1': ...
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
1
d={} def fact(n): if n==0 or n==1: d[n]=1 return d[n] else: if n in d: return d[n] else: d[n]=n*fact(n-1) return d[n] import sys sys.setrecursionlimit(1000000000) def gcd(a,b): if fact(a)==fact(b): return fact(a) else: r...
AtCoDeer has three cards, one red, one green and one blue. An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card. We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer. Is this integer...
3
print("YES"*(int(input()[::2])%4<1)or"NO")
There are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) deno...
3
import sys import math input = sys.stdin.readline n,m=map(int,input().split()) arr=[0]*n for i in range(m): u,v,d=map(int,input().split()) arr[u-1]-=d arr[v-1]+=d pos=[] neg=[] for i in range(n): if arr[i]>0: pos.append([i,arr[i]]) elif arr[i]<0: neg.append([i,-arr[i]]) # print(pos,neg) ans=[] j=0 for i in ...
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...
3
import math while True: n=int(input()) if n==0: break l = list(map(int, input().split())) s=0 for i in l: s+=((i-sum(l)/n)**2) print("{0:.8f}".format(math.sqrt(s/n)))
Snuke is buying a bicycle. The bicycle of his choice does not come with a bell, so he has to buy one separately. He has very high awareness of safety, and decides to buy two bells, one for each hand. The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively. Find the m...
1
abc = map(int, raw_input().split()) abc = sorted(abc) print abc[0] + abc[1]
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
n,m = map(int,input().split()) a = list(map(int,input().split())) ans = 1000 a.sort() for i in range(0,m-n+1): ans = min(ans,a[i+n-1]-a[i]) print(ans)
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius. He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of...
1
n = int(raw_input()) ns = [] for i in xrange(n): line = map(int, raw_input().split()) ns.append(line) d1, d2 = {}, {} for i in xrange(-n + 1, n): tot = 0 for j in xrange(n): y = j x = i + j if y < 0 or x < 0 or y >= n or x >= n: continue tot += ns[y][x] ...
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
def func(n): a = input().split() ls=[] for i in a: if not(i in ls): ls.append(i) str1 = ls[0]+" " for i in range (1,len(ls)): str1+=ls[i]+" " print(str1) t = int(input()) for i in range(0,t): n=int(input()) func(n)
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109. At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. Aft...
3
def p1(): n = int(input()) for i in range(0,n,1234567): for j in range(0,n-i,123456): if (n-i-j)%1234 == 0: return 'YES' return 'NO' def p2(): n,m = [int(i) for i in input().split()] l = [int(i) for i in input().split()] for i in range(n): if m-i-1 <= 0 : return l[m-1] m = m-i-1 def p3(): n = int...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
s1=input() s2='WUB' i=0 c=1 while i!=len(s1): if len(s1)-i<3: print(s1[i], end='') i = i + 1 continue if s1[i]+s1[i+1]+s1[i+2]=='WUB': if c==0: print(' ',end='') c+=1 i=i+3 else: print(s1[i],end='') i=i+1 c=0
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
3
from sys import stdin,stdout from math import gcd,sqrt,floor,ceil # Fast I/O #input = stdin.readline #print = stdout.write def list_inp(x):return list(map(x,input().split())) def map_inp(x):return map(x,input().split()) def lcm(a,b): return (a*b)/gcd(a,b) a,b = map_inp(int) for i in range(1,10): if (i*a)% 10 ==...
Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it. He has A_i cards with an integer i. Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1. Snuke wants to create the maximum number of pairs from his card...
3
N = int(input()) A = [int(input()) for _ in range(N)] ans = 0 cnt = 0 for i in range(N): if A[i] != 0: ans += (A[i]+cnt)//2 cnt = (A[i]+cnt)%2 else: cnt = 0 print(ans)
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()) count = 0 for i in range(n): a, b, c = map(int, input().split()) if a == 1 and b==1 or a==1 and c==1 or c==1 and b==1: count +=1 print(count)
Suresh is a fan of Mario. But being a programmer he decided to modify the game. In one module he needs your help. He modified the game as follows: There are N stones on the way indexed from 1 to N. Every stone having index i is associated with points equal to i^th fibonacci number. That is if there are 5 stones then th...
1
n ,m = map(int, raw_input().split(' ')) s = sum(map(int, raw_input().split(' '))) v, S, c = [1, 1],0, 0 for i in xrange(2, n): v += [v[i-1]+v[i-2]] print sum(v)-s
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input('')) x = 0 for i in range(n): st = input('') if '+' in st: x = x + 1 elif '-' in st: x = x - 1 print(x)
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
for _ in range(int(input())): n=int(input());A=[];t=0;k=0 if n==2:print(2) else: for i in range(1,n+1): A.append(2**i) #print(A[:n//2-1]) k+=sum(A[:n//2-1]);k+=A[-1];print(abs(sum(A)-2*k))
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
import sys def capitalizeWord(word): return word[0].upper() + word[1:] base_string = input().strip() result = capitalizeWord(base_string) print(result)
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: ...
3
a = list(map(int, input().split())) legs = False leg = 0 for i in range(len(a)): if a.count(a[i]) >= 4: legs = True leg = a[i] break if legs == False: print ("Alien") exit() for i in range(len(a)): if a[i] == leg: a[i] = 0 a.sort() #print (a) if a[len(a)-1] == a[len(a)-2]: print ("Elephant") else: print (...
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
n = sorted(list(map(int, input().split()))) c = n[3] - n[0] a = n[1] - c b = n[2] - c print(a, b, c)
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time...
3
data = input().split() N, M = int(data[0]), int(data[1]) correct = list(map(int, input().split())) wrong = list(map(int, input().split())) V = min(correct) P = max(correct) C = min(wrong) if max(2 * V, P) < C: print(max(2 * V, P)) else: print('-1')
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
from collections import defaultdict import sys, math f = None try: f = open('q1.input', 'r') except IOError: f = sys.stdin if 'xrange' in dir(__builtins__): range = xrange def print_case_iterable(case_num, iterable): print("Case #{}: {}".format(case_num," ".join(map(str,iterable)))) def print_case_number(case_n...
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
pozi, pozj = 0, 0 for i in range(5): if pozi != 0: break v = input().split() for j in range (5): if v[j] == '1': pozi = i+1 pozj = j+1 break print(abs(3 - pozi ) + abs(3 - pozj))
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
line = input().split() n = int(line[0]) m = int(line[1]) piece = int(m / 2)*n if m%2: piece += int(n/2) print(piece)
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
1
exec input()*'print input()-1>>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,m,a=map(int, input("").split()) x=0 y=0 if n%a==0: x=int(n/a) else: x=int((n/a)+1) if m%a==0: y=int(m/a) else: y=int((m/a)+1) print(x*y) ''' ''' words = [] n = int(input("")) for i in range(n): word=input("") if len(word)>10: words.append(str(word[0]+str(len(word)-2)+word[-1...
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters. You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j. You can perform this operation at most once. How many different strings can you obtain? Constraints * 1 \leq |A| \leq 200...
3
from collections import Counter a=input() cnt=Counter(a) n=len(a) ans=n*(n-1)//2+1 for v in cnt.values(): ans-=v*(v-1)//2 print(ans)
The following problem is well-known: given integers n and m, calculate <image>, where 2n = 2·2·...·2 (n factors), and <image> denotes the remainder of division of x by y. You are asked to solve the "reverse" problem. Given integers n and m, calculate <image>. Input The first line contains a single integer n (1 ...
3
import math n = int(input()) m = int(input()) if math.log2(m) < n: print(m) else: print(m % (2 ** n))
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
3
from math import factorial as f a,b = [int(x) for x in input().split()] print(f(min(a,b)))
A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly 1 meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees lef...
3
from sys import stdin for _ in range(1): n=int(input()) if(n%2==0): print((int(n/2)+1)**2) else: print(2*(int(n/2)+2)*(int(n/2)+1))
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
n = int(input()) for t in range(n): sc = str(input()) if '1' not in sc: print(0) else: ini = sc.index('1') sc = sc[ini:len(sc)] cont = 0 for i in range(len(sc)): if '1' not in sc[i:len(sc)]: break if sc[i]=='0': ...
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
# -*- coding: utf-8 -*- """ Created on Tue Nov 26 20:56:39 2019 @author: Zheng Jiajia """ word=list(input()) trans=str(input()) right=word[::-1] check=''.join(right) if trans==check: print('YES') else: print('NO')
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
# cook your dish here def sumofdigits(n): n=str(n) sum1=0 for i in n: sum1+=int(i) return sum1 def satisfy(p2,s,n1): if(sumofdigits(int(p2)+n1)<=s): return 1 else: return 0 for i in range(int(input())): n,s=list(map(int,input().split())) n1=n sum1=sumofdigits...
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius. He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of...
1
from itertools import * from collections import * from operator import * from bisect import * from fractions import * Ii = lambda: map(int, raw_input().split()) Is = lambda: raw_input().split() ri = raw_input n = input() A = [Ii() for _ in xrange(n)] plusDiag = [] for i in xrange(n): plusDiag.append(su...
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
1
import sys n = int(sys.stdin.readline().strip()) sa = '' a = 0 sb = '' b = 0 for i in range(0, n): s = sys.stdin.readline().strip() if sa == '': sa = s elif sa != s and sb == '': sb = s if s == sa: a += 1 else: b += 1 if a > b: print(sa) else: print(sb)
There is a directed graph with N vertices and M edges. The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece. Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move t...
3
from operator import itemgetter N, M = map(int, input().split()) abc = [list(map(int, input().split())) for _ in range(M)] INF = -float("inf") dist = [INF]*N dist[0] = 0 d_tmp = 0 for abci in abc: if dist[abci[0]-1] != INF and dist[abci[1] - 1] < dist[abci[0] - 1] + abci[2]: dist[abci[1] - 1] = dist[abci[...