The post 102 Easier Classical SPOJ Solutions using Python appeared first on Dreamshire.

]]>102 SPOJ programming problem solutions using Python (average of 4 lines) to some of the easier SPOJ classical problems using Python which run in minimum time (0.00 sec.). Most of these solution are older and were converted from perl, C++ or crafted using Python directly.

The sole purpose of this collection is to aid a research project in comparative machine/human language where source code is considered a subconscious form of recorded thought.

Note: These solutions don’t have much point value, if any, when competing for rank.

SPOJ User-id: beta_projects

Time: 0.00

Output: Classic towers of Hanoi game.

for _ in xrange(input()): print 3**input() - 1

Time: 0.00

Output: For each ni×ni board print on a single line “0” if A wins considering both players play optimally well. Otherwise, print “1”.

for _ in xrange(int(raw_input())): print 1 - int(raw_input())%2

Time: 0.00

Output: Probability that the given quadratic equation has real roots. 1-sqrt(2)/3/sqrt(S)

for _ in xrange(input()): print '%.6f' % (1 - (2**0.5/3)/(input()**0.5))

Time: 0.00

Output: Determine who wins at a game which is way more complicated that this solution.

N = int(raw_input()) % 10 print "1\n%d" % N if N!=0 else 2

Time: 0.00

Output: Calculate the probability of the next ball Mr. M picks out is red.

import sys for cs, ns in enumerate(sys.stdin, 1): N, P, Q = map(float, ns.split()) print 'Case %d: %.4f' % (cs, (Q+1)/(P+2))

Time: 0.00

Output: Steinmetz Solid. 8*(2-sqrt(2)*R**3

for _ in xrange(input()): print '%.4f' % ((16 - 8*2**0.5) * input()**3)

Time: 0.00

Output: Minimize surface area of triangular prism when the volume is V.

for i in xrange(int(raw_input())): V = int(raw_input()) print '%.10f' % (6.75**0.5 * (16.0*V*V)**(1/3.))

Time: 0.00

Output: Find the maximum girth of a graph

for _ in xrange(int(raw_input())): d, r = divmod(int(raw_input())-2, 3) print (2*d + 2 + (r==2))%1000000007

Time: 0.00

Output: Find the square of the distance to the enemy aircraft.

for _ in xrange(int(raw_input())): a, b, c = map(int, raw_input().split()) print a*a - 2*b

Time: 0.00

Output: SPOJ Python solutions.

for _ in range(10): t = int(raw_input()); k = int(raw_input()) print (t+k)/2, '\n', (t-k)/2

Time: 0.00

Output: Catalan numbers.

from math import factorial as f while True: n = int(raw_input()) if n == -1: break print f(2*n) / f(n) / f(n+1))

Time: 0.00

Output: Catalan numbers. Again!

from math import factorial as f while True: n = int(raw_input()) if n==0: break print f(2*n) / f(n) / f(n+1) % 761238923

Time: 0.00

Output: Calculate the Stirling number of the second kind, S(n,m).

for _ in xrange(int(raw_input())): n, m = map(int, raw_input().split()) print int(not((n-m) & ((m-1)/2)))

Time: 0.00

Output: Print the person who moves first. BS Problem.

for _ in xrange(int(raw_input())): N, p = map(int, raw_input().split()) print "Airborne wins." if p==0 else "Pagfloyd wins."

Time: 0.00

Output: Maximum number of bishops that can be placed on nxn chessboard without threatening each other. Also a good example for handling EOF on input.

import sys for ns in sys.stdin: print max(1, 2*(int(ns)-1))

Time: 0.00

Output: Print the name of whom the final coin belongs to.

for _ in xrange(int(raw_input())): S = [raw_input() for _ in xrange(int(raw_input()))] print 'lxh' if S.count('lxh')%2 else 'hhb'

Time: 0.00

Output: Simple combination calculation.

for _ in xrange(int(raw_input())): c1, c2 = map(int, raw_input().split()) print 'Ramesh' if c1%2 and c2%2 else 'Suresh'

Time: 0.00

Output: Calculate 1/2 + 1/3 + … 1/(n+1)

while True: c, n = float(raw_input()), 2 if c == 0: break while c > 0: c-= 1.0/n n+= 1 print n-2, 'card(s)'

Time: 0.00

Output: Calculate log(n)/log(2)

from math import log while True: n = int(raw_input()) if n == 0: break print int(log(n,2))

Time: 0.00

Output: Find the number of possible IDs modulo 10^9+7.

m = 10**9 + 7 while(True): N, L = map(int, raw_input().split()) if N==0 and L==0: break print ((pow(N, L+1, m)-1)*pow(N-1, m-2, m) - 1) % m

Time: 0.00

Output: (Really?) Print the last character of a string. Another BS Problem.

for _ in xrange(input()): N, S = raw_input().split() print S[-1]

Time: 0.00

Output: Calculate the length of a missing geometrical segment.

for _ in xrange(int(raw_input())): b, c, d = map(int, raw_input().split()) print (c-b)+(c-d)

Time: 0.00

Output: find the kth number (indexed from 1) whose cube ends in 888.

for _ in range(int(raw_input())): k = int(raw_input()) print 250*(k-1) + 192

Time: 0.00

Paraphrase: Output ‘TAK’ if n is a power of 2 else output ‘NIE’

n = int(raw_input()) print "TAK" if n == -n&n else "NIE"

Time: 0.00

Output: Minimize the Gender Regularity in a linear arrangement of boys and girls

from math import ceil while(True): G, B = map(float, raw_input().split()) if G==-1 and B==-1: break print int(ceil(max(G,B)/(1+min(G,B))))

Time: 0.00

Output: Given the information of how many pentagons will be created, write a program to calculate the number of marbles needed.

while True: n = int(raw_input()) if n==0: break print (3*(n+1)**2 - n)/2

Time: 0.00

Output: Determine if doughnuts would cause Harry’s spine to crack.

for _ in xrange(int(raw_input())): c, k, w, = map(int,raw_input().split()) print 'yes' if k>=c*w else 'no'

Time: 0.00

Output: Find the second pentagonal number modulo 1,000,007.

for _ in xrange(int(raw_input())): n = int(raw_input()) print (n*(3*n+1)/2) % 1000007

Time: 0.00

Output: Always a right triangle, use Thales’ theorem to solve.

for cs in xrange(1, int(raw_input())+1): r = int(raw_input()) print "Case %d: %.2f" % (cs, 4*r*r + 0.25)

Time: 0.00

Output: Check for a common difference or common ratio. Calculate next in series.

while (True): a1, a2, a3 = map(int,raw_input().split()) if a1==0 and a2==0 and a3==0: break print '%s %d' % (('AP', a3+a2-a1) if a2-a1 == a3-a2 else ('GP', a3*a2/a1))

Time: 0.00

Output: Calculate the probability for replenishing supply in simple queue based on cost of x and supply of x and 2x.

while (True): N, M = map(float, raw_input().split()) if N==0 and M==0: break print '%.6f' % ((M-N+1)/(M+1) if M >= N else 0)

Time: 0.00

Output: Find the position of the person who survives.

from math import log while True: n = float(raw_input()) if n == 0: break print '%d' % (2*(n - 2**int(log(n,2))) + 1)

Time: 0.00

Output: Determine for a certain number of creatures p, the exact time Luis has to be in the room to see that amount.

from math import log for cs in xrange(1, int(raw_input())+1): p0, p1, t, p = map(float, raw_input().split()) print 'Scenario #%d: %.2f' % (cs, ((log(p)-log(p0))*t / (log(p1)-log(p0))))

Time: 0.00

Output: Determine for a certain number of creatures p, the exact time Luis has to be in the room to see that amount.

from math import log, ceil for _ in range(int(raw_input())): n = float(raw_input()) print int(ceil(log(n, 2))) + 1

Time: 0.00

Output: Find the maximum number of soldiers that can be placed in a separate line.

for _ in xrange(int(raw_input())): m, n = map(int,raw_input().split()) print max(m*(n/2+n%2), n*(m/2+m%2))

Time: 0.00

Output: For each segment of the trip, output the total distance traveled up to that point.

import sys A = [ map(float, ns[ns.find('(')+1:-3].split(',')) for ns in sys.stdin ] d = 0 for i in xrange(len(A)-1): d += ((A[i][0]-A[i+1][0])**2 + (A[i][1]-A[i+1][1])**2)**0.5 print "The salesman has traveled a total of %.3f kilometers." % d

Time: 0.00

Output: Find the total number of ways people can be accommodated.

for _ in xrange(int(raw_input())): n = int(raw_input())-1 print pow(2, n*n % 204, 98777)

Time: 0.00

Output: Find the corresponding term in Cantor’s enumeration.

from math import sqrt, ceil for _ in xrange(int(raw_input())): x = int(raw_input()) n = ceil((sqrt(8*x+1)-1)/2) t = x - n*(n-1)/2 print 'TERM %d IS %d/%d' % ((x, n-t+1, t) if n%2 else (x, t, n-t+1))

Time: 0.00

Output: Print the day of the week for the date given.

from datetime import datetime for _ in xrange(int(raw_input())): d, m, y = map(int, raw_input().split()) print datetime(y, m, d).strftime('%A')

Time: 0.00

Output: Calculate the number of nested boxes

for _ in range(int(raw_input())): N, K, T, F = map(int, raw_input().split()) print F + (F-N)/(K-1)

Time: 0.00

Output: Find the last digit of an exponentiation

Note: Same program solves: LASTDIG2 – The last digit re-visited

for _ in xrange(int(raw_input())): a, b = map(int, raw_input().split()) print pow(a, b, 10)

Time: 0.00

Output: Given a height and velocity, calculate the maximum distance that an arrow can reach when it hits the ground.

from math import sqrt while(True): V, H = map(int, raw_input().split()) if V==-1 and H==-1: break print "%.6f" % (V/9.8 * sqrt(H*19.6 + V*V))

Time: 0.00

Output: Marina is very bored, so she attempts a mindless task that, you guessed it, only causes more boredom. I just can’t make this stuff up.

for _ in xrange(int(raw_input())): a = int(raw_input()) print a if a%2 else int(bin(a)[:1:-1], 2)

Time: 0.00

Output: Calculate how many rectanges can be formed from a set of squares.

from math import sqrt N = int(raw_input()) print sum(N/i-i+1 for i in xrange(1, int(sqrt(N)+1)))

Time: 0.00

Output: Find the number of triangles in the “level N” hexagon. (Doesn’t allow Python) SPOJ solutions using Python

for _ in xrange(int(raw_input())): N = float(raw_input()) print int(N*(7*N*N + 4.5*N + 1)/2)

Time: 0.00

Output: Determine if the string is a palindrome. SPOJ solutions using Python

def is_palindromic(s): return s==s[::-1] for _ in xrange(int(raw_input())): print 'YES' if is_palindromic(raw_input()) else 'NO'

Time: 0.00

Output: Compare minimum in one list to the second minimum in another and determine offside condition.

while True: A, D = map(int, raw_input().split()) if A==0 and D==0: break b = min(map(int, raw_input().split())) C = sorted(map(int, raw_input().split())) print 'Y' if b < C[1] else 'N'

Time: 0.00

Output: Calculate the number of distinct point two countercyclical runners will meet. SPOJ solutions using Python

