id string | question string | starter_code string | solution string |
|---|---|---|---|
APPS_401 | January and February are usually very cold in ChefLand. The temperature may reach -20 and even -30 degrees Celsius. Because of that, many people seal up windows in their houses.
Sergey also lives in ChefLand. He wants to seal the window in his house. The window has the shape of a simple convex polygon with N vertices... | from math import sqrt
import sys
sys.setrecursionlimit(10**8)
intMax = 10**18
def knapsack(rl,l,c,m):
if m==0 and rl>0:
return intMax
if rl<=0:
return 0
return min(c[m-1]+knapsack(rl-l[m-1],l,c,m),knapsack(rl,l,c,m-1))
for _ in range(int(input())):
n= int(input())
cost=[]
length=[]
sides=[]
for i in range(n... | |
APPS_402 | Supermarket Dilemma
Chef is going to local supermarket but there appears a problem with chef as he is confused about which Supermarket he can choose to go as he is not able to decide whether he can park his car in that particular supermarket’s parking lot or not! There are N parking slots in each supermarket which are ... | import math
def check(s):
if s==2:
return 1
for i in range(2,math.ceil(math.sqrt(s))+1):
if s%i == 0:
return 0
return 1
def Solve(slots):
if slots<3:
return 0
#check
s = math.sqrt(slots)
if math.floor(s) == math.ceil(s):
... | |
APPS_403 | Mr. Krabs loves money. He enters a bank and sees that there are n rooms arranged in a row. The only rooms with doors are the two rooms on either corner. Initially, all the rooms are locked (including the corner ones). To enter a room, it must be unlocked with a key.
Mr. Krabs is able to steal k keys from the sleeping n... | rooms=int(input())
money=list(map(int,input().split()))
keys=int(input())
rev=-1
a,b=0,-1
tot=[]
#print(money[-3:-1])
x=0
for i in range(keys):
#print(money[b:-1],money[0:a])
x=sum(money[b:])+sum(money[0:keys-abs(b)])
tot.append(x)
b-=1
print(max(tot))
| |
APPS_404 | The game of billiards involves two players knocking 3 balls around
on a green baize table. Well, there is more to it, but for our
purposes this is sufficient.
The game consists of several rounds and in each round both players
obtain a score, based on how well they played. Once all the rounds
have been played, the total... | s1=s2=lead=0
mlead1=mlead2=0
for _ in range(int(input())):
x, y= list(map(int, input().split()))
s1, s2= s1+x, s2+y
if(s1>s2):
lead=(s1-s2)
mlead1= max(mlead1, lead)
else:
lead=(s2-s1)
mlead2= max(mlead2, lead)
if(mlead1<(mlead2)):
print('2', mlead2)
else:
print('... | |
APPS_405 | Dr. S. De teaches computer architecture in NIT Patna. Whenever he comes across any good question(with complexity $k$), he gives that question to students within roll number range $i$ and $j$
At the start of semester he assigns score of $10$ to every student in his class if a student submits a question of complexity $k$... | try:
t=int(input())
for a in range(t):
l=input().split()
n=int(l[0])
m=int(l[1])
d={}
s=0
for b in range(m):
l1=input().split()
i=int(l1[0])
j=int(l1[1])
k=int(l1[2])
for c in range(i,j+1):
if c not in d:
d[c]=10
for c in range(i,j+1):
d[c]=d[c]*k
for i in d:
s=s+d[i]
... | |
APPS_406 | You are given an N × N grid initially filled by zeros. Let the rows and columns of the grid be numbered from 1 to N, inclusive. There are two types of operations can be applied to the grid:
- RowAdd R X: all numbers in the row R should be increased by X.
- ColAdd C X: all numbers in the column C should be increased by... | n,q=map(int,input().split())
dr={}
dc={}
for i in range(1,n+1):
dr[i]=0
dc[i]=0
mer=0
mec=0
for i in range(q):
s,j,k=input().split()
j=int(j)
k=int(k)
if s=="RowAdd":
dr[j]+=k
if dr[j]>mer:
mer=dr[j]
else:
dc[j]+=k
if mec<dc[j]:
mec=dc[j]
# m=max(list(dr.values()))+max(list(dc.values()))
# for i i... | |
APPS_407 | The activity of a panipuri seller is "making a panipuri and putting it on the palte of his customer".
$N$ customers are eating panipuri, Given an array $A$ of length $N$, $i^{th}$ customer takes $A_i$ seconds to eat a panipuri.
The Speed of Panipuri seller refers to the number of customers served per second. D... | # cook your dish here
from math import ceil
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
ans=ceil(n/min(a))
print(int(ans)) | |
APPS_408 | A group of rebels travelling on a square hoverboard is ambushed by Imperial Stormtroopers.Their big hoverboard is an easy target, so they decide to split the board into smaller square hoverboards so that they can bolt away easily.But they should also make sure they don't get too spread out.Help the rebels split the cra... | a=int(input())
if(a%2==0):
print("4")
print(a/2,a/2,a/2,a/2)
else:
print("6")
print((a-1)/2,(a-1)/2,(a-1)/2,(a-1)/2,(a-1)/2,(a+1)/2) | |
APPS_409 | Chef Leonardo has a decimal integer $N$ and a non-zero decimal digit $d$. $N$ does not contain the digit zero; specifically, $N$ should always be treated as a decimal integer without leading zeroes.
Chef likes $d$ and does not like any other digit, so he decided to change $N$. He may apply the following operation any n... | for _ in range(int(input())):
n,d=map(str,input().split())
k=list(n)
dd,c,n=d,0,len(n)
for x in range(n):
if int(k[n-x-1])>int(d):
k.pop(n-x-1)
c+=1
else:
d=k[n-x-1]
print(''.join(k)+c*dd) | |
APPS_410 | You are given an array A consisting of N integers. A group of disjoint subarrays in it will be a collection of subarrays of the array. Formally a group of subarrays consisting of K subarrays can be denoted by 2 * K indices, [i1, j1], [i2, j2] , ..., [iK, jK], such that i1 ≤ j1 < i2 ≤ j2 < ... < iK ≤ jK.
For example, i... | t=int(input())
for k in range(t):
n=int(input())
l=[int(i) for i in input().split()]
m={}
count=1
for i in range(1,n):
if l[i]==l[i-1]:
count+=1
else:
if l[i-1] not in m:
m[l[i-1]]=(count*(count+1))/2
else:
... | |
APPS_411 | Anmol gained a lot of weight last semester. So this semester, he decided to run everyday. There is a very long straight road starting at his hostel. There are N poles on the road - P1, P2, P3,..., PN on the road. All the poles lie on the same side of his hostel. The distance between Pi and his hostel is Di.
For 1 ≤ i, ... | #code snippet reference:http://www.geeksforgeeks.org/searching-for-patterns-set -2-kmp-algorithm/
def KMPMatch(pattern, string):
M = len(pattern)
N = len(string)
nonlocal ans
lps = [0]*M
j = 0
LPSCompute(pattern, M, lps)
i = 0
while i < N:
if pattern[j] == string[i]:
i+=1
j+=1
if j==M:
ans+... | |
APPS_412 | Alice likes prime numbers. According to Alice, only those strings are nice whose sum of character values at a prime position is prime. She has a string $S$. Now, she has to count the number of nice strings which come before string $S$( including $S$) in the dictionary and are of the same length as $S$.
Strings are zer... | import sys
from collections import defaultdict
from copy import copy
MOD = 10**9 + 7
R = lambda t = int: t(input())
RL = lambda t = int: [t(x) for x in input().split()]
RLL = lambda n, t = int: [RL(t) for _ in range(n)]
# primes up to n
def primes(n):
P = []
n = int(n)
U = [1] * (n+1)
p = 2
... | |
APPS_413 | Navnit is a college student and there are $N$ students in his college .Students are numbered from $1$ to $N$.
You are given $M$ facts that "Student $A_i$ and $B_i$".The same fact can be given multiple times .If $A_i$ is a friend of $B_i$ ,then $B_i$ is also a friend of $A_i$ . If $A_i$ is a friend of $B_i$ and $B_i$ is... | # cook your dish here
from collections import defaultdict
d=defaultdict(list)
def dfs(i):
p=0
nonlocal v
e=[i]
while(e!=[]):
p+=1
x=e.pop(0)
v[x]=1
for i in d[x]:
if v[i]==-1:
v[i]=1
e.append(i)
return p
n,... | |
APPS_414 | A number K$K$ is said to be magical if it can be represented as a power of 2 only.That is K$K$=2x$2^{x}$ for some natural number x$x$.
Given a string of digits S$S$ of length N$N$, Let P be a valid arrangement of S.
By valid arrangement we mean that it should not have any leading zeroes.
Find the sum of all such disti... | from math import log2, ceil
MOD = int(1e9 + 7)
srt = lambda s: ''.join(sorted(s))
for _ in range(int(input())):
s = srt(input())
res = -1
for p in range(ceil(log2(int(s))), int(log2(int(s[::-1]))) + 1):
if int(srt(str(pow(2, p)))) == int(s):
if res == -1: res = 0
res... | |
APPS_415 | Chef has a garden with $N$ plants arranged in a line in decreasing order of height. Initially the height of the plants are $A_1, A_2, ..., A_N$.
The plants are growing, after each hour the height of the $i$-th plant increases by $i$ millimeters. Find the minimum number of integer hours that Chef must wait to have two p... |
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
hrs = arr[0] - arr[1]
for i in range(1, n-1):
if hrs > arr[i] - arr[i+1]:
hrs = arr[i] - arr[i+1]
print(hrs) | |
APPS_416 | The snakes want to build a temple for Lord Cobra. There are multiple strips of land that they are looking at, but not all of them are suitable. They need the strip of land to resemble a coiled Cobra. You need to find out which strips do so.
Formally, every strip of land, has a length. Suppose the length of the i-th str... | # cook your dish here
for i in range(int(input())):
N=int(input())
L=list(map(int,input().split()))
l,h=0,N-1
flag=1
if L[l]!=1 and L[h]!=1:
flag=0
else:
while(l<h):
if (L[l]!=L[h]) or (L[l+1]-L[l]!=1 and L[h-1]-L[h]!=1):
flag=0
break
l+=1
h-=1
if flag:
print("yes")
else:
print("no") | |
APPS_417 | Note : This question carries $100$ $points$
CodeLand is celebrating a festival by baking cakes! In order to avoid wastage, families follow a unique way of distributing cakes.
For $T$ families in the locality, $i$-th family (1 <= $i$ <= $T$) has $N$ members. They baked $S$ slices of cakes. The smallest member of the fam... | # cook your dish here
extra, less = 0,0
for _ in range(int(input())):
sli,mem,sma,luc = list(map(int, input().split()))
total = sma
t = sma
while mem > 1:
t *= luc
total += t
mem -= 1
if total <= sli:
extra += sli-total
print('POSSIBLE',sli-total)
else:
... | |
APPS_418 | This is probably the simplest problem ever. You just need to count the number of ordered triples of different numbers (X1, X2, X3), where Xi could be any positive integer from 1 to Ni, inclusive (i = 1, 2, 3).
No, wait. I forgot to mention that numbers N1, N2, N3 could be up to 1018. Well, in any case it is still quite... | d=1000000007
for _ in range(int(input())):
l=sorted(list(map(int,input().split())))
ans=(l[0]%d)*((l[1]-1)%d)*((l[2]-2)%d)
print(ans%d) | |
APPS_419 | Chef recently learned about concept of periodicity of strings. A string is said to have a period P, if P divides N and for each i, the i-th of character of the string is same as i-Pth character (provided it exists), e.g. "abab" has a period P = 2, It also has a period of P = 4, but it doesn't have a period of 1 or 3.
C... | T=int(input())
for i in range(T):
n,m=list(map(int,input().split()))
if(m<=2):
print("impossible")
else:
l=[0]*m
if(m%2==0):
a=m//2
else:
a=(m//2)+1
for j in range(a):
if(j%2==0):
l[j]="a"
l[m-j-1]="a"
else:
l[j]="b"
l[m-j-1]="b... | |
APPS_420 | Chef has some numbers. His girlfriend Chefina feels good when chef gives her a particular pattern number also called as Armstrong number.
Armstrong number is a number whose sum of its all individual digit raise to the power of the number of digit in that number is equal to that number itself
eg.. 153 = 1^3 + 5^3 + 3^3 ... | def power(x, y):
if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)
return x * power(x, y // 2) * power(x, y // 2)
# Function to calculate order of the number
def order(x):
# Variable to store of the number
n = 0
while (x != 0):
n = n + 1
x = x // 10
return n
# Function t... | |
APPS_421 | After a long and successful day of preparing food for the banquet, it is time to clean up. There is a list of n jobs to do before the kitchen can be closed for the night. These jobs are indexed from 1 to n.
Most of the cooks have already left and only the Chef and his assistant are left to clean up. Thankfully, some o... | T = int(input())
for _ in range(T):
n,m = map(int,input().split())
completed = list(map(int,input().split()))
jobs = []
for i in range(1,n+1):
if i not in completed:
jobs.append(i)
jobs.sort()
chef = []
ass = []
for i in range(len(jobs)):
if i%2==0:
chef.append(str(jobs[i]))
else:
ass.append(str(... | |
APPS_422 | Let's consider a rooted binary tree with the following properties:
- The number of nodes and edges in the tree is infinite
- The tree root is labeled by $1$
- A node labeled by $v$ has two children: $2 \cdot v$ (the left child of $v$), and $2 \cdot v + 1$ (the right child of $v$).
Here is an image of the first several ... | t = int(input())
while(t>0):
t-=1;
n,l,r = list(map(int,input().split()));
a = bin(l)[2:];
b = bin(r)[2:];
# find matching
z = 0;
l = min(len(a),len(b));
for i in range(l):
if a[i]==b[i]:
z+=1;
else:
break;
#find base string
a = a[z:]
b = b[z:]
if(len(a)==0 and len(b)==0):
print(n);
else :
m... | |
APPS_423 | Chef taught his brother Chefu about right angled triangle and its properties. Chefu says that he has understood everything about right angled triangles. Chef wants to check learning of his brother by asking the following question "Can you find a right angled triangle whose length of hypotenuse is H and its area is S?"... | import math
t = eval(input())
while(t > 0):
h,s = input().split()
h = int(h)
s = int(s)
if(((h*h*h*h) - (16*s*s)) < 0):
print("-1")
else:
B = (math.sqrt((h*h) + math.sqrt((h*h*h*h) - (16*s*s))))/math.sqrt(2)
P = (2*s)/B
if(B > P):
print('{0:.6f}'.format(P),'{0:.6f}'.format(B),'{0:.6f}'.format(h))
else... | |
APPS_424 | Consider a 2d-grid. That is, each cell is identified by (i,j). You have received reports of two snake-sightings on this grid. You want to check whether they could be partial sightings of the same snake or not.
Each of the snake sightings correspond to a straight, axis-parallel line segment in the grid, and the starting... | # cook your dish here
t=int(input())
for _ in range(t):
x1,y1,x2,y2=map(int,input().split())
x3,y3,x4,y4=map(int,input().split())
if (x1==x3 and y1==y3)or(x2==x4 and y2==y4):
print("yes")
elif (x1==x4 and y1==y4)or(x2==x3 and y2==y3):
print("yes")
else:
if(y1==y2)and(y1==y3)and(y1==y4):
a1=max(x1,x2);a2=m... | |
APPS_425 | Two's company, three's a crowd!
It's been one year since Chef met his brother. Last year, his younger brother came to visit him during this time of the year. This year, the Chef is planning to go visit his brother. Chef's brother has planned to throw a "Welcome Party" for him. He wants to invite people from his neighbo... | MOD = int(1e9+7)
def mult(a, b):
rsp = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(3):
for j in range(3):
for k in range(3):
rsp[i][j] += a[i][k] * b[k][j]
rsp[i][j] %= MOD
return rsp
ident = [[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
m = [[1, 1, 0],
[1, 0, 1],
[1, 0, 0]]
powers = [m]
f... | |
APPS_426 | A string with length $L$ is called rich if $L \ge 3$ and there is a character which occurs in this string strictly more than $L/2$ times.
You are given a string $S$ and you should answer $Q$ queries on this string. In each query, you are given a substring $S_L, S_{L+1}, \ldots, S_R$. Consider all substrings of this sub... | t=int(input())
for _ in range(t):
n,q=map(int,input().split())
s=input()
l=[0]*(n-1)
for i in range(n-2):
a,b,c=s[i],s[i+1],s[i+2]
if len(set([a,b,c]))<3:
l[i]=l[i-1]+1
else:
l[i]=l[i-1]
for i in range(q):
left,right=map(int,input().split())
left-=1
right-=1
if right-left+1 <3:
print('N... | |
APPS_427 | Chef wants to gift pairs to his friends this new year. But his friends like good pairs
only.
A pair (a , b) is called a good pair if 1 <= a < b <= N such that GCD(a*b , P) = 1.
Since Chef is busy in preparation for the party, he wants your help to find all the
good pairs.
—————————————————————————————————————
INPUT
• T... | # cook your dish here
def G(x, y):
while(y):
x, y = y, x % y
return x
# t=int(input())
# l=list(map(int,input().split()))
for _ in range(int(input())):
n,p=map(int,input().split())
c=0
for i in range(1,n+1):
if G(i,p)==1:
c+=1
ans=c*(c-1)//2
print(ans) | |
APPS_428 | You're given an integer N. Write a program to calculate the sum of all the digits of N.
-----Input-----
The first line contains an integer T, the total number of testcases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, calculate the sum of digits of N, and display it in... | # cook your dish here
number = int(input())
for i in range(number):
a = list(input())
for k in range(len(a)):
a[k] = eval(a[k])
print(sum(a)) | |
APPS_429 | Bears love candies and games involving eating them. Limak and Bob play the following game. Limak eats 1 candy, then Bob eats 2 candies, then Limak eats 3 candies, then Bob eats 4 candies, and so on. Once someone can't eat what he is supposed to eat, he loses.
Limak can eat at most A candies in total (otherwise he would... | for t in range(int(input())):
limakMax, bobMax = list(map(int, input().split()))
limakEat = 0; bobEat = 0
eating = 1
while limakEat <= limakMax or bobEat <= bobMax:
if eating % 2 != 0 and limakEat <= limakMax:
limakEat += eating
eating += 1
if limakEat > limakMax:
print("Bob")
break
elif eatin... | |
APPS_430 | Chef bought a huge (effectively infinite) planar island and built $N$ restaurants (numbered $1$ through $N$) on it. For each valid $i$, the Cartesian coordinates of restaurant $i$ are $(X_i, Y_i)$.
Now, Chef wants to build $N-1$ straight narrow roads (line segments) on the island. The roads may have arbitrary lengths; ... | import sys
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return list(map(int, sys.stdin.readline().strip().split()))
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
t=iinput()
for _ in range(t):
n=iinput()
p=[]
mi=[]
for i in... | |
APPS_431 | There are three squares, each with side length a placed on the x-axis. The coordinates of centers of these squares are (x1, a/2), (x2, a/2) and (x3, a/2) respectively. All of them are placed with one of their sides resting on the x-axis.
You are allowed to move the centers of each of these squares along the x-axis (eit... | t=int(input())
for i in range(t):
a,k=list(map(int,input().split()))
x1,x2,x3=list(map(int,input().split()))
big=max(x1,x2,x3)
small=min(x1,x2,x3)
q=big-small-2*k
if q>=a:
print(0)
elif -1*q>=0:
print(a*a)
else:
print(a*(a-q))
| |
APPS_432 | Lira is now very keen on compiler development. :)
She knows that one of the most important components of a compiler, is its parser.
A parser is, in simple terms, a software component that processes text, and checks it's semantic correctness, or, if you prefer, if the text is properly built.
As an example, in declaring... | # cook your dish here
t=int(input())
for j in range(t):
s=input()
st=[]
ans=0
for i in range(len(s)):
if(s[i]=='>'):
if(len(st)!=0 and st[-1]=='<'):
st.pop()
if(len(st)==0):
ans=i+1
else:
break
... | |
APPS_433 | You are given positive integers $N$ and $D$. You may perform operations of the following two types:
- add $D$ to $N$, i.e. change $N$ to $N+D$
- change $N$ to $\mathop{\mathrm{digitsum}}(N)$
Here, $\mathop{\mathrm{digitsum}}(x)$ is the sum of decimal digits of $x$. For example, $\mathop{\mathrm{digitsum}}(123)=1+2+3=6$... | from collections import deque
T=int(input())
def break_down(num):
count=0
while(len(num)!=1):
temp=0
for i in range(0,len(num)):
temp=temp+int(num[i])
num=str(temp)
count=count+1
return (int(num),count)
def digit_sum(num):
temp=0
for i in ran... | |
APPS_434 | Chef is planning a huge party for all of you and has ordered M pizzas. He wants to invite as many people to the party. However, he knows that everyone will have exactly one slice of a pizza (regardless of the size) and he wants to make sure that he has enough pizza slices.
Chef is very lazy and will only make a total ... | # cook your dish here
m,n=[int(i) for i in input().split()]
arr=list(map(int,input().split()))
arr=sorted(arr,reverse=True)
ans=0
w=0
q=m
for m in range(q):
if(arr[m]>n):
w=1
break
ans+=1+(arr[m]*(arr[m]+1))//2
n-=arr[m]
if(n==0):
print(ans)
else:
if(w==1):
... | |
APPS_435 | Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
-----Input-----
The first line contains an integer T, the total number of testcases. Then T lines follow, each line contain... | n=int(input())
for i in range(n):
a,b,c=map(int,input().split())
if a>0 and b>0 and c>0 and a+b+c==180:
print("YES")
else:
print("NO") | |
APPS_436 | There is a popular apps named “Exbook” like “Facebook”. To sign up in this app , You have to make a strong password with more than 3 digits and less than 10 digits . But I am a pro hacker and so I make a Exbook hacking site . You need to login in this site to hack exbook account and then you will get a portal. You can ... | # cook your dish here
t=int(input())
for i in range(0,t):
p=input()
l=list(p)
for j in range(0,len(l)):
l[j]=int(l[j])
l[j]=l[j]-2
for j in range(0,len(l)):
l[j]=str(l[j])
q=''.join(l)
print(q) | |
APPS_437 | You have an array A of size N containing only positive numbers. You have to output the maximum possible value of A[i]%A[j] where 1<=i,j<=N.
-----Input-----
The first line of each test case contains a single integer N denoting the size of the array. The next N lines contains integers A1, A2, ..., AN denoting the numbe... | n = int(input())
a = []
for i in range(n):
a.append(int(input()))
m1 = 0
m2 = 0
for e in a:
if (e > m1):
m2 = m1
m1 = e
elif (e > m2 and e != m1):
m2 = e
ans = 0
for e in a:
temp = m1%e
if (temp>ans):
ans = temp
print(max(m2%m1,ans)) | |
APPS_438 | Chef and Abhishek both are fighting for the post of Chairperson to be part of ACE committee and are trying their best. To select only one student their teacher gave them a binary string (string consisting of only 0's and 1's) and asked them to find number of sub-strings present in the given string that satisfy the foll... | def countSubstr(str, n, x, y):
tot_count = 0
count_x = 0
for i in range(n):
if str[i] == x:
count_x += 1
if str[i] == y:
tot_count += count_x
return tot_count
t=int(input())
for _ in range(t):
n=int(input())
str=input()
... | |
APPS_439 | Chef is playing with an expression which consists of integer operands and the following binary
Bitwise operators - AND, OR and XOR. He is trying to figure out that what could be the Maximum possible answer of the expression, given that he can perform the operation in any order i.e not necessarily follow the rule of Pr... | # cook your dish here
def value(a, b, c):
if(c == '&'):
return a&b
elif(c == '^'):
return a^b
elif(c == '|'):
return a|b
def break_rules(n, operator):
if(len(n) == 1):
return n
elif(len(n) == 2):
return [value(n[0], n[1], operator[0])]
else:
cont_... | |
APPS_440 | -----
CHEF N TIMINGS
-----
One day chef was working with some random numbers. Then he found something
interesting. He observed that no 240, 567, 9999 and 122 and called these numbers
nice as the digits in numbers are in increasing order. Also he called 434, 452, 900
are not nice as digits are in decreasing order
N... | for _ in range(int(input())):
n=input().rstrip()
n=[ele for ele in n]
l=len(n)
m=10**18+8
ini=1
for i in range(l-1,-1,-1):
if int(n[i])<=m:
if ini==1:
m=int(n[i])
else:
m=max(m,n[i])
else:
m=int(n[i])-1
n[i]=str(m)
for j in range(l-1,i,-1):
n[j]='9'
i=0
while n[i]=='0':
i+=1... | |
APPS_441 | Ada's classroom contains $N \cdot M$ tables distributed in a grid with $N$ rows and $M$ columns. Each table is occupied by exactly one student.
Before starting the class, the teacher decided to shuffle the students a bit. After the shuffling, each table should be occupied by exactly one student again. In addition, each... | # cook your dish here
t=int(input())
for _ in range(t):
N, M=map(int,input().split())
if(N%2==0 or M%2==0):
print("YES")
else:
print("NO") | |
APPS_442 | Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program.
Program is very simple, Given two integers A and B, write a program to add these two numbers.
-----Input-----
The first line contains an integer T, the total number of t... | #Note that it's python3 Code. Here, we are using input() instead of raw_input().
#You can check on your local machine the version of python by typing "python --version" in the terminal.
#Read the number of test cases.
T = int(input())
for tc in range(T):
# Read integers a and b.
(a, b) = list(map(int, input().split(... | |
APPS_443 | and Bengali as well.
There are N$N$ cats (numbered 1$1$ through N$N$) and M$M$ rats (numbered 1$1$ through M$M$) on a line. Each cat and each rat wants to move from some point to some (possibly the same) point on this line. Naturally, the cats also want to eat the rats when they get a chance. Both the cats and the rats... | # cook your dish here
# cook your dish here
class Animal:
def __init__(self):
start, end, starting_time = map(int, input().split())
self.ending_time = starting_time + abs(start - end)
self.velocity = 1 if end >= start else -1
self.eaten_by = -1, 10 ** 10
... | |
APPS_444 | Chef is making Window frames for his new office, for this he has n wooden Logs whose lengths are l1, l2, … ln respectively. Chef Doesn’t want to break any logs or Stick 2 or more logs together.
To make a h × w Window Frame, he needs two Logs with lengths equal h and two with length .
The Chef wants as much sunlight ... | # cook your dish here
t=int(input())
j=0
while j<t:
n=int(input())
lst=list(map(int,input().split()))
s=set()
d=list()
for i in lst:
if i in s:
s.remove(i)
d.append(i)
else:
s.add(i)
x=len(d)
if x%2==0:
print(x//2)
else:
... | |
APPS_445 | You are given an unweighted tree with N$N$ nodes (numbered 1$1$ through N$N$). Let's denote the distance between any two nodes p$p$ and q$q$ by d(p,q)$d(p, q)$.
You should answer Q$Q$ queries. In each query, you are given parameters a$a$, da$d_a$, b$b$, db$d_b$, and you should find a node x$x$ such that d(x,a)=da$d(x, ... | # cook your dish here
class TestCase:
def __init__(self):
[self.node_count, self.query_count] = read_line()
def fill_nodes(self):
self.nodes = {n+1: [] for n in range(self.node_count)}
for i in range(self.node_count -1):
new_node_1, new_node_2 = read_line()
... | |
APPS_446 | For her next karate demonstration, Ada will break some bricks.
Ada stacked three bricks on top of each other. Initially, their widths (from top to bottom) are $W_1, W_2, W_3$.
Ada's strength is $S$. Whenever she hits a stack of bricks, consider the largest $k \ge 0$ such that the sum of widths of the topmost $k$ bricks... | t=int(input())
for i in range(t):
n,w1,w2,w3=map(int,input().split())
if n>=w1+w2+w3:
print(1)
elif n>=w1+w2 or n>=w2+w3:
print(2)
else:
print(3) | |
APPS_447 | Every day, Mike goes to his job by a bus, where he buys a ticket. On the ticket, there is a letter-code that can be represented as a string of upper-case Latin letters.
Mike believes that the day will be successful in case exactly two different letters in the code alternate. Otherwise, he believes that the day will be... | def res(s):
if len(s) == 2:
if s[0] == s[1]:
print("NO")
else:
print("YES")
elif s[0] != s[1]:
counte = 0
for i in range(2, len(s)):
if i % 2 == 0:
if s[i] != s[0]:
counte = 1
break
else:
if s[i] != s[1]:
counte = 1
break
if counte == 0:
print("YES")
else:
p... | |
APPS_448 | You are given a binary string S. You need to transform this string into another string of equal length consisting only of zeros, with the minimum number of operations.
A single operation consists of taking some prefix of the string S and flipping all its values. That is, change all the 0s in this prefix to 1s, and all ... | # cook your dish here
s=input()
s1=s[::-1]
arr=[]
cnt=0
for i in range(len(s1)):
arr.append(s1[i])
for i in range(len(arr)):
if(arr[i]=="1"):
for j in range(i,len(arr)):
if(arr[j]=="1"):
arr[j]="0"
else:
arr[j]="1"
cnt+=1
print(cnt) | |
APPS_449 | Let's define the niceness of a sequence of positive integers X1,X2,…,XN$X_1, X_2, \dots, X_N$ as the sum of greatest common divisors of all pairs of its elements, i.e.
N∑i=1N∑j=i+1gcd(Xi,Xj).∑i=1N∑j=i+1Ngcd(Xi,Xj).\sum_{i=1}^N \sum_{j=i+1}^N \mathrm{gcd}(X_i, X_j)\;.
For example, the niceness of the sequence [1,2,2]$[1... | # cook your dish here
mod = 10**9 + 7
from math import gcd
def fac50():
f = [0]*51
f[0] ,f[1] = 1,1
for i in range(1,51):f[i] = (f[i-1]*i)%mod
return f
def gcd110():
gc = [[0]*111 for i in range(111)]
for i in range(111):
for j in range(111):gc[i][j] = gcd(i,j)
return gc
factorials,g... | |
APPS_450 | Two cheeky thieves (Chef being one of them, the more talented one of course) have came across each other in the underground vault of the State Bank of Churuland. They are shocked! Indeed, neither expect to meet a colleague in such a place with the same intentions to carry away all the money collected during Churufest 2... | t=int(input())
while(t):
s=input().split()
m=int(s[0])
p=float(s[1])
if(m%2==0):
r=(1-p**m)/(p+1)
else:
r=(1+p**m)/(p+1)
print(1000000000*r,1000000000*(1-r))
t-=1 | |
APPS_451 | The garden has a tree with too many leaves on it and gardner wants to cut the unwanted leaves. This is a rooted tree, where a node $v$ is called parent of another node $u$, if there exists a directed edge from $v$ to $u$. Leaf node is a node with no outgoing edges.
Gardner cuts the tree in a peculiar way:
- For each pa... | def dfs(node):
nonlocal adj,leaf
val=0
flag=0
for i in adj[node]:
x= dfs(i)
val+=x
if x==0:
flag=1
leaf+=val-val%3
if val%3==0 and flag==0:
return 1
else:
return 0
for _ in range(int(input())):
n=int(input())
adj=[[] for i in range(n+2)]
arr=[int(i) for i in input().split()]
leaf=0
#print(adj)
... | |
APPS_452 | Rupsa really loves triangles. One day she came across an equilateral triangle having length of each side as an integer N. She started wondering if it was possible to transform the triangle keeping two sides fixed and alter the third side such that it still remains a triangle, but the altered side will have its length a... | # cook your dish here
import math
def isPos(num):
if num%2==0:
for i in range(num,2*num,1):
if ((num**2)-((i/2)**2))**(1/2)==int(((num**2)-((i/2)**2))**(1/2)):
return 'YES'
return 'NO'
else:
for i in range(num+1,2*num,1):
if ((num**2)-((i/2)**2))**(1/2)==int(((num**2)-((i/2)**2))**(1/2)):
return '... | |
APPS_453 | Two words rhyme if their last 3 letters are a match. Given N words, print the test case number (of the format Case : num) followed by the rhyming words in separate line adjacent to each other.
The output can be in anyorder.
-----Input-----
First line contains the number of test case T
The next line contains the numb... | t = int(input())
for i in range(t):
n = int(input())
suffixes = {}
xx = input().split()
for x in range(n):
try:
a = suffixes[xx[x][-3:]]
except Exception as e:
a = []
a.append(xx[x])
suffixes.update({xx[x][-3:]: a})
print("Case : %d" % (i + 1))
for a in sorted(suffixes):
print("".join(b + " " fo... | |
APPS_454 | Indraneel has to sort the books in his library. His library has one long shelf. His books are numbered $1$ through $N$ and he wants to rearrange the books so that they appear in the sequence $1,2, ..., N$.
He intends to do this by a sequence of moves. In each move he can pick up any book from the shelf and insert it at... | n=int(input())
arr=[int(x) for x in input().split()]
l=[1]*n
if sorted(arr)==arr:
print('0')
else:
for i in range(0,len(arr)):
for j in range(i):
if arr[i]>=arr[j] and l[i]<l[j]+1:
l[i]=l[j]+1
print(n-max(l)) | |
APPS_455 | This question is similar to the $"Operation$ $on$ $a$ $Tuple"$ problem in this month's Long Challenge but with a slight variation.
Consider the following operations on a triple of integers. In one operation, you should:
- Choose a positive integer $d>0$ and an arithmetic operation - in this case, it will only be addi... | # cook your dish here
"""
Input:
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains three space-separated integers p, q and r.
The second line contains three space-separated integers a, b and c.
Ou... | |
APPS_456 | After failing to clear his school mathematics examination, infinitepro decided to prepare very hard for his upcoming re-exam, starting with the topic he is weakest at ― computational geometry.
Being an artist, infinitepro has C$C$ pencils (numbered 1$1$ through C$C$); each of them draws with one of C$C$ distinct colour... | from collections import Counter
from math import factorial
def nc3(n):
a=factorial(n)
b=factorial(n-3)
return ((a)/(b*6))
def rem(s,k):
t=-1
x=-1
for i in range(len(s)):
if s[i][0]>2 and s[i][1]<=k:
if s[i][0]>3:
ch=(nc3(s[i][0])-nc3(s[i][0]-1))/s[... | |
APPS_457 | Kabir Singh is playing a game on the non-negative side of x-axis. It takes him $1 second$ to reach from Pth position to (P−1)th position or (P+1)th position.
Kabir never goes to the negative side and also doesn't stop at any moment of time.
The movement can be defined as :
- At the beginning he is at $x=0$ , at tim... | # cook your dish here
T=int(input())
MOD=int(1e9+7)
for t in range(T):
N,K=[int(a) for a in input().split()]
M=K//2
# ans= ((K%2)?( (N+M)*(N+M) + M ):( (N+M)*(N+M) - M) )
ans=(N+M)*(N+M) -M
if(K%2):
ans+=2*M
if(N==0):
ans=K*(K-1)
print(ans%MOD) | |
APPS_458 | Polo, the Penguin, likes numbers. He says that the goodness of a number is itself multiplied by the number of digits in it's decimal representation. For example, the goodness of the integer 474 is 474*3 = 1422.
Help him to count the sum of goodness of all integers from L to R, inclusive. Since the answer can be too lar... | # cook your dish here
from sys import stdin
from math import sqrt,ceil,log10
def get_sum(a,b,digits):
sum=((b+a)*(b-a+1))//2
return sum*digits
def solve():
mod=10**9+7
thehighlimiter={i: 10 ** i - 1 for i in range(12)}
thelowlimiter={i: 10**i for i in range(12)}
for _ in range(int(input())):
... | |
APPS_459 | Sumit and Dhiraj are roommates in a hostel of NIT Jamshedpur,One day after completing there boring assignments of Artificial Intelligence, they decided to play a game as it was dhiraj,s idea to play a game so he started explaining the rules of the game to sumit.
So the game was as follows-They randomly took a number N ... | import math
for t in range(int(input())):
n = int(input())
temp = math.sqrt(n)
if (temp == int(temp)):
print("YES")
else:
print("NO") | |
APPS_460 | Given an array A of length N, your task is to find the element which repeats in A maximum number of times as well as the corresponding count. In case of ties, choose the smaller element first.
-----Input-----
First line of input contains an integer T, denoting the number of test cases. Then follows description of T ca... | t = input();
a = [0 for i in range(10001)]
i = 0;
while i < int(t):
n = input();
k = input();
assert(len(k.split(' ')) == int(n));
for each in k.split(' '):
a[int(each)] += 1;
V = 0;
C = a[V];
for j in range(10001):
if C < a[j]:
V = j;
C = a[V];
a[j] = 0;
i += 1;
print(V, C);
| |
APPS_461 | Chefu is Chef's little brother, he is 12 years old and he is new to competitive programming.
Chefu is practicing very hard to become a very skilled competitive programmer and win gold medal in IOI.
Now Chefu is participating in a contest and the problem that he is trying to solve states:
Given an array A of N integers,... | T=int(input())
for i in range(T):
N=int(input())
A=list(map(int,input().split()))[:N]
l=[]
for j in range(len(A)):
for k in range(j+1,len(A)):
l.append(A[j]+A[k])
print(l.count(max(l))/((N*(N-1))/2)) | |
APPS_462 | You are given a tree with $N$ vertices (numbered $1$ through $N$) and a sequence of integers $A_1, A_2, \ldots, A_N$. You may choose an arbitrary permutation $p_1, p_2, \ldots, p_N$ of the integers $1$ through $N$. Then, for each vertex $i$, you should assign the value $A_{p_i}$ to this vertex.
The profit of a path bet... | T = int(input())
M = 10 ** 9 + 7
for _ in range(T):
N = int(input())
A = list(map(int, input().split()))
if N == 1:
print(0)
continue
B = {}
C = {}
for i in range(N - 1):
u, v = input().split()
u = int(u) - 1
v = int(v) - 1
if u not in B:
B[u] = []
if v not in B:
B[v] = []
B[u].appe... | |
APPS_463 | -----Problem Statement-----
We have an integer sequence $A$, whose length is $N$.
Find the number of the non-empty contiguous subsequences of $A$ whose sum is $0$. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individua... | from collections import defaultdict
def findSubarraySum(arr, n, Sum):
# Dictionary to store number of subarrays
# starting from index zero having
# particular value of sum.
prevSum = defaultdict(lambda : 0)
res = 0
# Sum of elements so far.
currsum = 0
for i in range(0, n):
# Add c... | |
APPS_464 | It is the end of 2019 — the 17th of November, the Cooking Challenge day.
There are N$N$ players participating in this competition, numbered 1$1$ through N$N$. Initially, the skill level of each player is zero. There are also M$M$ challenges (numbered 1$1$ through M$M$). For each valid i$i$, the i$i$-th challenge has th... | import numpy as np
def sort_it(array):
new_list = []
for i in range(len(array)):
start = 0
value = array[i][0]
last = len(new_list)
while start != last:
mid = (start + last) // 2
if new_list[mid][0] > value:
last = mid
else:
... | |
APPS_465 | Chef is playing a game which contains a binary string.
He can perform one operation only:
- Toggle the i_th bit of the string (0 to 1 or 1 to 0)
By performing operations on the string (can be zero times), you have to convert the string with no adjacent bit being the same.
Can you help chef ?
-----Input:-----
- First ... | '''
Name : Jaymeet Mehta
codechef id :mj_13
Problem : Avenir Strings
'''
from sys import stdin,stdout
test=int(stdin.readline())
for _ in range(test):
N=int(stdin.readline())
seq=list(input())
fp,fp1,fl,fl1=0,0,0,1
for i in range(N):
if fl!=int(seq[i])-0:
fp+=1
fl=1-fl
for i in range(N):
if fl1!=int(seq[i... | |
APPS_466 | It's Diwali time and you are on a tour of Codepur, a city consisting of buildings of equal length and breadth because they were designed by a computer architect with a bit of OCD.
The ruling party of Codepur wants to have a blockbuster Diwali celebration but lack enough funds and decided to open a donation channel call... | #dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
def kadane(arr, start, finish, n):
Sum = 0
maxSum = float('-inf')
i = None
finish[0] = -1
local_start = 0
for i in range(n):
... | |
APPS_467 | Chef is stuck on the minute hand of a giant clock. To escape from this clock he needs to get onto the hour hand which has an exit door.
Since the minute hand and and hour hand are not connected at any point, chef will surely need to make a jump. Since he wants minimum risks, he chooses to jump on the hour hand so that... | # cook your dish here
t=int(input())
while t>0:
a=input().split(":")
a1=int(a[0])
a2=int(a[1])
b1=a1%12
if a2%5!=0:
b2=(a2//5)*5+5
else:
b2=a2
c1=b1*30
extra=0.5*b2
c1+=extra
c1%=360
d1=(b2//5)*30
d1%=360
if c1>d1:
ans1=c1-d1
ans2=360-ans1
else:
ans1=d1-c1
ans2=360-ans1
ans=min(a... | |
APPS_468 | Lumpy is a bus driver. Today, the conductor is absent so Lumpy has to do the conductor's job as well. There are N creatures in the bus. Sometimes the creatures don't carry change and can't pay the exact amount of the fare. Each creature in the bus today has paid an amount
greater than his/her fare. You are given inform... | # cook your dish here
# cook your dish here
t=int(input())
for _ in range(t):
n,p,q=list(map(int,input().split(" ")))
l=list(map(int,input().split(" ")))
l.sort()
s=sum(l)
a=p+2*q
b=0
for i in l:
if(p==0):
if(i%2==0 and a>=i):
a=a-i
b=b+1
elif(q==0):
if(a>=i):
a=a-i
b=b+1
else:
if(... | |
APPS_469 | Nitika was once reading a history book and wanted to analyze it. So she asked her brother to create a list of names of the various famous personalities in the book. Her brother gave Nitika the list. Nitika was furious when she saw the list. The names of the people were not properly formatted. She doesn't like this and ... | # cook your dish here
x= int(input())
for i in range(x):
y = list(map(str, input().split()))
j= 0
while j<len(y)-1:
print((y[j][0]).capitalize()+".", end=' ')
j+= 1
print(y[len(y)-1].capitalize()) | |
APPS_470 | The Chef is given an array of numbers and asked to find the first balance point of an array. A balance point is an index in the array N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no such balance point, print -1
-----Input-----
The first line of the... | import sys
t = eval(input())
for j in range(t):
n = eval(input())
a = list(map(int, input().split()))
ch = 0
sm = 0 ; x = sum(a)
s1 = [0] * n ; s2 = [0] * n
for i in range(n):
sm += a[i]
s1[i] = sm
s2[i] = x
x -= a[i]
if(sum(a) - a[0] == 0):
print(0)
elif(sum(a) - a[n - 1] == 0):
print(n - 1)
else... | |
APPS_471 | Chef’s girlfriend is angry with him because he forgot her birthday. Chef decided to please her by gifting her a Love Graph.
Chef has $N$ vertices: $V_1, V_2, \dots, V_N$. Love Graph is an undirected multigraph with no self-loops and can be constructed by performing the following operations:-
- Choose an integer $i$ ($... | def fastpow(base, power):
result = 1
while power > 0:
if power % 2 == 0:
power = power // 2
base = base * base
else:
power = power - 1
result = result * base
power = power // 2
base = base * base
return result
t=int(input())
for i in range(t):
a=list(map(int,input().split()))
n,r=a[0],a[1]
... | |
APPS_472 | Finally, a COVID vaccine is out on the market and the Chefland government has asked you to form a plan to distribute it to the public as soon as possible. There are a total of $N$ people with ages $a_1, a_2, \ldots, a_N$.
There is only one hospital where vaccination is done and it is only possible to vaccinate up to $D... | for _ in range(int(input())):
f,d=list(map(int,input().split()))
arr=list(map(int,input().split()))
risk=0
days_risk=0
days_norm=0
if d==1:
print(f)
else:
for a in arr:
if a>=80 or a<=9:
risk+=1
norm=f-risk
if risk%d==0:
days_risk=risk//d
else:
days_risk=(risk//d)+1
if norm%d==0:
days... | |
APPS_473 | Chef has N laddus of K sweetness each. Chef wants to eat all laddus, but Chef is restricted with the given condition that he must not eat two adjacent laddus. Chef starts calculating the maximum sweetness that he will get from the laddus. Find the maximum sweetness that chef gets at the end of all calculations.
-----... |
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
if n==1:
print(m)
else:
if n%2==0:
print((n//2)*m)
else:
print(((n//2)+1)*m) | |
APPS_474 | Vishal Wants to buy 2 gifts for his best friend whose name is Annabelle(her age is 20), So they both went for shopping in a store. But Annabelle gave, Vishal a condition that she will accept this gifts only when the total price of the gifts is the same as her age times 100.
The store contains, a list of items whose pri... | test = int(input())
ANS = list()
for i in range(test):
n = int(input())
items = sorted(list(map(int, input().split())))
c = 1
for j in range(len(items)):
if items[j] < 2000:
t = 2000 - items[j]
if t in items[j+1:]:
ANS.append("Accepted")
c = 2
break
else:
pass
else:
break
if c==1:
... | |
APPS_475 | Yash likes playing with numbers. He has a challenge for you. Yash gives
you a number that he made by multiplying two numbers. He claims that the
possible sum of the two numbers he multiplied is as minimum as possible. He
challenges you to find that minimum sum.
Formally, for a given value of N, you are required to fin... | # cook your dish here
def isPrime(n) :
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= ... | |
APPS_476 | In a bizarre game of chess ,knight was so drunk, that instead of his usual move he started walking straight. In every move Knight jumps on 2n steps forward (n is number of block that he had travelled so far from starting) but after that he has to take either 1 step forward or backward.
Now the Knight needs to get to po... | from math import log,pow
n=int(input())
a=[]
for i in range(n):
no=int(input())
if(no%2==0):
a.append("0")
elif(no==1):
a.append("1")
elif(no==3):
a.append("3")
else:
s="2"
lv=int(log(no,2))
clv=1
cno=3
while(cno!=no):
if(no<cno*pow(2,lv-clv)):
s=s+"1"
clv=clv+1
cno=(2*cno)-1
else... | |
APPS_477 | [Chopsticks (singular: chopstick) are short, frequently tapered sticks used in pairs of equal length, which are used as the traditional eating utensils of China, Japan, Korea and Vietnam. Originated in ancient China, they can also be found in some areas of Tibet and Nepal that are close to Han Chinese populations, as w... | # cook your dish here
a,b=list(map(int,input().split()))
ls=[]
for i in range(a):
ls.append(int(input()))
ls.sort()
c=0;i=0
while i<(a-1):
if ls[i+1]-ls[i]<=b:
c=c+1
i=i+1
i=i+1
print(c)
| |
APPS_478 | You are given a string S containing only lowercase characters.
You can rearrange the string and you have to print minimum number of characters needed(can be 0) to make it palindrome.
-----Input:-----
- First line contain an interger T denoting number of testcases.
- First line of each testcase contains integer N, siz... | # cooking dish here
from sys import stdin
from collections import Counter
read = stdin.readline
for testcase in range(int(read())):
length = int(read())
string = read().strip()
counts = Counter(string)
odd_counts = 0
for count in list(counts.values()):
# print(count, counts)... | |
APPS_479 | In the 2-D world of Flatland, the Circles were having their sports day and wanted to end it with a nice formation. So, they called upon Mr. Sphere from Spaceland for help. Mr Sphere decides to arrange the Circles in square formations. He starts with $N$ Circles and forms the largest possible square using these Circles.... | # cook your dish here
import math
for _ in range(int(input())):
n=int(input())
c=0
while(n>0):
i=int(math.sqrt(n))
c+=1
n=n-i**2
print(c)
| |
APPS_480 | There is a city with $N$ numbered $0 - N-1$ shops. A market is a place where we can reach from one shop to another using some road. There are $M$ roads in this city connecting each connecting any two shops.
Find the number of markets in the city.
NOTE: A market having only one shop is also a valid market.
-----Input... | from sys import stdin
from math import ceil, gcd
# Input data
#stdin = open("input", "r")
def dfs(src, visit):
visit[src] = 1
for nbr in d[src]:
if visit[nbr] == 0:
dfs(nbr, visit)
for _ in range(int(stdin.readline())):
n, m = list(map(int, stdin.readline().split()))
... | |
APPS_481 | Chef and his friends are playing the game AMONG US. They all have chosen their names as numbers. There are N people in Chef’s group including him, and each swears that he is not the imposter. However, it turns out there were N+1 people in the game. Now all that Chef needs to know is the name of the imposter, which is a... | try:
n=int(input())
x=[*list(map(int, input().split()))]
y=[*list(map(int, input().split()))]
for i in y:
d=x.count(i)-y.count(i)
if d!=0:
print(i)
break
except: pass
| |
APPS_482 | Autobots are instructed by Optimus Prime to mobilize in the form of a rectangular shape with each Autobot on each vertex of the rectangle region on a -”deployment area” (which may consist of one or more regions). This is done so as to take care of the inner rectangular area called “region”. However the rule states-“no ... | print | |
APPS_483 | Write a program, which takes an integer N and if the number is less than 10 then display "Thanks for helping Chef!" otherwise print "-1".
-----Input-----
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, output... | # cook your dish here
for i in range(int(input())):
x=int(input())
if x<10:
print("Thanks for helping Chef!")
else:
print("-1")
| |
APPS_484 | Chef is an advocate for Go Green Initiative. Today he had n trees planted in a row outside his his restaurant. Today, the height of i-th tree is hi feet. The trees grow at a rate of mi feet per day.
Chef knows that trees will look beautiful if they form a zig-zag sequence. The trees will be said to be in Zig-zag sequen... | def get(l,n):
l1,l2 = [],[]
i = 1
h1,m1 = l[0]
while (i < len(l)):
h2,m2 = l[i]
if (h1>h2):
if (m1 >= m2):
l1 += [(0,10**20)]
l2 += [(-1,-1)]
else:
d = (h1-h2)//(m2-m1)
if (((h1-h2)%(m2-m1)) == 0):
l1 += [(0,d-1)]
l2 += [(d+1,10**20)]
else:
l1 += [(0,d)]
l2 += [(d+1... | |
APPS_485 | In Snakeland, there are some snakes and mongooses. They are lined up in a row. The information about how exactly they are lined up it is provided to you by a string of length n. If the i-th character of this string is 's', then it means that there is a snake at the i-th position, whereas the character 'm' denotes a mon... | for i in range(int(input())):
a=input()
c=a.count('m')
d=a.count('s')
t=0
while t<len(a)-1:
if (a[t]=='m' and a[t+1]=='s') or (a[t]=='s' and a[t+1]=='m'):
d=d-1
t=t+2
else:
t=t+1
if c>d:
print('mongooses')
elif d>c:
print('snakes')
else:
print('tie')
| |
APPS_486 | Little Elephant is playing a game with arrays. He is given an array A0, A1, ..., AN−1 of N integers. And then Q queries are given, each containing an integer K. He has to tell how many subarrays satisfy the condition: the function foo returns K when it is applied to the subarray.
In this problem, a subarray is defined... | import sys
import math
def main(arr,k):
ans=0
for i in range(len(arr)):
curr_min=float('inf')
for j in range(i,len(arr)):
curr_min=min(curr_min,arr[j])
if curr_min==k:
ans+=1
return ans
n=int(input())
arr=list(map(int,inpu... | |
APPS_487 | Tom has finally taken over the business empire and now looking for
a new Name of the business to make a new start.
Joe (Tom's dear friend) suggested a string $S$ consisting of
Uppercase and lowercase letters
Tom wants to make some changes as per the following criteria:
1) String should $not$ have any vowels ... | s = input().lower()
vow = ["a", "e", "i", "o", "u", "y"]
ans = ""
for ch in s:
if ch in vow:
continue
if ch.isalpha():
ans += "." + ch
print(ans)
| |
APPS_488 | Abhishek is fond of playing cricket very much. One morning, he is playing cricket with his friends. Abhishek is a right-hand batsman
.He has to face all types of balls either good or bad. There are total 26 balls in the game and each ball is represented
by one of the following two ways:-
1. "g" denotes a good ball... | import sys
for _ in range(0,eval(input())):
d,inp,mp,n,q=set(),list(map(ord,list(sys.stdin.readline().strip()))),[x=='b' for x in list(sys.stdin.readline().strip())],eval(input()),ord('a')
inps = [inp[i:] for i in range(len(inp))]
inps.sort()
op,prev= 0,''
for ip in inps:
i,ct=0,0
... | |
APPS_489 | In order to establish dominance amongst his friends, Chef has decided that he will only walk in large steps of length exactly $K$ feet. However, this has presented many problems in Chef’s life because there are certain distances that he cannot traverse. Eg. If his step length is $5$ feet, he cannot travel a distance of... | t=int(input())
for i in range(0,t):
n,k=map(int,input().split())
a1,*a=map(int,input().split())
a.insert(0,a1)
j=0
while j<n:
if a[j]%k==0:
print(1,end="")
else:
print(0,end="")
j+=1
print("") | |
APPS_490 | Roger recently built a circular race track with length K$K$. After hosting a few races, he realised that people do not come there to see the race itself, they come to see racers crash into each other (what's wrong with our generation…). After this realisation, Roger decided to hold a different kind of "races": he hired... | import numpy as np
from numba import njit
i8 = np.int64
@njit
def solve(a, b, t, K, N):
t1 = t // K
d = t % K * 2
# b が a から a + d の位置にあれば衝突する
x = 0
y = 0
ans = 0
for c in a:
while b[x] < c:
x += 1
while b[y] <= c + d:
y += 1
... | |
APPS_491 | Guddu was participating in a programming contest. He only had one problem left when his mother called him for dinner. Guddu is well aware how angry his mother could get if he was late for dinner and he did not want to sleep on an empty stomach, so he had to leave that last problem to you. Can you solve it on his behalf... | import itertools
from collections import defaultdict as dfd
def sumPairs(arr, n):
s = 0
for i in range(n-1,-1,-1):
s += i*arr[i]-(n-1-i)*arr[i]
return s
def subarrayXor(arr, n, m):
ans = 0
xorArr =[0 for _ in range(n)]
mp = dfd(list)
xorArr[0] = arr[0]
for i in range(1, n):
xorArr[i] = xorArr[i - 1] ^ ar... | |
APPS_492 | Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they went to a fair where Oliver bought some square shaped marshmallows and Nova bought so... | import math
def lcm(a, b):
return (a*b)//gcd(a, b)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
for _ in range(int(input())):
n = int(input())
na = math.ceil((2*n)/math.acos(-1))
nb = ((n+1)//2)**2
nlcm = lcm(na, nb)
oa = math.ceil(n/2)
ob = (n//2)*(n//... | |
APPS_493 | There are $5$ cities in the country.
The map of the country is given below.
The tour starts from the red city.
Each road is associated with a character.
Initially, there is an empty string.
Every time a road has been travelled the character associated gets appended to the string.
At the green city either the string ca... | for _ in range(int(input())):
s=input()
if len(s)<4:
print("NO")
else:
if s[-4:]=="1000":
print("YES")
else:
print("NO") | |
APPS_494 | Chef has a natural number N. Cheffina challenges chef to check whether the given number is divisible by the sum of its digits or not. If the given number is divisible then print "Yes" else "No".
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case cont... | import sys,io,os,math
from math import ceil,log,gcd,inf
from itertools import permutations
mod=1000000007
mod1=998244353
def printlist(n):
sys.stdout.write(" ".join(map(str,n)) + "\n")
printf=lambda n:sys.stdout.write(str(n)+"\n")
def printns(n):
sys.stdout.write(str(n))
def intinp():
return int(sys.stdi... | |
APPS_495 | Problem description.
This problem is simple and will introduce you to the Dynamic Programming.
You will be given an array and a key value.
You will have to find out the occurrences of the key value depending upon the query using Brute Force and Top Down Dynamic Programming.
-----Brute-Force: -----
You will check th... | for __ in range(eval(input())):
x = eval(input())
a = list(map(int,input().split()))
key = eval(input())
query = eval(input())
maxvisited = x #maximum visted value
j = x-1
ans = []
val = 0
while j>=0:
if a[j]==key:
ans.append(val+1)
val = val +1
... | |
APPS_496 | Taru likes reading. Every month he gets a copy of the magazine "BIT". The magazine contains information about the latest advancements in technology. Taru
reads the book at night and writes the page number to which he has read on a piece of paper so that he can continue from there the next day. But sometimes
the pa... | import sys
rl=sys.stdin.readline
T=int(rl())
for t in range(T):
P=int(rl())
T=(P+1)//2
F=list(map(int,rl().split()))[1:]
numtorn=int(rl())
t=sum(range(1,P+1))-sum(F)
K=T-numtorn
print('%.4f' % (t*K/float(T)))
| |
APPS_497 | Toby has found a game to entertain himself.The game is like this:
You are in a coordinate system initially at (0,0) and you are given a sequence of steps which lead to your destination.The steps are given in the form of directions: ’U’ ,’D’ , ’L’ and ‘R’ for up, down, left and right respectively.If you are at position... | from collections import Counter
try:
for _ in range(int(input())):
n=int(input())
s=input()
d1=dict(Counter(s))
u,d,r,l=0,0,0,0
if 'U' in d1:
u=d1['U']
else:
u=0
if 'D' in d1:
d=d1['D']
else:
d=0
if 'R' in d1:
r=d1['R']
else:
r=0
if 'L' in d1:
l=d1['L']
else:
l=0
x=... | |
APPS_498 | Chefland has all the cities on a straight line. There are $N$ cities in Chefland numbered $1$ to $N$. City $i$ is located at coordinate $x_i$ on the x-axis. Guru wants to travel from city $A$ to city $B$. He starts at time t=0. He has following choices to travel.
- He can walk $1$ metre in $P$ secs.
- There is a train ... | t=int(input())
for _ in range(t):
n,a,b,c,d,p,q,y=list(map(int,input().split()))
l=list(map(int,input().split()))
ans = abs((l[b-1]-l[a-1]))*p
x=abs(l[c-1]-l[a-1])*p
if x<=y:
x=y+abs(l[d-1]-l[c-1])*q+abs(l[b-1]-l[d-1])*p
ans=min(ans,x)
print(ans)
| |
APPS_499 | Chef recently took a course in linear algebra and learned about linear combinations of vectors. Therefore, in order to test his intelligence, Raj gave him a "fuzzy" problem to solve.
A sequence of integers $B_1, B_2, \ldots, B_M$ generates an integer $K$ if it is possible to find a sequence of integers $C_1, C_2, \ldot... | import math
import bisect
from functools import reduce
from collections import defaultdict
# import sys
# input = sys.stdin.readline
def inn():
return int(input())
def inl():
return list(map(int, input().split()))
MOD = 10**9+7
INF = inf = 10**18+5
n = inn()
a = inl()
k = []
for q in range(inn()):
k.append(inn()... | |
APPS_500 | Two sisters, A and B, play the piano every day. During the day, they can play in any order. That is, A might play first and then B, or it could be B first and then A. But each one of them plays the piano exactly once per day. They maintain a common log, in which they write their name whenever they play.
You are given t... | def checkValidity(s):
count = 0
previous = ""
for x in s:
if count == 0:
previous = x
count += 1
elif count == 1:
count = 0
if previous == x:
return "no"
return "yes"
t = int(input())
for _ in range(t):
s = input()
print(checkValidity(s))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.