from fractions import gcd for _ in xrange(int(raw_input())): S1, S2 = map(int, raw_input().split()) print abs((S1-S2) / gcd(S1, S2))

Time: 0.00

Output: Compute the number of valid ordered combinations of submission results.

from math import factorial as f n, w, t, r = map(int, raw_input().split()) print f(n) / (f(w)*f(t)*f(r)) % 1000000007

Time: 0.00

Output: Determine who wins the game.

from operator import xor for _ in xrange(int(raw_input())): raw_input() C = map(int, raw_input().split()) a = reduce(xor, (i for i, c in enumerate(C, 1) if c%2), 0) print 'Hanks Wins' if a==0 else 'Tom Wins'

Time: 0.00

Output: Determine whether the permutation is ambiguous or not.

A=[0, 1] for i in xrange(2, 1001): A.append(A[-1] + 1.0/i) for _ in xrange(int(raw_input())): sides = int(raw_input()) print '%.2f' % sides*A[sides]

Time: 0.00

Output: OEIS 002898 - Number of n-step closed paths on hexagonal lattice; n<15.

for _ in xrange(int(raw_input())): n = int(raw_input()) - 1 print [0, 6, 12, 90, 360, 2040, 10080, 54810, 290640, 1588356, 8676360, \ 47977776, 266378112, 1488801600][n]

Time: 0.00

Output: Find the radius of the big circle to build the tambourine.

from math import pi, sin while(True): r, N = map(int, raw_input().split()) if r==0 and N==0: break print '%.2f' % (r / sin(pi/2/N))

Time: 0.00

Output: Find largest non-negative number less than or equal to floor (N/2) which is coprime to N.

for _ in xrange(int(raw_input())): n = int(raw_input()) k = n/2 print (k if n==2 or n%2 else (k-2 if k%2 else k-1))

Time: 0.00

Output: See A001835 a(n) = 4*a(n-1) – a(n-2), with a(0)=1, a(1)=1.

def T(n): if n==0 or n==1: return 1 return 4*T(n-1) - T(n-2) while True: n = int(raw_input()) if n==-1: break print '0' if n%2 else T(n/2+1)

Time: 0.00

Output: Calculate the area of a semi-circle. (0.1591549 is 1/(2*pi)).

while True: L = int(raw_input()) if L == 0: break print '%.2f' % (0.1591549*L*L)

Time: 0.00

Output: Kissing circles. Given three mutually tangent circles, what radius can a fourth tangent circle have?

from math import sqrt for _ in xrange(int(raw_input())): R1, R2, R3 = map(lambda x:1/float(x), raw_input().split()) Rs = R1 + R2 + R3 + 2*sqrt(R1*R2 + R2*R3 + R3*R1) print '%.6f' % (1/Rs)

Time: 0.00

Output: Find the sum of digits of the square of a repunit or Demlo numbers.

import sys for ns in sys.stdin: n = int(ns) print 81*(n/9) + (n%9)**2

Time: 0.00

Output: Can a sequence be modified to all zeros with several operations?

for _ in xrange(int(raw_input())): d = 0; raw_input() for a in map(int, raw_input().split()): d = a - d print "YES" if d==0 else "NO"

Time: 0.00

Output: How many sequences are there such that every rebel can dock his star ship?

for _ in xrange(int(raw_input())): n = int(raw_input()) print pow(n+1, n-1, 10007)

Time: 0.00

Output: Complicated and obtuse instructions – you’re gonna have to read this one yourself.

from math import sqrt for _ in xrange(int(raw_input())): X, Y = map(int, raw_input().split()) print '%.3f' % (2*sqrt(X*X - Y*Y))

Time: 0.00

Output: Find the number of ways in which the ball can be hit so that it eventually reaches one of the four holes.

from fractions import gcd while True: M, N = map(int, raw_input().split()) if M==0: break g = gcd(M, N) print 4*(M/g + N/g - 2)

Time: 0.00

Output: Find the minimum number of cubes.

while True: w, d = map(int, raw_input().split()) if w==0 and d==0: break wx = map(float, raw_input().split()) dx = map(float, raw_input().split()) print sum(i * max(wx.count(i), dx.count(i)) for i in xrange(1, 21))

Time: 0.00

Output: Calculate the sum of the whirligig of all numbers between two given numbers A and B (inclusive).

def fnr(n): if n<2: return n return 2*fnr(n/2) + n/2 + n%2 a, b = map(int, raw_input().split()) print fnr(b) - fnr(a-1)

Time: 0.00

Output: Find the original plain-text message. SPOJ solutions using Python

while True: c = int(raw_input()) if c==0: break codex = raw_input() print ''.join(codex[j*c + (c-i-1 if j%2 else i)] for i in xrange(c) for j in xrange(len(codex)/c))

Time: 0.00

Output: Print total number of strings which have a length N and are not special.

A = [0, 3, 9] for _ in xrange(3, 31): A.append(2*A[-1] + A[-2]) for _ in xrange(int(raw_input())): print A[int(raw_input())]

Time: 0.00

Output: An angry boss, an incompetent employee and some erroneous tiles with an easy solution.

while True: W, H = map(int, raw_input().split()) if W==0 or H==0: break print (W/H if W%H==0 else (H/W if H%W==0 else H*W))

Time: 0.00

Output: Print total number of strings which have a length N and are not special.

for _ in xrange(int(raw_input())): n, s = int(raw_input()), '' while n: n,r = divmod(n, 2) n -= 1-r s = '65'[r] + s print s

Time: 0.00

Output: Fib(N+2) just like AMZRCK - Amz Rock.

F = [0, 1] for i in xrange(2, 3300): F.append(F[-1] + F[-2]) print F[int(raw_input()) + 2]

Time: 0.00

Output: Calculate the area of the garden.

from math import sqrt for _ in xrange(int(raw_input())): a, b, c = map(float, raw_input().split()) area = (sqrt(3) * (a*a + b*b + c*c))/8 s = (a + b + c)/2 area += (1.5 * sqrt(s*(s-a)*(s-b)*(s-c))) print '%.2f' % area

Time: 0.00

Summary: For each data test, write in one line the number P Nguyen wants to find.

from itertools import groupby for i in xrange(int(raw_input())): Q = map(len, raw_input().split()) print max(len(list(L)) for n, L in groupby(Q))

Time: 0.00

Output: Output a line containing POSSIBLE if Brenda can make the trip.

while True: n = int(raw_input()) if n==0: break A = sorted([int(raw_input()) for _ in xrange(n)]) if sum(1 for i in xrange(n-1) if A[i+1]-A[i]>200) > 0 or \ 1422-A[-1] > 100: print 'IMPOSSIBLE' else: print 'POSSIBLE'

Time: 0.00

Output: Select a basketball team.

y = ''.join(raw_input()[0] for _ in xrange(int(raw_input()))) s = ''.join(chr(c) for c in xrange(97, 123) if y.count(chr(c)) >= 5) print s if s else 'PREDAJA'

Time: 0.00

Output: Print a single line containing a string composed solely of the characters '0', '+' and '-' and not beginning with '0', representing the digits of the number N in balanced base-3.

for _ in xrange(int(raw_input())): n, s = int(raw_input()), '' while n: s += '0+-'[n%3] if n%3 == 2: n+=1 n /= 3 print s[::-1]

Time: 0.00

Output: Find the minimum amount of fare that Jack has to give.

m, n = map(int, raw_input().split()) a = [[999]+map(int, raw_input().split())+[999] for _ in xrange(m)] for i in xrange(m-1): for j in xrange(1, n+1): a[i+1][j] += min(a[i][j], a[i][j-1], a[i][j+1]) print min(a[m-1])

Time: 0.00

Output: A single integer denoting Bob's number of friends of friends.

a=set(); b=set() for _ in xrange(int(raw_input())): A = raw_input().split() a.add(A[0]) b.update(A[2:]) print len(a ^ (a|b))

Time: 0.00

Output: Find the color of the Linearian, either red or blue..

def q(n, k): if n==0 and k==0: return 'red' p = k/2 ans = q(n-1, p) if k == 2*p: return 'blue' if ans == 'red' else 'red' return ans print q(int(raw_input()),int(raw_input()))

Time: 0.00

Output: Find the common permutation. SPOJ solutions using Python

import sys import collections for ns in sys.stdin: h1=collections.Counter(ns.strip()) h2=collections.Counter(sys.stdin.next().strip()) s = ''.join(c * min(h2[c], h1[c]) for c in 'abcdefghijklmnopqrstuvwxyz') print s

Time: 0.00

Output: Maximize the chances of survival from Russian Roulette.

import sys for ns in (sys.stdin): s, l, e = ns.strip(), 0, 0 for i in xrange(len(s)): if s[i]=='0' and s[i-1]=='0': l += 1 if s[i]=='0' and s[i-1]=='1': e += 1 print 'EQUAL' if l == len(s) or l == e else ('SHOOT' if l > e else 'ROTATE')

Time: 0.00

Output: Estimate the length of a way between two kingdoms.

from math import sqrt for cs in xrange(1, int(raw_input())+1): x1,y1, x2,y2, ac, l = map(float,raw_input().split()) ab = sqrt((x1-x2)**2 + (y1-y2)**2) cosa = (ab*ab + ac*ac - (l/sqrt(2))**2) / (2*ab*ac) if cosa <= 1: print "%d. %.3f" % (cs, 2*ac*sqrt(1-cosa*cosa)) else: print "%d. No problem" % cs

Time: 0.00

Output: Print the number of ways Joker can assign numbers to his knifes.

from operator import mul for _ in xrange(int(raw_input())): n = int(raw_input()) k = sorted(map(int, raw_input().split())) print 0 if k[n-1] < n else reduce(mul, (k[i]-i for i in xrange(n)))%1000000007 print "KILL BATMAN"

Time: 0.00

Output: Find the number of intersections of diagonals.

for _ in xrange(int(raw_input())): n = int(raw_input()) print n*(n-1)*(n-2)*(n-3)/24 % 1000000007

Time: 0.00

Output: Determine if a triangle is right (or wrong).

while True: a, b, c = map(lambda x:int(x)*int(x), raw_input().split()) if a==0 and b==0 and c==0: break print 'right' if a+b==c or a+c==b or b+c==a else 'wrong'

Time: 0.00

Output: Calculate the number of different ways a tree with N vertices may be labeled.

for cs in xrange(1, 1000): n = int(raw_input()) if n==0: break print 'Case %d, N = %d, # of different labelings = %d' % (cs, n, pow(n, n-2))

Time: 0.00

Output: Output a single line containing an uppercase “Y” if N is a beehive number, or an uppercase “N” otherwise.

from math import sqrt while True: n = int(raw_input()) if n==-1: break print 'N' if sqrt(12*n-3)%1 else 'Y'

Time: 0.00

Output: Bell or exponential numbers: number of ways to partition a set of n labeled elements.

A000110 = [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570] for _ in xrange(int(raw_input())): print A000110[int(raw_input())]

Time: 0.00

Output: Multiply two numbers.

for _ in xrange(int(raw_input())): a, b = map(int, raw_input().split()) print a * b

Time: 0.00

Output: Count total number of such primes p in the xrange [a ≥ 0, b > 0] so that (p2 + 1) or/and (p2 + 2) is/are prime(s).

for _ in xrange(int(raw_input())): a, b = map(int, raw_input().split()) print min(3,b)-a+1 if a < 4 else 0

Time: 0.00

Output: Find the maximum number of teams that can be formed. SPOJ solutions using Python

for _ in xrange(int(raw_input())): e, n = map(int, raw_input().split()) mx, mn = (e,n) if e>n else (n,e) print (e+n)/3 if mn > mx/2 else mn

Time: 0.00

Output: Find the number of possible different shapes of the pizza.

A006534 = [1, 1, 1, 4, 6, 19, 43, 120, 307, 866, 2336, 6588, 18373, 52119, 147700, 422016] for cs in xrange(1, int(raw_input())+1): n = int(raw_input()) - 1 print 'Case #%d: %d' % (cs, A006534[n])

Time: 0.00

Output: What is the dimensions of the room, L and W, respectively.

from math import sqrt r, b = map(int, raw_input().split()) q = r/2 + 2 d = int(sqrt(q*q - 4*(r+b))) print (q + d)/2, (q - d)/2

Time: 0.00

Output: Specify the number of even numbers and odd numbers respectively.

for _ in xrange(int(raw_input())): n = int(raw_input()) odds = pow(2, bin(n).count('1')) print n-odds+1, odds

Time: 0.00

Output: The cows may be on to something.

print bin(int(raw_input()) + 2863311530 ^ 2863311530)[2:]

Time: 0.00

Output: A single line for each test case, containing the answer modulo 314159.

for _ in xrange(int(raw_input())): n = int(raw_input())-1 print (4*pow(8, n, 314159) + 5*pow(10, n, 314159)) % 314159

Time: 0.00

Output: Print least possible time in which all jobs can be done.

n, k = map(int, raw_input().split()) print 2*n - 1 if k > n else k + n*n/k - (n%k==0)

Time: 0.00

Output: Calculate the number of good playlists.

p = 5**0.5 for _ in xrange(int(raw_input())): n = int(raw_input()) + 2 print int(((1+p)**n-(1-p)**n)/(2**n*p))

Time: 0.00

Output: Print the total number of items the customer will have after exchanging maximum no of cards for getting extra items.

for i in xrange(int(raw_input())): x, n = map(int, raw_input().split()) x+= x/(n-1) print x if x%n else x-1

Time: 0.00

Output: What is the expected number of tosses needed till you get N consecutive heads?

for _ in xrange(int(raw_input())): n, m = map(int, raw_input().split()) print '%d.00' % (pow(2, n+1) - pow(2, m+1))

Time: 0.00

Output: Number of cuts. SPOJ solutions using Python

from math import sqrt for _ in xrange(int(raw_input())): n = int(raw_input()) - 1 print int((sqrt(8*n + 1) + 1)/2 - 1)

Time: 0.00

Output: print <, =, or > for the appropriate relationship between two Heptadecimal Numbers.

while True: a, b = raw_input().split() if a=='*' and b=='*': break a, b = a.zfill(len(b)), b.zfill(len(a)) print '=' if a==b else ('>' if a > b else '<')

Time: 0.00

Output: Estimate the number of people that played in a day.

from math import ceil while True: p, b, f = map(int, raw_input().split()) if b == 0: break print 'No accounting tablet' if (p-f)%b else int(ceil(abs(p-f)/b/3.0))

Time: 0.00

Output: A005178(n) = a(n-1)+5*a(n-2)+a(n-3)-a(n-4).

A005178 = [0, 1, 1, 5, 11, 36, 95, 281, 781, 2245, 6336, 18061, 51205, 145601, 413351, 1174500, 3335651, 9475901, 26915305, 76455961, 217172736, 616891945, 1752296281] for cs in xrange(1, int(raw_input())+1): W = int(raw_input()) + 1 print cs, A005178[W]

The post 102 Easier Classical SPOJ Solutions using Python appeared first on Dreamshire.

]]>The post Medium Level SPOJ Problems appeared first on Dreamshire.

]]>Most of these were written in Perl or C++ and I have been converting them to Python. Many solutions have Perl-like references and influences in them.

SPOJ User-id: beta_projects

Time: 0.00

Summary: Find the product of all primitive roots of n.

from math import sqrt; from itertools import count, islice def isPrime(n): if n < 2: return False return all(n%i for i in islice(count(2), int(sqrt(n)-1))) for cs in range(int(raw_input())): n = int(raw_input()) if n == 3: print '%d:%d' % (cs+1, 2) elif isPrime(n): print '%d:%d' % (cs+1, 1) else: print '%d:%s' % (cs+1, 'NOTPRIME')

Time: 0.00

Summary: For each test case, print the grid as it appears at the end of the nth day.

def next_to(z): if (x+1<r and Cx[x+1][y]==z) or (x-1>=0 and Cx[x-1][y]==z) or (y-1>=0 and Cx[x][y-1]==z) or \ (y+1<c and Cx[x][y+1]==z): return True #with edge detection return False for _ in xrange(input()): r, c, n = map(int, raw_input().split()) C = [list(raw_input().strip()) for _ in xrange(r)] for _ in xrange(n): Cx = [_[:] for _ in C] #copy array by value for x in xrange(r): for y in xrange(c): if C[x][y]=='W' and next_to('G'): C[x][y]='G' elif C[x][y]=='A' and next_to('W'): C[x][y]='W' elif C[x][y]=='G' and next_to('A'): C[x][y]='A' for _ in C: print ''.join(_)

Time: 0.00

Summary: Find the product of all primitive roots of n.

from math import sqrt def area(a, b, c): s = (a + b + c) / 2.0 return sqrt(s*(s-a)*(s-b)*(s-c)) for _ in range(int(raw_input())): WX, WY, WZ, XY, XZ, YZ = map(int, raw_input().split()) u = WY*WY + WZ*WZ - YZ*YZ v = WZ*WZ + WX*WX - XZ*XZ w = WX*WX + WY*WY - XY*XY vol = sqrt(4*WX*WX*WY*WY*WZ*WZ - WX*WX*u*u - WY*WY*v*v - WZ*WZ*w*w+u*v*w) / 12.0 s = area(YZ,XZ,XY) + area(WX, WY, XY) + area(YZ, WY, WZ) + area(WX, XZ, WZ) print '%.4f' % ((3*vol) / s)

Time: 0.00

Summary: or each test case output one line describing the type of a hand, exactly like in the list above.

from collections import Counter rank = [ 0, 0, 0, 'four of a kind', 0, 'full house', 'two pairs', 'three of a kind', \ 'pair', 'flush', 'high card', 'straight flush', 'straight', 'royal flush'] straights = [[v-4, v-3, v-2, v-1, v] for v in range(6, 15)] + [[2, 3, 4, 5, 14]] vx ={'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14} for _ in range(input()): h = raw_input() v = sorted([vx[h[i]] for i in range(0,14,3)]) c = Counter(v) flush = int(h.count(h[1]) == 5) score = len(c)*2 - int(4 in c.values()) + int(3 in c.values()) - flush + int(v in straights)*2 + int(min(c)==10)*2 print rank[score]

Time: 0.00

Summary: Convert from one base to another.

import sys def base(dec, base): list, res = '0123456789ABCDEF', '' while dec != 0: res, dec = res+list[dec % base], dec//base return res[::-1] for b in sys.stdin.readlines(): s, bx, by = b.split() t = base(int(s, int(bx)), int(by)) print " ERROR" if len(t) > 7 else t.rjust(7, ' ')

Time: 0.00

Summary: Decode the attack date.

import time p = 4000000007 def decrypt(a, p): k = lambda n: ((p-1)/2 - 1) / 2 + 1 return p - pow(a, k(p), p) ts = decrypt(int(raw_input()), p) print time.ctime(ts)

Time: 0.01

Summary:translate the expressions to RPN form.

def rpn(s): vs, ss = [], [] for c in s: if 'a' <= c <= 'z': vs.append(c) elif c in '^*/+-': ss.append(c) elif c == ')': vs.append(vs.pop(-2) + vs.pop() + ss.pop()) return vs[0] for _ in range(input()): print rpn(raw_input())

Time: 0.12

Summary: Calculate the value of the given set of walks.

s = raw_input() ct, w = 1, 1 for c in s: left = 2*w if c=='R': w = left + ct elif c=='L': w = left elif c=='*': w += (left + left + ct) ct *= 3 print w

Time: 0.35

Summary: Find the contiguous subsequence with the maximum XOR value.

n = int(raw_input()) a = map(int, raw_input().split()) + [0] for x in xrange(1, n): a[x] ^= a[x - 1] m = 0 for x in xrange(-1, n + 1): for y in xrange(x + 1, n + 1): if a[x] ^ a[y] > m: m = a[x] ^ a[y] lo, hi = x + 2, y + 1 print m, '\n', lo, hi

Time: 0.96

Summary: For each test case output one line with the indices of the neighbours the children should select (here, index i corresponds to neighbour i who gives a total number of ai sweets).

while True: c, n = map(int, raw_input().split()) if c==0 and n==0: break A = map(int, raw_input().split()) mx = [-1] + [-2]*n s = 0 for i in range(n): s = (s+A[i])%c if mx[s] != -2: break mx[s] = i print ' '.join(str(j) for j in range(mx[s]+2, i+2))

Time: 0.24

Summary: Find the total distance armies must travel during relocation.

for cs in range(1, input()+1): ans, n = 0, input() A = [map(int, raw_input().split()) for _ in range(n)] for k in range(n): for i in range(n): for j in range(n): A[i][j] = min(A[i][j], A[i][k] + A[k][j]) for _ in range(input()): x, y = map(int, raw_input().split()) q += A[x-1][y-1] print 'Case #%d: %d' % (cs, q)

Time: 0.19

Summary: Find the total distance armies must travel during relocation.

c = int(raw_input()) for k in range(c): N, M = map(int, raw_input().split()) x = 0 for i in range(N): A = map(int, raw_input().split())[::-1] a0 = 0 for a in A: a0 = a - (a<=a0) x ^= a0 print "FIRST" if x else "SECOND" if k+1 < c: raw_input()

Time: 0.11

Summary: Calculate the ratio of the decreasing n-digit integers to the increasing n-digit integers.

def nCr(n, k): nt = 1 for t in range(min(k, n-k)): nt = nt * (n-t) // (t+1) return nt for _ in xrange(int(raw_input())): n = int(raw_input()) print '%.6f' % ((nCr(n + 9, n) - 1)/float(nCr(n + 8, n)))

Time: 0.37

Summary: Find the term in Recaman’s Sequence.

p, a = {0:1}, [0]*500001 for i in range(1, 500001): t = a[i-1]-i if t>0 and t not in p: p[t] = a[i] = t else: a[i] = a[i-1]+i p[a[i]] = 1 while True: k = int(raw_input()) if k == -1: break print a[k]

Time: 0.04

Paraphrased: Is it possible to construct figure satisfying the specification.

def ck(A): return sum(1 for x in A if x%2) for _ in range(input()): A = [0]*301 raw_input() while True: a, b = map(int, raw_input().split()) if a == -1 and b == -1: break A[a] += 1; A[b] += 1 print 'NO' if ck(A) else 'YES'

Time: 1.10

Output: For each test case, output a single integer indicating the minimum cost for this year.

for cs in range(1, int(raw_input())+1): n, a, b = map(int, raw_input().split()) t = map(int, raw_input().split()) c = 2*a + n*b fc = 2*a for i in range(1, n): inx = (t[i]-t[i-1]-1) * b c+= inx if inx < fc else fc print 'Case #%d: %d' % (cs, c)

Time: 0.04

Paraphrased: Find the number of possible decodings for the input string.

while True: s = raw_input() if s[0]=='0': break dp = [1] + [0]*(len(s)-1) + [1] for i in range(1, len(s)): if s[i]>'0': dp[i] = dp[i-1] if 9 < int(s[i-1]+s[i]) <= 26: dp[i]+= dp[i-2] print dp[-2]

Time: 0.01

Paraphrased: For each test case output string "YES" if given number is prime and "NO" otherwise.

import random def miller_rabin(n): d = n - 1 s = 0 while d % 2 == 0: d >>= 1 s += 1 for repeat in range(1): a = 0 while a == 0: a = random.randrange(n) if not miller_rabin_pass(a, s, d, n): return False return True def miller_rabin_pass(a, s, d, n): a_to_power = pow(a, d, n) if a_to_power == 1: return True for i in range(s-1): if a_to_power == n - 1: return True a_to_power = (a_to_power * a_to_power) % n return a_to_power == n - 1 def f(): for _ in range(input()): n=int(raw_input()) print "YES" if miller_rabin(n) else "NO" f()

Time: 0.40

Paraphrased: Find the next lexicographical permutation.

# Project Nayuki # Computes the next lexicographical permutation of the specified list in place, # returning whether a next permutation existed. (Returns False when the argument # is already the last possible permutation.) # def next_permutation(arr): # Find non-increasing suffix i = len(arr) - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 if i <= 0: return False # Find successor to pivot j = len(arr) - 1 while arr[j] <= arr[i - 1]: j -= 1 arr[i - 1], arr[j] = arr[j], arr[i - 1] # Reverse suffix arr[i : ] = arr[len(arr) - 1 : i - 1 : -1] return True for _ in xrange(int(raw_input())): n = int(raw_input()) A = raw_input().split() print ''.join(A) if next_permutation(A) else -1

Time: 0.10

Output: Output the sum requested.

n, k = map(int, raw_input().split()) i, a = 1, 0 while i <= n: j, r = divmod(k, i) if j == 0: break s = min(r/j, n-i) a+= (r+r - s*j) * (s+1) / 2 i+= s+1 print a + r*(n-i+1)

Time: 0.13

Output: For each test case output one line contains how many Gold Alloys are destroyed by Khairy.

for _ in range(int(raw_input())): n = int(raw_input()) A = map(int, raw_input().split()) for i in range(1, n): A[i-1] = min(A[i-1], A[i]) c =2*A[0] for i in range(1, n-1): c+=2*A[i]- min(A[i-1], A[i]) print c if n!=1 else 0

Time: 0.11

Output: For each test case output a single line with the minimum positive integer that satisfies all the

clues, or −1 if there is no such a number.

from fractions import gcd def f(s): lcm = lambda a, b: a*b/gcd(a,b) ans = reduce(lcm, (n for n, c in enumerate(s, 1) if c == 'Y'), 1) for n, c in enumerate(s, 1): if c == 'N' and ans%n == 0: return -1 return ans while True: s = raw_input() if s == "*": break print f(s)

The post Medium Level SPOJ Problems appeared first on Dreamshire.

]]>The post More solutions to SPOJ programming problems appeared first on Dreamshire.

]]>Note: SPOJ may prevent Python from being used for solving some problems or set time limits suitable only for compiled languages.

some of these were originally written in Perl and have been rewritten in Python. Many solutions have Perl-like references and influences in them.

SPOJ User-id: beta_projects

Time: 0.00

Output: Your program has to output the value of the number in the input file in the nowadays more common decimal system. One number per line.

B = [0, 1, 20, 360, 7200, 144000, 2880000, 57600000] c = lambda d: d.count('.') + 5*d.count('-') while True: n = int(raw_input()) if n==0: break A = reversed([raw_input() for _ in range(n)]) print sum(c(d) * B[i] for i, d in enumerate(A, 1))

Time: 0.00

Summary: Find the minimum amount of money he has to spend.

for _ in xrange(input()): n, k = map(int, raw_input().split()) P = [(int(x), i) for i,x in enumerate(map(int, raw_input().split()), 1) if x>=0] dp = [0]+[9999]*k for p, i in P: for j in xrange(i, k+1): if dp[j-1] != 9999: dp[j] = min(dp[j], dp[j-i] + p) print dp[k] if dp[k] != 9999 else -1

Time: 0.00

Summary: Determine the number of games, and the number of teams to add.

from math import log, ceil while True: g, t, a, d = map(int, raw_input().split()) if g < 0: break y = g*a + d x = 2**int(ceil(log(y, 2))) m = x + t*(t-1)/2*g - 1 print '%d*%d/%d+%d=%d+%d' % (g, a, t, d, m, x-y)

Time: 0.00

Output: You must output k lines with answers for each test case. The answer is YES, if the mouse can escape or NO otherwise.

n, m = map(int, raw_input().split()) for _ in range(int(raw_input())): x1, y1, x2, y2, x3, y3 = map(int, raw_input().split()) xd = min(x2+abs(y1-y2), x3+abs(y1-y3)) xm = max(x2-abs(y1-y2), x3-abs(y1-y3)) yd = min(y2+abs(x1-x2), y3+abs(x1-x3)) print 'YES' if x1 < xd or y1 < yd or x1 > xm else 'NO'

Time: 0.00

Output: Calculate the measure of the angle A in degrees and the velocity of the ball measured in inches per second.

from math import pi, sqrt, atan while True: a, b, s, m, n = map(float, raw_input().split()) if s==0: break vx = m*a/s vy = n*b/s print '%.2lf %.2lf' % (atan(vy/vx)*180.0/pi, sqrt(vx*vx + vy*vy))

Time: 0.00

Summary: Find the maximum amount of American dollars you can make.

m = {} def coins(n): if n==0: return n if not n in m: m[n] = max(n, coins(n/2) + coins(n/3) + coins(n/4)) return m[n] for _ in xrange(10): print coins(input())

Time: 0.00

Summary: Calculate the Nim sum in base B of X and Y.

for _ in xrange(input()): csi, b, x, y = map(int,raw_input().split()) i, s = 1, 0 while x+y > 0: s+= (x+y)%b * i x//= b; y//= b; i*= b print csi, s

Time: 0.00

Summary: Print the value of the investment at the end of a year.

from math import floor for cs in range(1, 100000): P, r, n = map(float, raw_input().split()) if n==0: break print 'Case %d. $%.2f at %.2f%% APR compounded %d times yields' % (cs, P, r, n), for i in range(int(n)): P+= floor((P*r/n))/100 print '$%.2f' % P

Time: 0.00

Summary: Is it possible to form a genie sequence?

for _ in xrange(int(raw_input())): A = [0]*1001 n = int(raw_input()) for i in map(int, raw_input().split()): if A[i+1]==0: A[i+1] = 1 else: A[n-i] = 1 print 'YES' if n==sum(A) else 'NO'

Time: 0.00

Summary: Print the nth manku word.

for _ in xrange(input()): s = '' n = int(raw_input()) while n > 0: n, r = divmod(n, 5) if r==0: n -= 1 s += 'umank'[r] print s[::-1]

Time: 0.00

Summary: Determine the fate of the farmer.

while True: d, f, b, m = map(int, raw_input().split()) if d<1 or f<1 or b<1 or m<1: break n = (f*f + f + 2) /2 t = d - n*b if t > m: print 'Farmer Cream will have', t, 'Bsf to spend.' else: print 'The firm is trying to bankrupt Farmer Cream by', m-t, 'Bsf.'

Time: 0.00

Summary: Convert Mayan dates from the Haab calendar to the Tzolkin calendar.

haab = {'pop':0, 'no':1, 'zip':2, 'zotz':3, 'tzec':4, 'xul':5, 'yoxkin':6,\ 'mol':7, 'chen':8, 'yax':9, 'zac':10, 'ceh':11, 'mac':12, 'kankin':13, \ 'muan':14, 'pax':15, 'koyab':16, 'cumhu':17, 'uayet':18} tzolkin = 'imix, ik, akbal, kan, chicchan, cimi, manik, lamat, muluk, ok, \ chuen, eb, ben, ix, mem, cib, caban, eznab, canac, ahau'.split(', ') c = int(raw_input()) print c for _ in xrange(c): n, d, y = raw_input().split() ndays = int(float(n)) + haab[d]*20 + int(y)*365 print ndays%13 + 1, tzolkin[ndays%20], ndays/260

Time: 0.00

Summary: For each test case print the case number and Gwen win probability in a/b format.

from fractions import gcd for cs in xrange(1, int(raw_input())+1): x1, y1, x2, y2 = map(int,raw_input().split()) n = x1*(x2+1) + y1*(y2+1) d = (x1+y1) * (x2+y2+1) if n==0 or d==0: print 'Case %d: 0' % cs else: g = gcd(d,n); print 'Case %d: %d/%d' % (cs, n/g, d/g)

Time: 0.00

Output: Find the least possible number of moves such that you can change the chip's position.

while True: S, T = raw_input().split() if S=='*' and T=='*': break c, f = 0, 0 for s,t in zip(S,T): if s!=t and f==0: c +=1 f = (s!=t) print c

Time: 0.00

Summary: Find the minimum number of operations needed to convert the given string into a balanced one.

import sys for cs, s in enumerate(sys.stdin.readlines(), 1): if s[0] == '-': break n, cnt = 0, 0 for c in s: if c == '{': n+= 1 elif c == '}' and n==0: n+= 1; cnt+= 1 elif c == '}' and n>0: n-= 1 print '%d. %d' % (cs, n/2+cnt)

Time: 0.00

Summary: Compute the average number of Knights to leave the circle during a competition.

A = [0, 0] for i in xrange(2, 10001): A.append(A[-1] + 1.0/i) while True: n = int(raw_input()) if n == 0: break print 'With %d competitors, a Jedi Knight will be replaced approximately %.2f times.' % (n, A[n])

Time: 0.00

Summary: Find the volume of a tetrahedron given only the six edge-lengths.

from math import sqrt for _ in xrange(input()): A, D, B, E, C, F = map(lambda x: int(x)**2, raw_input().split()) volume = sqrt((-A*B*C - A*D*E - B*D*F - C*E*F + A*C*D + B*C*D + \ A*B*E + B*C*E + B*D*E + C*D*E + A*B*F + A*C*F + \ A*D*F + C*D*F + A*E*F + B*E*F - C*C*D - C*D*D - \ B*B*E - B*E*E - A*A*F - A*F*F)/144.0) print "%.4f" % volume

Time: 0.00

Summary: Find the maximum possible sum which can be obtained after modifying the array.

for _ in xrange(input()): n, k = map(int, raw_input().split()) A = map(int, raw_input().split()) for i in xrange(min(n, k)): if A[i]>=0: break A[i] *= -1 k-=1 m = min(A) if k&1 else 0 print sum(A)-2*m

Time: 0.00

Summary: Print the wealth of yth node in a single line.

def fnr(x, w, n=0): if x <= 1: return w q = 4.0 if x%4==3 else 2.0 if n: return fnr((x - x%2)/2, w*q, 1) return fnr((x - x%2)/2, w/q) for _ in xrange(input()): x, y, w = map(int, raw_input().split()) print '%.6f' % (fnr(y, fnr(x, w, 1)))

Time: 0.00

Summary: Find the smallest m <= N such that m/phi(m) is maximum.

primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97,101] for _ in xrange(20): n = int(raw_input()) px = 1 for p in primes: if px*p > n: break px*=p print px

Time: 0.00

Output: Find the number of times a process had to be done to determine that N is happy, or -1 if N is not happy.

N = int(raw_input()) a = [] while True: N = sum(int(d)**2 for d in str(N)) if N in a or N==1: break a.append(N) print len(a)+1 if N==1 else -1

Time: 0.50

Summary: Find the total dots in the domino pieces.

for _ in xrange(int(raw_input())): n = int(raw_input()) print n*(n+1)*(n+2)/2

Time: 0.17

Summary: For each test case print a single line, the Nth term of the sequence Sk.

for _ in xrange(int(raw_input())): k, n = map(int, raw_input().split()) print int(bin(n)[2:], k)

Time: 0.01

Summary: find the last non-zero digit of N!.

import sys def L(n): p = lambda x: [1,2,4,8][x%4] if n<5: return [1,1,2,6,4][n] return p(n/5) * L(n/5) * L(n%5) % 10 for b in sys.stdin.readlines(): print L(int(b))

Time: 0.01

Summary: Determine if a sentence is a tautogram.

while True: w = raw_input().strip().lower().split() if w[0]=='*': break s = sum(1 for c in w if c[0]==w[0][0]) print 'Y' if len(w)==s else 'N'

Time: 0.07

Summary: Calculate the minimum energy required by David to pass the street.

for cs in xrange(1, int(raw_input())+1): raw_input() s, m = 0, 0 for x in raw_input().split(): s += int(x) if s < 0: s, m = 0, m-s print 'Scenario #%d: %d' % (cs, m+1)

Time: 0.05

Summary: Find the value of a sequence.

for _ in xrange(input()): n = float(raw_input()) print '%.11f' % (2.0/3 + (1.0/6 + 1/(n+2) - 1/(n+1))/2)

Time: 0.16

Summary: The 'ol "gray elephant from Denmark" trick.

for _ in xrange(input()): A = [raw_input().split() for _ in xrange(99)] s = ''.join(c for n,c in A if int(n)%9==0 and int(n)<82) print 'YES' if s==s[0]*len(s) else 'NO'

Time: 0.02

Summary: Find the smallest number of moves for each block of data.

while True: n = input() if n == -1: break A = [int(raw_input()) for _ in xrange(n)] s = sum(A) print -1 if s%n else sum(abs(s/n-a) for a in A)/2

Time: 0.05

Summary: Find the length of the chocolate bar and the minimum number of times to break the bar.

from math import log, ceil for _ in xrange(input()): n, c = int(raw_input()), 0 e = int(ceil(log(n, 2))) while n%2 == 0: n/=2; c+=1 print 2**e, e-c

Time: 0.15 PYPY

Summary: Output "YES" if manku can drink exactly z litres of water else "NO".

from fractions import gcd for _ in xrange(int(raw_input())): x, y, z = map(int, raw_input().split()) print 'NO' if (z>x and z>y) or z%gcd(x,y)!=0 else 'YES'

Time: 0.07

Summary: Find the number of "real" mangoes Ranjith gets.

for _ in xrange(int(raw_input())): N = int(raw_input()) print ((N/2 + 1)**2) % N

Time: 0.03

Summary: Calculate the total number and "Tringus" number of pieces needed for a pyramid of level K.

for cs in xrange(1, int(raw_input())+1): K = int(raw_input()) print 'Pyramid E. Nro# %d: %d' % (cs, K*(2*K*K + 6*K - 5)/3) print 'Tringus:', 2*(K*K - K)

Time: 0.02

Summary: Print the string representation of the location of this fraction in the Bird tree.

for _ in xrange(input()): a, b = map(int, raw_input().split('/')) s = '' while a*b > 1: s += 'L' if a < b else 'R' a, b = (b-a, a) if a < b else (b, a-b) print s

Time: 0.12

Summary: Find the minimum number of cuts.

from fractions import gcd N, M = map(int, raw_input().split()) print M - gcd(M, N)

Time: 0.01

Summary: Determine if (xd,yd) is reachable from (xs,ys).

from fractions import gcd for _ in xrange(input()): xs, ys, xd, yd = map(int, raw_input().split()) gd = abs(gcd(xd, yd)) gs = abs(gcd(xs, ys)) while 0 < gs < gd: gs *= 2 print 'YES' if gd==gs else 'NO'

Time: 0.06

Summary: Take a 2 column one-to-one relationship and match non correctly.

A = [0, 0, 1] for i in xrange(3, 100000): A.append(((i-1) * (A[-1]+A[-2])) % 1000000007) for _ in xrange(input()): n = int(raw_input()) print 0 if n >= 100000 else A[n]

Time: 0.04

Summary: Determine the number of terms in the series and the series numbers.

for _ in xrange(input()): a, b, c = map(int, raw_input().split()) n = (c*2)/(a+b) d = (b-a)/(n-5) m = a-2*d print n, '\n', " ".join(str(m+d*i) for i in range(n))

Time: 0.22 PYPY

Summary: Your task is to find the number of ways Player 1 can start the game so that after his first move, he is in the winning position.

from operator import xor for cs in xrange(1, input()+1): raw_input() A = map(int, raw_input().split()) s = reduce(xor, A, 0) print 'Case %d: %d' % (cs, sum(1 for a in A if s^a < a))

Time: 1.46

Summary: Find the number of subsequences.

for cs in xrange(1, int(raw_input())+1): br = [0]*10 ar = map(int, list(raw_input())) for a in ar: br[a]+= sum(br[:a]) + 1 print 'Case %d: %d' % (cs, sum(br) % 1000000007)

Time: 0.61

Summary: For each of the test cases output a single line with a single integer : the badness of the best rank list for the given teams.

for _ in xrange(int(raw_input())): raw_input() n = int(raw_input()) A = sorted([int(raw_input().split()[1]) for _ in xrange(n)]) print sum(abs(A[i]-i-1) for i in xrange(n))

Time: 0.03

Summary: Output a single line with four non-negative integers separated by single spaces,

representing the amount of each ingredient John needs to buy.

from math import ceil while True: A = map(float, raw_input().split()) if A[0] < 0: break mx = max(ceil(A[i] / A[i+4]) for i in xrange(4)) print ' '.join(str(int(mx*A[i+4] - A[i])) for i in xrange(4))

Time: 0.08

Summary: For each test case print the corresponding key.

from math import sqrt for _ in xrange(input()): a, b = map(int, raw_input().split()) x, y = 0xFFFFF, 0 for i in xrange(int(sqrt(a)), int(sqrt(b))): t = (i+1)*(i+1) - i*i x &= t y ^= t print x&y

Time: 0.12

Summary: Encode N into another possible smallest integer M (M > 0), such that product of digits of M equals to N.

for _ in xrange(input()): n, s = input(), '' if n == 0: print 10 elif n < 10: print n else: for i in xrange(9, 1, -1): while n%i == 0: s += str(i) n /= i print -1 if n > 1 else s[::-1]

Time: 0.11

Summary: Find the minimum altitude difference between two suitable platform points.

for _ in xrange(input()): A = sorted(map(int, raw_input().split())[1:]) B = sorted(map(int, raw_input().split())[1:]) d = abs(A[0]-B[0]) for a in A: for b in B: d = min(d, abs(a-b)) if a < b: break print d

Time: 0.11

Summary: Output the sum from 2^0 to 2^n MODULO 12980...

for _ in xrange(input()): n = int(raw_input()) print pow(2, n+1, 1298074214633706835075030044377087) - 1

Time: 0.07

Summary: Find the minimum number of cubes that can be cut from the given stones.

while True: t, vol, N = 0, 1001, int(raw_input()) if N==0: break for i in xrange(N): a, b, c = map(int, raw_input().split()) t += a*b*c vol = min(a, b, c, vol) print t/vol**3

Time: 0.59

Summary: Calculate the summation of the absolute difference of all the distinct pairs.

for _ in xrange(input()): N = input() A = map(int, raw_input().split()) s, x = 0, 0 for i in xrange(1, N): x += (i*(A[i] - A[i-1])) s += x print s

Time: 0.04

Summary: Find the number of distinct subsequences.

m = 10**9 + 7 for _ in xrange(int(raw_input())): r, t, s = 2, [0]*100, map(ord, raw_input()) t[s[0]] = 1 for i in s[1:]: tmp = t[i] t[i] = r r = (2*r - tmp) % m print r

Time: 0.17

Summary: The number of valid pairs (j, k).

for cs in xrange(1, int(raw_input())+1): cnt = 0 C = map(int, raw_input().split()) X = C[0]; A = [0]*2001 for c in C[2:]: if X >= c: cnt += A[X-c] A[c] += 1 print '%d. %d' % (cs, cnt)

Time: 2.02

Summary: Calculate number of sequences which sum is equal to N.

from math import sqrt while True: n = 2*int(raw_input()) if n==0: break q = int(sqrt(n)) + 1 r = sum((i+n/i)%2 for i in xrange(1, q) if n%i==0) print 2*r+q%2 if q*q == n else 2*r

Time: 0.17

Summary: Calculate the first 1 million self numbers.

v = [0]*1000001 for i in xrange(1, 1000000): if v[i]==0: print i s, n = 0, i while n > 0: s, n = s + n%10, n//10 v[min(s+i, 1000000)] = 1

Time: 0.44

Summary: For each compound output a single line with the sum of the valences.

while True: V = raw_input().split() n = int(V[0]) if n == 0: break print sum(map(int, V[n/2+1:]))

Time: 0.46 PYPY

Summary: Given a number you have to tell whether the number is divisible by 252 and 525.

def d(s, n, r=0): for c in s: r = (10*r + int(c)) % n return r==0 for _ in xrange(input()): s = raw_input() print ('Yes' if d(s,252) else 'No'), ('Yes' if d(s,525) else 'No')

Paraphrased: Calculate the biggest possible volume of a cylinder.

from math import pi while True: w, h = map(float, raw_input().split()) if w==0 and h==0: break res = h/2/(pi+1) if h < w*(pi+1) else w/2 res2 = pi * res*res * w res3 = w*w/4 * (h*pi - w) / pi**2 print '%.3f' % max(res2, res3)

Time: 0.40

Summary: Find the only number in a row.

t, m = [1], 10**9+7 for _ in xrange(1, 100000): t.append(2*t[-1] % m) for cs in xrange(1, input()+1): n = int(raw_input()) print 'Case %d: %d' % (cs, 1 if n==1 else (n+1)*t[n-2] % m)

Time: 0.02

Summary: Avoid the pit of death.

for _ in xrange(input()): n, m, i ,j = raw_input().split() m = int(m[-1]) * int(n) j = int(j[-1]) + int(i) print 'Possible.' if m%2 and j%2==0 else 'Impossible.'

Time: 0.70

Summary: Find the perfect shot.

from math import sqrt for _ in xrange(int(raw_input())): x, y, z = map(int, raw_input().split()) d = int(sqrt(x*x + y*y + 2*y*z)) a = 2*x*z + 2*z*d b = 2*y + 4*z print 'Not this time.' if a % b else a/b

Time: 0.06 PYPY

Summary: Calculate the number of ways muffins could be distributed.

from math import factorial as f def C(n, k): return f(n)//f(k)//f(n-k) n, r = map(int, raw_input().split()) print -1 if n < r else C(n-1, r-1) % 10000007

Time: 0.38

Summary: Print “Yes” if the regular polygon can be constructed with compass and straightedge.

A000215 = [3, 5, 17, 257, 65537] for _ in xrange(int(raw_input())): n = int(raw_input()) while n%2==0: n/=2 for a in A000215: if n%a==0: n/=a print 'Yes' if n==1 else 'No'

Time: 0.01

Summary: Find the maximum possible length of the upper envelop line.

n = int(raw_input()) A = [map(int, raw_input().split()) for _ in xrange(n)] L1, L2 = A[0][1], A[0][0] for i in xrange(1, n): L1, L2 = max(L1+abs(A[i-1][0]-A[i][0])+A[i][1], L2+abs(A[i-1][1]-A[i][0])+A[i][1]), \ max(L1+abs(A[i-1][0]-A[i][1])+A[i][0], L2+abs(A[i-1][1]-A[i][1])+A[i][0]) print max(L1, L2)

Time: 0.10

Summary: Output the probability that Mario will survive if he receives all the randomly placed mushrooms one by one.

for cs in xrange(1, input()+1): m, k = map(int, raw_input().split()) print 'Case #%d: %.8f' % (cs, 1.0/(k + m*k + 1))

Time: 0.06★

Summary: Can you empty a string of binary digits by recursively removing '100's.

for cs in xrange(1, input()+1): s, cnt = raw_input(), 0 for b in s[::-1]: cnt+= 1 if b=='0' else -2 if cnt < 0: break print 'Case %d: %s' % (cs, 'no' if cnt else 'yes')

Time: 0.03

Summary: For each test case, output a single line with two positive integers C and D representing

that CU1 is equivalent to DUN.

from fractions import gcd while True: n = int(raw_input()) if n == -1: break nx, dx = 1, 1 for i in xrange(n-1): a, b = map(int, raw_input().split()) nx, dx = nx*a, dx*b print nx/gcd(nx, dx), dx/gcd(nx, dx)

Time: 0.13

Summary: Specify the number of even numbers and odd numbers respectively.

m = 10**5+10 dp = [1]+[0]*m for i in [2,3,6,7,8]: for j in xrange(i, m): dp[j]+= dp[j-i] for _ in xrange(input()): print dp[int(raw_input())]

Time: 0.32

Summary: Print the numerator and denominator of the lowest form of the fraction.

m = {1:1} def f(n): if not n in m: m[n] = f(n/2)+f(n/2+1) if n&1 else f(n/2) return m[n] while True: n = int(raw_input()) if n==0: break print '%d/%d' % (f(n), f(n+1))

Time: 0.62

Summary: Find p/q, where p/q is an irreducible fraction denoting the probability of forming an arithmetic progression from the chits LJ picks.

from fractions import gcd for _ in xrange(input()): n = int(raw_input()) p = (3*n*n + 1)/2 if n%2 else 3*n*n/2 q = 6*n**3 g = gcd(p, q) print '%d/%d' % (p/g, q/g)

Time: 0.05

Summary: For each input n print the number of consecutive zeroes pairs that will appear in the sequence after n steps.

import sys A = [0, 1] for _ in xrange(1000): A.append(2*A[-2] + A[-1]) for ns in sys.stdin: print A[int(ns)-1]

Time: 0.64

Summary: Output the minimal number of trees that must be planted.

from fractions import gcd n = int(raw_input()) A = [int(raw_input()) for _ in xrange(n)] d = 0 for i in xrange(1, n): d = gcd(d, A[i]-A[i-1]) print (A[-1]-A[0])/d - n+1

Time: 0.27

Summary: Output all positions of the needle's occurences within the haystack.

while True: try: _, n, h = [raw_input() for _ in xrange(3)] p = h.find(n) while p > 0: print p p = h.find(n, p+1) print except: break

Time: 0.11

Summary: How many permutations of the first N numbers exist such that the maximum element between the indices [i..j] is either present at index i, or at index j?

for _ in xrange(input()): print pow(2, int(raw_input())-1, 1000000007)

Time: 1.04

Summary: Minimize the total anger for the children of the corn. See the movie to get the reference. Also, the mod 2^64 was a nice touch in adding to one's misery.

m, n = map(int, raw_input().split()) W = sorted([int(raw_input()) for _ in xrange(n)]) t = sum(W) - m ta = 0 for i in xrange(n): anger = min(W[i], t/(n-i)) ta += anger * anger t -= anger print ta % 2**64

Time: 0.25

Paraphrased: Go. Go. Godzilla. Find the more powerful 'monster' before the next movie!

for _ in xrange(input()): raw_input(); raw_input(); #blank & unneeded Gmax = max(map(int, raw_input().split())) Mmax = max(map(int, raw_input().split())) print 'Godzilla' if Gmax >= Mmax else 'MechaGodzilla'

Time: 0.34

Paraphrased: Determine whether the permutation is ambiguous or not.

while True: if input()==0: break p = map(int, raw_input().split()) for j, pj in enumerate(p, 1): if pj != j and p[pj-1] != j: print 'not', break print 'ambiguous'

Time: 0.28

Paraphrased: Collatz sequence.

import sys for ns in sys.stdin: n, c = int(ns), 1 while n != 1: n = 3*n +1 if n%2 else n>>1 c += 1 print c

Time: 0.02

Paraphrased: Find the unique words in a string.

for _ in xrange(input()): print len(set(raw_input().split()))

Time: 0.02

Paraphrased: Determine the probability that the color of last ball remaining in the bag is black.

for _ in xrange(int(raw_input())): B = int(raw_input().split()[1]) print '1.000000' if B%2 else '0.000000'

Time: 0.02★

Paraphrased: Find the value at an (x,y) coordinate in a stair-step pattern.

for _ in xrange(int(raw_input())): x, y = map(int, raw_input().split()) print x+y-x%2 if x==y or (x-y)==2 else 'No Number'

Time: 0.11

Paraphrased: Find whether a team can survive the trip to an opponent's empire.

for _ in xrange(int(raw_input())): n, m, D = map(int, raw_input().split()) c = sum((int(raw_input())-1)/D for _ in xrange(n)) print 'YES' if c >= m else 'NO'

Time: 0.09

Paraphrased: Count the number of triangles in a triangular grid (triangle tiling).

for _ in xrange(int(raw_input())): n = int(raw_input()) print n*(n+2)*(2*n+1) / 8

Time: 0.02

Paraphrased: Find the Maximal Quadrilateral Area for a Cyclic Quadrilateral using Brahmagupta's formula.

from math import sqrt for _ in xrange(int(raw_input())): a, b, c, d = map(float, raw_input().split()) s = (a+b+c+d)/2 print "%.2f" % sqrt(((s-a)*(s-b)*(s-c)*(s-d)))

Time: 0.08 PYPY

Paraphrased: Add the **net** transactions in wine trading.

while True: t, w = 0, 0 if raw_input() == '0': break for a in raw_input().split(): t+= int(a) w+= abs(t) print w

Time: 0.01

Paraphrased: Add 1 and divide by 2.

for _ in xrange(int(raw_input())): print (int(raw_input())+1) / 2

Time: 0.13

Paraphrased: Calculate the minimum number of moves required to invert the triangle.

for _ in xrange(int(raw_input())): h = int(raw_input()) print h*(h+1) / 6

Time: 1.48

Paraphrased: When it comes to war, cheaters always prosper. Simple sort and compare to see who wins more battles, and thus, the war.

S = input() Q = sorted(map(int, raw_input().split())) N = sorted(map(int, raw_input().split())) b = 0 for j in range(S): if Q[b] < N[j]: b+=1 print b

Time: 1.07

Paraphrased: Given a number N count the number R of different presentations of N in the form A*A+B*B with A and B being positive integers including zero.

from math import sqrt for _ in xrange(50): x = input() print sum(1 for i in xrange(1, int(sqrt(x/2))+1) if sqrt(x - i*i)%1 == 0)

Time: 0.21

Paraphrased: Calculate the maximum number of elements which can have the same value.

for _ in xrange(int(raw_input())): n = int(raw_input()) t = sum(map(int, raw_input().split())) print n-1 if t%n else n

Time: 0.06

Paraphrased: Find the number of triangles in the “level N” hexagon.

for _ in xrange(int(raw_input())): N = int(raw_input()) print N + N*N*(10*N + 9)

time: 0.01

Paraphrased: Recover addition problems damaged by ink blots. SPOJ Python solutions

for _ in xrange(input()): raw_input(); a, _, b, _, c = raw_input().split() if 'machula' in a: a = str(int(c) - int(b)) elif 'machula' in b: b = str(int(c) - int(a)) else: c = str(int(a) + int(b)) print a, '+', b, '=', c

time: 0.12

Paraphrased: Maximum number of people at the end of a party.

for _ in xrange(int(raw_input())): print max(0, int(raw_input())-2)

Time: 0.04

Paraphrased: Calculate reversed sum of two reversed numbers.

for _ in xrange(int(raw_input())): a, b = raw_input().split() print int(str((int(a[::-1]) + int(b[::-1])))[::-1])

Time: 0.86

Paraphrased: Check a sequence for legitimacy according to clone rules of replication.

for _ in xrange(int(raw_input())): raw_input(); b = map(int, raw_input().split()) d = reduce(lambda d,t: 2*(d - t), b[:-1], 1) print 'Yes' if d==b[-1] else 'No'

Time 0.43 PYPY

Paraphrased: Find the smallest "nice" number greater or equal to n.

def sd(n): return sum(int(i) for i in str(n)) for _ in xrange(int(raw_input())): n = int(raw_input()) while n % sd(n): n+=1 print n

Time: 0.01

Paraphrased: Simple combination calculation.

while True: N, D = map(int, raw_input().split()) if N==0 and D==0: break print pow(N, D)

Time: 0.10

Paraphrased: Find the minimum number of steps required for your program to solve the game.

import sys for g, st in enumerate(sys.stdin, 1): c = 0 for s in st.strip(): c+= (s=='1') ^ (c&1) print "Game #%d: %d" % (g, c)

Time: 0.03

Paraphrased: Use Stirling's formula to calculate the length of a factorial.

from math import log10, pi, e for _ in xrange(input()): n = input() print 1 if n<4 else int(log10(2*pi*n)/2 + n*log10(n/e)) + 1

Time: 0.01

Paraphrased: Calculate the GCD for two numbers.

from fractions import gcd for _ in xrange(input()): A, B = map(int, raw_input().split()) g = gcd(A, B) print B/g, A/g

Time: 0.06

Paraphrased: Find the minimum side length of the large box required to ship 4 square-shaped suitcases.

import sys for c, ns in enumerate(sys.stdin, 1): A = sorted(map(int, ns.split())) print 'Case %d: %d' % (c, A[2] + A[3])

Time: 0.03

Paraphrased: Determine if candies can be distributed equally.

for _ in xrange(int(raw_input())): raw_input(); n = int(raw_input()) k = sum(int(raw_input())%n for _ in xrange(n)) print "NO" if k%n else "YES"

Time: 0.21 PYPY

Paraphrased: Find the least amount of money Alice must spend on candy. (PYPY)

while True: N = input() if N==0: break C = sorted(map(int, raw_input().split())) P = sorted(map(int, raw_input().split())) print sum(C[i] * P[N-i-1] for i in xrange(N)) #cost

Time: 0.31 PYPY

Paraphrased: Simply, find the number of trailing zeros in a factorial.

for _ in xrange(input()): n = input() c = 0 while n >= 5: n /= 5 c += n print c

Time: 0.78

Paraphrased: Find the winner of the game.

while True: N, D = map(int, raw_input().split()) if N==0 and D==0: break print N, D, reduce(lambda a,j:(a+D)%j, xrange(2, N+1), 0) + 1

Time: 0.02

Paraphrased: Find the required direction you will be facing at the end.

for _ in xrange(input()): n, m = map(int, raw_input().split()) if n>m: print 'U' if m%2==0 else 'D' else: print 'L' if n%2==0 else 'R'

Time: 0.47

Paraphrased: Simple DP solution.

for cs in xrange(1, input()+1): raw_input() dp = [0, 0] for x in map(int, raw_input().split()): dp.append(max(x+dp[-2], dp[-1])) print 'Case %d: %d' % (cs, dp[-1])

Time: 0.34 PYPY

Paraphrased: Find the minimum time it takes to start dancing.

while True: n = input() if n == 0: break a = map(int, raw_input().split()) print sum(a[n-i-1] - a[i] - (n-2*i-1) for i in xrange(0, n/2))

Time: 2.51

Paraphrased: Determine if there exists at least one solution to ax + by = c.

from fractions import gcd for cs in xrange(1, input()+1): a, b, c = map(int, raw_input().split()) print "Case %d: %s" % (cs, ('No' if c % gcd(a,b) else 'Yes'))

Time: 0.30

Paraphrased: Calculate the number of triangles you can create from a wire of length n.

for _ in xrange(input()): n = input() k = n*n if n%2==0 else (n+3)*(n+3) print k/48+1 if k%48>24 else k/48

Time: 0.80

Paraphrased: Compute the largest sum on the paths starting from the top towards the base of a numerical triangle.

for _ in xrange(input()): nx = input() t = [map(int, raw_input().split()) for _ in xrange(nx)] for r in xrange(nx-1, 0, -1): for c in xrange(0, r): t[r-1][c] += max(t[r][c], t[r][c+1]) print t[0][0]

Time: 0.02

Paraphrased: Print the largest possible number in the sequence.

for _ in xrange(int(raw_input())): x, avg = map(int, raw_input().split()) print (avg*avg - x*x - 3*x + 3*avg)/2

Time: 0.39

Paraphrased: Minimize the height difference between the tallest and shortest in a group.

for _ in xrange(int(raw_input())): N, K = map(int, raw_input().split()) h = sorted(map(int, raw_input().split())) print min(h[K-1+i] - h[i] for i in xrange(N-K+1))

Time: 0.08

Paraphrased: Josephus Problem.

for _ in xrange(int(raw_input())): n = int(raw_input()) print reduce(lambda q,k: (q+n-k)%k+1, xrange(2, n+1), 1)

Time: 0.04

Paraphrased: Calculate the expected number of times the 'if' block of the provided pseudo-code executes.

a = [0, 1] for i in xrange(2, 100001): a.append(a[-1] + 1.0/i) for _ in xrange(int(raw_input())): print a[int(raw_input())]

Time: 0.09

Paraphrased: Print the minimum number of pieces that should be bought.

from math import sqrt A = [0] + [999999]*1000 for i in xrange(1, 1001): for j in xrange(1, int(sqrt(i))+1): A[i] = min(A[i], A[i-j*j]+1) for _ in xrange(int(raw_input())): print A[int(raw_input())]

Time: 1.03

Paraphrased: Find the minimum number of pieces that should be bought.

from math import sqrt for cs in xrange(1, int(raw_input())+1): n = int(raw_input()) print 'Case %d: %d' % (cs, sqrt(n+1)-1)

ime: 0.20

Paraphrased: Determine the time at which the reaction will have to be stopped.

from math import log for _ in xrange(int(raw_input())): N, K, M = map(int, raw_input().split()) print 0 if M<=N else int(log(M/N, K))

Time: 1.32

Paraphrased: Print N! modulo P.

for _ in xrange(int(raw_input())): n, p = map(int, raw_input().split()) if n < p: q = reduce(lambda a,j:(a*j)%p, xrange(p-1, n, -1), 1) print p - pow(q, p-2, p) if n < p else 0

Time: 0.08

Paraphrased: Minimum numbers of steps to break a chocolate bar.

from math import log, ceil for cs in xrange(1, input()+1): N, M, K = map(int, raw_input().split()) t = ceil(log(N, 2)) + ceil(log(M, 2)) + ceil(log(K, 2)) print "Case #%d: %d %d" % (cs, N*M*K-1, t)

Time: 0.19

Paraphrased: Print number of groups currently in shahbag.

raw_input() cnt, Px = 0, [False]*20002 for p in map(int, raw_input().split()): Px[p] = True if Px[p-1] == Px[p+1] == True: cnt-= 1 if Px[p-1] == Px[p+1] == False: cnt+= 1 print cnt print 'Justice'

Time: 0.12

Paraphrased: Find number of the bead which is the first at the worst possible disjoining.

for _ in xrange(int(raw_input())): maxm = s = raw_input() maxf = 0 for f in xrange(len(s)): m = s[f:] + s[:f] maxm, maxf = (m, f) if maxm > m else (maxm, maxf) print maxf + 1

Time: 0.08

Paraphrased: Print a single integer denoting the sum of the hotness bonds for all pairs that MMDS has proposed.

for _ in xrange(input()): raw_input() A = sorted(map(int, raw_input().split())) B = sorted(map(int, raw_input().split())) print sum(a*b for a,b in zip(A,B))

Time: 0.16

Paraphrased: Find the run length encoding of the input string.

import sys, re buff = sys.stdin.readlines() for s in buff: sx = '' for g, c in re.findall(r'((\w)\2{0,})', s): j = len(g) sx+= c*j if j <= 3 else str(j)+'!'+c print sx

Time: 0.80

Paraphrased: Find the number of moves.

n = int(raw_input()) for a in reversed([raw_input() for _ in range(n)]): if a == str(n): n-= 1 print n

Time: 0.01

Paraphrased: Find the the minimal number of pizzas.

import sys, math buff = map(lambda s:s.strip(), sys.stdin.readlines()) a = buff.count('3/4') b = buff.count('1/2') c = buff.count('1/4') q = a + b/2.0 + 1 print int(math.ceil((q + (c-a - 2*b%2)/4.0) if a < c else q))

Time: 0.02

Paraphrased: Calculate the bowling score.

for _ in xrange(int(raw_input())): d = map(int,raw_input().split()) s = 0 for _ in xrange(10): s+= sum(d[:2 + (d[0]+d[1] > 9)]) d = d[2 - (d[0] > 9):] print s

Time: 1.14

Paraphrased: Calculate the number of numbers divisible by P on Nth row of the pascal triangle.

for _ in xrange(int(raw_input())): n, p = map(int, raw_input().split()) nx = n+1 ans = 1 while n>0: n, r = divmod(n, p) ans*= r+1 print nx-ans

Time: 0.00

Summary: Print the series numbers separated by single space.

from math import sqrt for _ in xrange(int(raw_input())): x, y, s = map(int,raw_input().split()) d = 5*y + 7*x + 2*s n = int((d + sqrt(d*d - 48*s*(x + y))) / (2*(x + y))) dx = (y-x)/(n-6) a = x - 2*dx print n, "\n", ' '.join(str(a + dx*i) for i in xrange(n))

Time: 0.12

Summary: Determine who wins the game.

for _ in range(int(raw_input())): n = int(raw_input()) print 'Sorry Shaktiman' if n%2 else 'Thankyou Shaktiman'

Time: 0.01

Output: For each test case print a single line with the character Y if it is possible for Alice to reach the given pair or N if it is impossible.

for _ in range(int(raw_input())): a, b = map(int, raw_input().split()) while b: a, b = b, a%b while a%2==0: a>>= 1 print 'Y' if a==1 else 'N'

Time: 0.39

Output: Help the man find his seat by telling him the row number (1,2,...), seat position(window or aisle or middle), and the direction(left or right).

for _ in range(int(raw_input())): n = int(raw_input()) if n==1: print 'poor conductor' else: r = (n+3)/5 print r, 'AWWAAMWWMA'[n%10], 'L' if n%10<4 else 'R'

Time: 0.09

Output: For each test case, find the minimum number of matches the player should have played to achieve that average.

for _ in xrange(int(raw_input())): s = raw_input() + '.' n = int(s.replace('.', '')) f = 10 ** len(s[s.index('.')+2:]) print f/gcd(n,f)

Time: 0.02

Output: Output T lines each containing a single integer ‘c’ which denotes the number of K-numbers which lie in the interval [A,B] inclusive of the end points.

A023194 = [2, 4, 9, 16, 25, 64, 289, 729, 1681, 2401, 3481, 4096, 5041, 7921, 10201, 15625, \ 17161, 27889, 28561, 29929, 65536, 83521, 85849, 146689, 262144, 279841, 458329, \ 491401, 531441, 552049, 579121, 597529, 683929, 703921, 707281, 734449, 829921, 1190281] for _ in range(int(raw_input())): L, H = map(lambda x:max(A023194, key=lambda y:y>=int(x)), raw_input().split()) print A023194.index(H) - A023194.index(L)

Time: 0.09

Output: Output the string “Scenario #i: “ where i is the test case you are analyzing followed by a single number D, denoting the Degrees necessary to do the launch, if the launching can't be done, output D as -1. the number must have a precision of 2 decimal digits.

from math import pi, asin for cs in range(1, int(raw_input())+1): ta, sp = map(float, raw_input().split()) si = ta*9.806 / sp / sp print 'Scenario #%d: %.2f' % (cs, asin(si)*90/pi if si <= 1 else -1)

Time: 0.02

Output: For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of load tests you need to run in the worst case before knowing within a factor of C how many people the site can support.

from math import sqrt for cs in xrange(1, int(raw_input())+1): L, P, C = map(int, raw_input().split()) y = 0 while L*C < P: L = sqrt(L*P) y += 1 print 'Case #%i: %s' % (cs, y)

Time: 0.00

Output: Help Super Mario and tell him how many points he will score.

def f(s=0): for _ in range(10): d = int(raw_input()) s += d if s >= 100: return s if s <= 100+d/2 else s-d return s print f()

Time: 0.46 PYPY

Output: The first and only line of output must contain the required minimum number of ships.

n, c = int(raw_input()), 0 bx = [int(raw_input())-1 for _ in range(n)][1:] for b in bx: for q in bx[c+1:]: if q%b==0: bx.remove(q) c+=1 print c

Time: 0.01

Output: For each test case, output the last four digits of the number of ways of carpeting the 2xN way. If the answer involves fewer than 4 digits, print the entire number.

f = [1,1]; g = [1,0] for i in range(2, 33001): f.append((f[-1] + f[-2] + 2*g[-1]) % 10000) g.append((f[-3] + g[-1])) for _ in range(int(raw_input())): print f[int(raw_input())]

Time: 0.03

Output: T real numbers rounded to 6 digits one in each line.

from math import sin def f(a, b, c, p, r): while (r - p > 1e-6): q = (p + r) / 2.0 r, p = (q, p) if a*q + b*sin(q) > c else (r, q) return r for _ in xrange(int(raw_input())): a, b, c = map(int, raw_input().split()) print '%.6f' % f(a, b, c, 0, c)

Time: 0.19

Output: For each test case, you have to output n lines, each line containing a single integer. The first line contains the number of different people that were not copied. The second line contains the number of people that were copied only once (i.e., there are two identical copies for each such person.)

from collections import Counter while True: n, m = map(int, raw_input().split()) if n==0 and m==0: break q =[0]*n for z in Counter(raw_input() for _ in range(n)).values(): q[z-1]+= 1 for qx in q: print qx

Time: 2.31

Output: For each test case your program should write all the pairs of the neighbouring towns (i.e. their numbers). There should be one pair in each line. Each pair can appear only once. The numbers in each pair should be given in increasing order. Pairs should be ordered so that if the pair (a, b) precedes the pair (c, d) then a < c or (a = c and b < d).

for _ in range(int(raw_input())): n = int(raw_input()) d = [map(int, raw_input().split()) for _ in range(n)] for i in range(n-1): for j in range(i+1, n): for k in range(n): if j!=k and i!=k and d[j][k]+d[k][i]==d[j][i]: break if k==n-1: print i+1, j+1 raw_input()

Time: 7.16

Output: The number of such sequences whose sum if zero.

from collections import defaultdict for _ in range(int(raw_input())): raw_input() d = defaultdict(lambda: 0, {0:1}) s, ans = 0, 0 for q in map(int, raw_input().split()): s+= q ans+= d[s] d[s]+= 1 print ans

Time: 0.10

Output: Find (1/2)**n with full precision to n<=1000.

for _ in xrange(input()): n = int(raw_input()) x = 5**(n-1) print '1' if n==1 else '0.'+str(x).zfill(n-1) # x/10**n

The post More solutions to SPOJ programming problems appeared first on Dreamshire.

]]>The post SPOJ Problem 11. Factorial (FCTRL) Trailing zeros in factorials appeared first on Dreamshire.

]]>SPOJ 11 Factorial (FCTRL) Trailing zeros in factorials

The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically.

ACM technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called “Travelling Salesman Problem” and it is very hard to solve. If we have N BTSes to be visited, we can visit them in any order, giving us N! possibilities to examine. The function expressing that number is called factorial and can be computed as a product 1×2×3×4×…×N. The number is very high even for a relatively small N.

The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. So they started to study behaviour of the factorial function.

For example, they defined the function Z. For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!. They noticed that this function never decreases. If we have two numbers N1 < N2, then Z(N1) ≤ Z(N2). It is because we can never “lose” any trailing zero by multiplying by any positive number. We can only get new and new zeros. The function Z is very interesting, so we need a computer program that can determine its value efficiently.

**Input Specification**

There is a single positive integer T on the first line of input (equal to about 100000). It stands for the number of numbers to follow. Then there are T lines, each containing exactly one positive integer number N, 1 ≤ N ≤ 1000000000.

**Output Specification**

For every number N, output a single line containing the single non-negative integer Z(N).

**Sample Input:**

6

3

60

100

1024

23456

8735373

**Sample Output:**

0

14

24

253

5861

2183837

**Ancillary Files**

Input file: fctrl.in

Output file: fctrl.out

**SPOJ 11 Factorial (FCTRL) Solution** in Python 2.7 (File: 11.py)

**Usage Directions**

Run from cmd prompt as: python 11.py < fctrl.in > my_fctrl.out

and compare my_ fctrl.out to fctrl.out. Submit the program to the SPOJ server at the link provided under the description.

The test cases are pre-qualified to match the input specification.

*Trailing zeros in factorials* update 6/30/2014

The post SPOJ Problem 11. Factorial (FCTRL) Trailing zeros in factorials appeared first on Dreamshire.

]]>The post SPOJ Problem 1680. Black and white painting (BLACK) appeared first on Dreamshire.

]]>1680. Black and white painting

You are visiting the Centre Pompidou which contains a lot of modern paintings. In particular you notice one painting which consists solely of black and white squares, arranged in rows and columns like in a chess board (no two adjacent squares have the same colour).

Since you are bored, you wonder how many 8 × 8 chess boards are embedded within this painting. The bottom right corner of a chess board must always be white.

**Input Specification**

The input contains several test cases. Each test case consists of one line with three integers n, m and c. (8 ≤ n, m ≤ 40000), where n is the number of rows of the painting, and m is the number of columns of the painting. c is always 0 or 1, where 0 indicates that the bottom right corner of the painting is black, and 1 indicates that this corner is white.

The last test case is followed by a line containing three zeros.

**Output Specification**

For each test case, print the number of chess boards embedded within the given painting.

**Sample Input**

8 8 0

8 8 1

9 9 1

40000 39999 0

0 0 0

**Sample Output**

0

1

2

799700028

**Ancillary Files**

Input file: black.in

Output file: black.out

**Solution** (File: 1680.py)

Use this link to get the Project Euler Solution Python 2.7 source.

- Run from cmd prompt as: python 1680.py < black.in > my_black.out
- and compare my_black.out to black.out. Submit the program to the SPOJ server at the link provided under the description.
- The test cases are qualified to match the input specification.

The post SPOJ Problem 1680. Black and white painting (BLACK) appeared first on Dreamshire.

]]>The post SPOJ Problem 1681. Cylinder Volume (CYLINDER) Solution appeared first on Dreamshire.

]]>**CYlinder Volume Description**

1681. Cylinder volume

Cylinder Volume: Using a sheet of paper and scissors, you can cut out two faces to form a cylinder in the following way:

- Cut the paper horizontally (parallel to the shorter side) to get two rectangular parts.
- From the first part, cut out a circle of maximum radius. The circle will form the bottom of the cylinder.
- Roll the second part up in such a way that it has a perimeter of equal length with the circle’s circumference, and attach one end of the roll to the circle. Note that the roll may have some overlapping parts in order to get the required length of the perimeter.

Given the dimensions of the sheet of paper, can you calculate the biggest possible volume of a cylinder which can be constructed using the procedure described above?

**Input Specification**

The input consists of several test cases. Each test case consists of two numbers w and h (1 ≤ w ≤ h ≤ 100), which indicate the width and height of the sheet of paper.

The last test case is followed by a line containing two zeros.

**Output Specification**

For each test case, print one line with the biggest possible volume of the cylinder. Round this number to 3 places after the decimal point.

**Sample Input**

10 10

10 50

10 30

0 0

**Sample Output**

54.247

785.398

412.095

In the first case, the optimal cylinder has a radius of about 1.591549, in the second case, the optimal cylinder has a radius of 5, and in the third case, the optimal cylinder has a radius of about 3.621795.

**Ancillary Files**

Input file: cylinder.in

Output file: cylinder.out

**Solution** (File: 1681.py)

**Comments**

Run from cmd prompt as: python 1681.py < cylinder.in > my_cylinder.out

and compare my_ cylinder.out to cylinder.out. Submit the program to the SPOJ server at the link provided under the description.

The test cases are qualified to match the input specification.

The post SPOJ Problem 1681. Cylinder Volume (CYLINDER) Solution appeared first on Dreamshire.

]]>The post SPOJ Problem 1682. Deli Deli (DELI) Solution appeared first on Dreamshire.

]]>1682. Deli Deli

Mrs. Deli is running the delicatessen store “Deli Deli”. Last year Mrs. Deli has decided to expand her business and build up an online store. She has hired a programmer who has implemented the online store.

Recently some of her new online customers complained about the electronic bills. The programmer had forgotten to use the plural form in case that an item is purchased multiple times. Unfortunately the programmer of Mrs. Deli is on holiday and now it is your task to implement this feature for Mrs. Deli. Here is a description how to make the plural form:

- If the word is in the list of irregular words replace it with the given plural.
- Else if the word ends in a consonant followed by “y”, replace “y” with “ies”.
- Else if the word ends in “o”, “s”, “ch”, “sh” or “x”, append “es” to the word.
- Else append “s” to the word.

**Input Specification**

The first line of the input consists of two integers **L** and **N** (*0 ≤ L ≤ 20*, *1 ≤ N ≤ 100*). The following **L** lines contain the description of the irregular words and their plural form. Each line consists of two words separated by a space character, where the first word is the singular, the second word the plural form of some irregular word. After the list of irregular words, the following **N** lines contain one word each, which you have to make plural. You may assume that each word consists of at most 20 lowercase letters from the English alphabet (‘a’ to ‘z’).

**Output Specification**

Print **N** lines of output, where the **i ^{th}** line is the plural form of the

**Ancillary Files**

Input file: deli.in

Output file: deli.out

**Solution** (File: 1682.py)

Use this link to get the Project Euler 1682 Solution Python 2.7 source.

- Run from cmd prompt as: python 1682.py < deli.in > my_deli.out
- and compare my_ deli.out to deli.out. Submit the program to the SPOJ server at the link provided under the description.
- The test cases are qualified to match the input specification.

The post SPOJ Problem 1682. Deli Deli (DELI) Solution appeared first on Dreamshire.

]]>The post SPOJ Problem 42. Adding Reversed Numbers (ADDREV) appeared first on Dreamshire.

]]>**Description**

42. Adding Reversed Numbers

The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

**Input Specification**

The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

**Output Specification**

For each case, print exactly one line containing only one integer – the reversed sum of two reversed numbers. Omit any leading zeros in the output.

**Sample Input**

3

24 1

4358 754

305 794

**Sample Output**

34

1998

1

**Solution** (File: 42.py)

**Comments**

The test cases are qualified to match the input specification.

The post SPOJ Problem 42. Adding Reversed Numbers (ADDREV) appeared first on Dreamshire.

]]>The post SPOJ Problem 4408. Build a Fence (FENCE1) Solution appeared first on Dreamshire.

]]>4408. Build a Fence

There is a wall in your backyard. It is so long that you can’t see its endpoints. You want to build a fence of length L such that the area enclosed between the wall and the fence is maximized. The fence can be of arbitrary shape, but only its two endpoints may touch the wall.

**Input Specification**

The input consists of several test cases.

For every test case, there is only one integer L (1<=L<=100), indicating the length of the fence. The input ends with L=0.

**Output Specification**

For each test case, output one line containing the largest area. Your answer should be rounded to 2 digits after the decimal point.

**Sample Input**

1

7

0

**Sample Output**

0.16

7.80

**Solution** (File: 4408.py)

Use this link to get the Project Euler Solution Python 2.7 source.

**Comments**

The test cases are qualified to match the input specification.

The post SPOJ Problem 4408. Build a Fence (FENCE1) Solution appeared first on Dreamshire.

]]>