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.
For the sealing, there are M kinds of sticky stripes, which are sold in the shops. The stripe of the ith type has the length of Li millimeters and the cost of Ci rubles.
The sealing process consists in picking the stripe and sticking it on the border of the window. The stripe can't be cut (it is made of very lasting material) and can only be put straight, without foldings. It is not necessary to put the strip strictly on the window border, it can possibly extend outside the border side of window too (by any possible amount). The window is considered sealed up if every point on its' border is covered with at least one stripe.
Now Sergey is curious about the stripes he needs to buy. He wonders about the cheapest cost, at which he can seal his window. Please help him.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of number of vertices in the polygon denoting Sergey's window.
Each of the following N lines contains a pair of space-separated integer numbers Xi Yi, denoting the coordinates of the ith points.
The following line contains a single integer M denoting the number of types of sticky stripe which is sold in the shop.
Each of the following M lines contains a pair of space-separated integers Li Ci denoting the length and the cost of the sticky stripe of the ith type respectively.
-----Output-----
For each test case, output a single line containing the minimum cost of sealing up the window.
-----Constraints-----
- 1 ≤ T ≤ 10
- The coordinates of the window are given either in clockwise or in a counter-clockwise order.
- No three or more vertices lie on the same line (i.e. are collinear).
- 0 ≤ Xi, Yi ≤ 106
- 1 ≤ Li, Ci ≤ 106
-----Subtasks-----
- Subtask #1 (17 points): 3 ≤ N ≤ 10, M = 1
- Subtask #2 (24 points): 3 ≤ N ≤ 42, M ≤ 2
- Subtask #3 (59 points): 3 ≤ N ≤ 2000, 1 ≤ M ≤ 10
-----Example-----
Input:1
4
0 0
1000 0
1000 2000
0 2000
2
1000 10
2000 15
Output:50
-----Explanation-----
Example case 1. In this case, Sergey's window is a rectangle with the side lengths of 1000 and 2000. There are two types of the sticky stripes in the shop - the one of the length 1000 with the cost of 10 rubles and with the length of 2000 and the cost of 15 rubles. The optimal solution would be to buy 2 stripes of the first type 2 stripes of the second type. The cost will be 2 × 15 + 2 × 10 = 50 rubles.
|
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):
x,y = map(int,input().split())
if i == 0:
x0 = x
y0 = y
prevx = x
prevy = y
elif i == n-1:
sides.append(sqrt((prevx-x)**2 + (prevy-y)**2))
sides.append(sqrt((x0-x)**2 + (y0-y)**2))
else:
sides.append(sqrt((prevx-x)**2 + (prevy-y)**2))
prevx = x
prevy = y
m = int(input())
for j in range(m):
li,ci = map(int,input().split())
length.append(li)
cost.append(ci)
ans=0
#print(sides)
for k in sides:
ans= ans + knapsack(k,length,cost,m)
print(int(ans))
|
|
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 marked from 1,2,3,4…N.
Chef will go to that supermarket in which he gets to know that there is exactly 1 empty parking slot having number K that exactly divides the total number of slots (N) available in that supermarket.
The 1st and Nth parking slots are always occupied by the staff of every supermarket. Rest parking slots are empty as Chef is arriving early morning to the supermarket.
Now Chef needs your help in determining whether he can park his car in a supermarket or not!
Input
The first line contains the single integer N showing how many supermarkets are there for the chef to choose.
The next N lines contain a number ‘ai’ which represents the total parking slots available in ith supermarket.
Output
You need to output "YES" (without the quotes), if a supermarket can be reached by Chef, and "NO" (without the quotes), if it can't.
Constraints
1<=N<=10^5
1<=ai<=10^12
Sample Input :
2
4
5
Sample Output :
YES
NO
|
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):
return check(s)
return 0
N = int(input())
for t in range(N):
slots = int(input())
if (Solve(slots)):
print("YES")
else:
print("NO")
|
|
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 night guard. Each key can be used to unlock only one room. To reach one of the inner rooms, he has to unlock an adjacent room first.
Eg: If there are 5 rooms labelled: 1 2 3 4 5
Only Rooms 1 and 5 can be accessed initially. To unlock room 2, either room 1 or room 3 must be unlocked. Similarly to unlock Room 4, he must unlock room 5 or room 3 first.
Each room has some money in it. The money present in room i is given by A[i]. Using the k keys, calculate what is the maximum possible amount of money obtainable.
-----Input:-----
- First line will contain n, number of rooms.
- Second line will contain space separated integers, denoting A[i], money present in each room.
- Third line will contain an integer, k, the number of keys available.
-----Output:-----
Maximum money obtained.
-----Constraints-----
- 1 <= Number of Rooms <= 10^5
- 1 <= A[i] <= 10^4
- 1 <= k <= Number of Rooms
-----Subtasks-----
- 40 points : 1 <= Number of Rooms <= 100
- 60 points : Number of Rooms > 100
-----Sample Input:-----
7
1 2 3 4 5 6 1
3
-----Sample Output:-----
12
-----Explanation:-----
For the first step, Mr. Krabs can only unlock the room at the left corner or the right corner. If he unlocks the room in the right corner, he obtains 1 dollar. He can then go on to unlock the second last room and gain 6 dollars, for a total of 7 dollars. Finally he can unlock the third last room and get 5 dollars, for a total of 12 dollars.
This is the maximum amount of money he can get with only 3 keys.
|
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 score of each player is determined by
adding up the scores in all the rounds and the player with the higher
total score is declared the winner.
The Siruseri Sports Club organises an annual billiards game where
the top two players of Siruseri play against each other. The Manager
of Siruseri Sports Club decided to add his own twist to the game by
changing the rules for determining the winner. In his version, at the
end of each round, the cumulative score for each player is calculated, and the leader and her current lead are found. Once
all the rounds are over the player who had the maximum lead at the
end of any round in the game is declared the winner.
Consider the following score sheet for a game with 5 rounds:
RoundPlayer 1Player 2114082289134390110411210658890
The total scores of both players, the leader and the lead after
each round for this game is given below:RoundPlayer 1Player 2LeaderLead114082Player 1582229216Player 1133319326Player 274431432Player 215519522Player 23
Note that the above table contains the cumulative scores.
The winner of this game is Player 1 as he had the maximum lead (58
at the end of round 1) during the game.
Your task is to help the Manager find the winner and the winning
lead. You may assume that the scores will be such that there will
always be a single winner. That is, there are no ties.
Input
The first line of the input will contain a single integer N (N
≤ 10000) indicating the number of rounds in the game. Lines
2,3,...,N+1 describe the scores of the two players in the N rounds.
Line i+1 contains two integer Si and Ti, the scores of the Player 1
and 2 respectively, in round i. You may assume that 1 ≤ Si ≤
1000 and 1 ≤ Ti ≤ 1000.
Output
Your output must consist of a single line containing two integers
W and L, where W is 1 or 2 and indicates the winner and L is the
maximum lead attained by the winner.
Example
Input:
5
140 82
89 134
90 110
112 106
88 90
Output:
1 58
|
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('1', mlead1)
|
|
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$, his score gets multiplied by $k$
This month he gave $M$ questions and he is wondering what will be mean of maximum scores of all the student. He is busy in improving his finger print attendance module, can you help him?
Input file may be large so try to use fast input output
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a First line of input, two integers $N, M$ i.e. Number of students in the class and number of questions given in this month.
- Next $M$ lines contains 3 integers -$i, j, k$ i.e. starting roll number, end roll number and complexity of the question
-----Output:-----
For each testcase, output in a single line answer - $floor$ value of Mean of maximum possible score for all students.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N, M \leq 10^5$
- $1 \leq i \leq j \leq N$
- $1 \leq k \leq 100$
-----Subtasks-----
Subtask1
-
$1 \leq T \leq 10$
-
$1 \leq N, M \leq 10^4$
Subtask2
-
Original Constraints
-----Sample Input:-----
1
5 3
1 3 5
2 5 2
3 4 7
-----Sample Output:-----
202
-----EXPLANATION:-----
Initial score of students will be : $[10, 10, 10, 10, 10]$
after solving question 1 scores will be: $[50, 50, 50, 10, 10]$
after solving question 2 scores will be: $[50, 100, 100, 20, 20]$
after solving question 1 scores will be: $[50, 100, 700, 140, 20]$
Hence after all questions mean of maximum scores will $(50+100+700+140+20)/5 = 202$
|
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]
print(s//n)
except:
pass
|
|
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 X.
Now after performing the sequence of such operations you need to find the maximum element in the grid.
-----Input-----
The first line of the input contains two space separated integers N and Q denoting the size of the grid and the number of performed operations respectively. Each of the following Q lines describe an operation in the format described above.
-----Output-----
Output a single line containing the maximum number at the grid after performing all the operations.
-----Constraints-----
- 1 ≤ N ≤ 314159
- 1 ≤ Q ≤ 314159
- 1 ≤ X ≤ 3141
- 1 ≤ R, C ≤ N
-----Example-----
Input:
2 4
RowAdd 1 3
ColAdd 2 1
ColAdd 1 4
RowAdd 2 1
Output:
7
-----Explanation-----
The grid changes as follows:
00 33 34 74 74
00 00 01 41 52
The maximum number in the final grid is 7.
|
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 in range(n):
# for j in range(n):
# ar[i][j]=dr[i+1]+dc[j+1]
# if ar[i][j]>m:
# m=ar[i][j]
print(mer+mec)
|
|
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. Determine the minimum speed of panipuri seller so that no customer has to wait for panipuri after getting his/her first panipuri.
Assume that the plate can hold infinite panipuris, and customer starts eating next panipuri just after finishing the current one. You would be provided with the time taken by each customer to eat a panipuri.
Panpuri seller serves panipuri in round robin manner (first to last and then again first).
-----Input:-----
- First line will contain $T$, number of testcases. Then the test cases follow.
- For each test case, the first line contains $N$ number of customers.
- Then the second line will contain $N$ space separated integers, $A_1$ to $A_N$, eating time taken by each customer(in seconds).
-----Output:-----
- For each test case, print a single line containing the minimum integral speed of panipuri seller so that no customer has to wait.
-----Constraints-----
- $0 < T \leq 100$
- $0 < N \leq 10^6$
- $0 < A_i \leq 10^9$
- Sum of $N$ over all test cases does not exceed $10^6$
-----Sample Input:-----
2
4
2 4 6 3
5
2 3 4 6 5
-----Sample Output:-----
2
3
-----EXPLANATION:-----
$Test case$ $1$:
Let's assume speed of panipuri seller be 1.
So starting from $0^{th}$ second, in $0$ to $1$ second seller make a panipuri and put it into the plate of first customer, and first customer completely eat it in $1$ to $3$ second as he takes $2$ second to eat a panipuri. But in $3$ to $4$ second panipuri seller is serving to $4^{th}$ customer, and hence first customer have to wait, so 1 cannot be our answer.
Next possible speed can be $2$ .
Starting from $0^{th}$ second, at half second seller make a panipuri and put it into the plate of first customer, first customer completely eat it on $2.5$ second as he takes $2$ second to eat a panipuri. In $0.5$ to $1$ second, seller serve the second customer. similarly in $1$ to $2$ second $3^{rd}$ and $4^{th}$ customer will be serve, in $2$ to $2.5$ second, seller will again serve the first customer so at $2.5$ sec $1^{st}$ customer will have a panipuri to eat.
Similarly proceeding further we will find that no customer have to wait when speed is $2$.
|
# 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 craft into minimum number of smaller crafts possible.
-----Input-----
A single integer N denoting the side length of the big hoverboard.
-----Output-----
In the first line, output the integer 'k' which is the minimum number of square boards into which the bigger board can be split up.
In the second line, output k space separated integers which denote the sizes of the smaller square hoverboards.This must be in increasing order of sizes.
-----Constraints-----
N ranges from 2 to 50.
-----Example-----
Input:
3
Output:
6
1 1 1 1 1 2
-----Explanation-----
A square of side length 3 can be split into smaller squares in two ways: Either into 9 squares of side1 or 5 squares of side 1 and 1 square of size 2.The second case is the favourable one.
|
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 number of times (including zero): append the digit $d$ to the decimal representation of $N$ ($d$ becomes the least significant digit of $N$), then remove one occurrence of one digit from the decimal representation of $N$.
Chef has already changed a lot of numbers and he got bored. Now, he wants to know the smallest possible value of $N$ which can be obtained by performing the operation described above. Can you help him?
-----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 and only line of each test case contains two space-separated integers $N$ and $d$.
-----Output-----
For each test case, print a single line containing one integer - the minimum number Chef can obtain.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^{18}$
- $N$ does not contain the digit $0$
- $1 \le d \le 9$
-----Subtasks-----
Subtask #1 (40 points):
- $1 \le T \le 100$
- $1 \le N \le 10^9$
Subtask #2 (60 points): original constraints
-----Example Input-----
3
35 4
42 4
24 9
-----Example Output-----
34
24
24
-----Explanation-----
Example case 1: Chef can remove the digit $5$ and add $4$ to the end of $N$. Then, $N$ becomes $34$.
Example case 2: Chef can remove the digit $4$ from the beginning of $N$, add $4$ to the end of $N$ and get $N = 24$.
Example case 3: Chef cannot make his number any smaller.
|
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, in array A = {5, 6, 7}. A group of subarrays could be the subarrays denoted by indices [1, 1], [2, 3]. The subarray corresponding to indices [1, 1] will be {5}. The subarray corresponding to indices [2, 3] will be {6, 7}. So, we have i1 = 1, j1 = 1, i2 = 2, j2 = 3 and K = 2. You can check that the indices satisfy the property i1 ≤ j1 < i2 ≤ j2.
Note that the group of subarrays [1, 2] and [2, 3] won't be disjoint, as it does not satisfy the property j1 < i2. In other words, the index 2 is common in two subarrays, which should not happen.
Let M denote the maximum value of K in a group of K disjoint subarrays of array A, such that there are not two elements (not indices) common in those subarrays. This means, that if the group contained subarrays [A[i1], A[j1], [A[i2], A[j2]] , ..., A[[iK, jK]], then there should not be an element which is present in more than one subarrays.
You have to find maximum number of group of disjoint subarrays that number of subarrays in those groups are equal to M. As the answer could be large, output it modulo 109 + 7.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of the each test case contains a single integer N denoting number of elements in array A.
Second line of each test case contains N space separated integers denoting the elements of the array A
-----Output-----
For each test case, output a single line corresponding to maximum number of group of disjoint subarrays of array A.
-----Constraints-----
- 1 ≤ T, N ≤ 105
- 1 ≤ Ai ≤ n
- Sum of N over all the test cases in a single file won't exceed 105
-----Subtasks-----
Subtask #1 (30 points)
- 1 ≤ T, N ≤ 103
- 1 ≤ Ai ≤ n
- Sum of N over all the test cases in a single file won't exceed 103
Subtask #2 (70 points)
- original constraints
-----Example-----
Input
3
2
3 4
3
1 2 2
5
1 1 2 2 2
Output:
1
3
18
-----Explanation-----
Example case 1. M will be equal to 2. The subarrays will be {[1, 1], [2, 2]}.
Example case 2. M will be equal to 3. The subarrays will be {[1, 1], [2, 2]}, {[1, 1], [3, 3]} and {[1, 1], [2, 3]}. Note that {[2, 2], [3, 3]} won't be a non-intersecting subarray as A[2] = 2 and A[3] = 2. So, 2 is common in both these subarrays.
|
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:
m[l[i-1]]+=(count*(count+1))/2
count=1
if(l[n-1]) not in m:
m[l[n-1]]=(count*(count+1))/2
else:
m[l[n-1]]+=(count*(count+1))/2
s=1
for x in m:
s=(s*m[x])%(1000000007)
print(s)
|
|
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, j ≤ N, i < j implies Di < Dj
Everyday, Anmol chooses a pole Pi to start running from. He keeps on running until he reaches Pi+K. Whenever he reaches a pole (other than the starting pole), he records the distance traveled since the last pole.
You are given the distances recorded by him today. Your task is to find the number of distinct values of i such that i + K ≤ N and if he starts at Pi and end at Pi+K, he would end up having exactly the same record of distances (in the same order).
-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
- The first line of each test case contains two space separated integers N and K.
- The next line contains N space separated integers D1, D2,..., DN.
- The next line contains K space separated integers representing the distances recorded by Anmol in the same order.
.
-----Output-----
- For each test case, output a single line containing the answer for that test case.
-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 5 x 104
- 1 ≤ K < N
- 1 ≤ Di ≤ 106
-----Subtasks-----
-----Subtask #1 (20 points)-----
- 1 ≤ N ≤ 1000
-----Subtask #2 (80 points)-----
- Original constraints
-----Example-----
Input:
3
5 1
1 5 10 12 14
5
5 2
5 8 13 16 21
3 5
5 3
2 6 8 11 16
2 3 5
Output:
1
2
1
-----Explanation-----
Example case 1. If he runs from P2 to P3, he will record (5)
Example case 2. He can start at P1 or P3
Example case 3. He can start at P2
|
#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+=1
j = lps[j-1]
elif i < N and pattern[j] != string[i]:
if j != 0:
j = lps[j-1]
else:
i+=1
def LPSCompute(pattern, M, lps):
len = 0
lps[0]
i = 1
while i < M:
if pattern[i]==pattern[len]:
len+=1
lps[i] = len
i+=1
else:
if len!=0:
len = lps[len-1]
else:
lps[i] = 0
i+=1
for _ in range(int(input())):
n,k=list(map(int,input().split()))
s=list(map(int,input().split()))
pattern=list(map(int,input().split()))
ans=0
string=[]
for i in range(n-1):
string.append(s[i+1]-s[i])
KMPMatch(pattern, string)
print(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 zero-indexed from left to right.
To find the character value she uses the mapping {'a': 0, 'b':1, 'c':2 ……. 'y': 24, 'z':25} .
For example, for string $abcde$ Characters at prime positions are $'c'$ and $'d'$. c + d = 2 + 3 = 5. Since, 5 is a prime number, the string is $nice$.
Since there could be many nice strings print the answer modulo $10^{9}+7$.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, the string $S$.
-----Output:-----
For each testcase, output in a single line number of nice strings modulo $10^{9}+7$.
-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq |S| \leq 10^2$
String $S$ contains only lowercase letters.
-----Sample Input:-----
1
abc
-----Sample Output:-----
10
|
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
while p <= n:
if U[p]:
P += [p]
x = p
while x <= n:
U[x] = 0
x += p
p += 1
return P
def solve():
S = R(str).strip()
X = [ord(c)-ord('a') for c in S]
P = primes(10000)
L = defaultdict(lambda : 0)
s = 0
for i in range(len(S)):
p = i in P
NL = defaultdict(lambda : 0)
for a in range(26):
for l in L:
NL[l + a * p] += L[l]
for a in range(X[i]):
NL[s + a * p] += 1
s += X[i] * p
L = NL
L[s] += 1
r = 0
for p in P:
r += L[p]
print(r % MOD)
T = R()
for t in range(1, T + 1):
solve()
|
|
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 a friend of $C_i$ then $A_i$ is also a friend of $C_i$.
Find number of ways in which two students can be selected in such a way that they are not friends.
-----Input:-----
- First line will contain two integers $N$ and $M$.
- Then $M$ lines follow. Each line contains two integers $A_i$ and $B_i$ denoting the students who are friends.
-----Output:-----
For each testcase, output the number of ways in which two students can be selected in such a way that they are friends.
-----Constraints-----
- $2 \leq N \leq 200000$
- $0 \leq M \leq 200000$
- $1 \leq A_i,B_i \leq N$
-----Sample Input:-----
5 3
1 2
3 4
1 5
-----Sample Output:-----
6
-----EXPLANATION:-----
Groups of friend are $[1,2,5]$ and $[3,4]$.Hence the answer is 3 X 2 =6.
|
# 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,m=list(map(int,input().split()))
for i in range(n+1):
d[i]=[]
for _ in range(m):
a,b=list(map(int,input().split()))
d[a].append(b)
d[b].append(a)
v=[]
for i in range(n+1):
v.append(-1)
c=0
p=[]
for i in range(1,n+1):
if v[i]==-1:
c+=1
p.append(dfs(i))
an=0
s=0
for i in range(c):
s+=p[i]
an+=p[i]*(n-s)
print(an)
|
|
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 distinct Pi's, which, when treated as a number is magical.
Two arrangements are said to be distinct, if there is atleast one index where they differ.
As the sum can be very large, print the sum modulo 109+7$10^{9}+7$.
-----Input:-----
-The first line of the input contains a single integer T$T$ denoting the number of test cases.
-Only line of each test case contains a string S$S$ of length N$N$, consisting only of digits between 0 to 9.
-----Output:-----
For each test case, print a single integer denoting the sum of all such magical Pi′s$Pi's$ modulo 109+7$10^{9}+7$.
If no such Pi$Pi$ exists print "-1".
-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 2≤N≤1000$2 \leq N \leq 1000$
- String only consists of digits between 0 to 9, both inclusive.
-----Subtasks-----
- 10 points : 1≤N≤5$1 \leq N \leq 5$
- 40 points : 1≤N≤100$1 \leq N \leq 100$
- 50 points : Original Constraints
-----Sample Input:-----
2
35566
31
-----Sample Output:-----
65536
-1
-----EXPLANATION:-----
Only arrangement is 65536.
No arrangement of 31 gives us a power of two.
|
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 = (res + pow(2, p, MOD)) % MOD
print(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 plants of the same height.
-----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 a single integer $N$.
- The second line contains $N$ space separated integers $A_1,A_2,..A_N$.
-----Output:-----
For each test case print a single line containing one integer, the minimum number of integer hours that Chef must wait to have two plants of the same height.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^5$
- $0\leq A_i \leq 10^{18}$
- $A_i >A_{i+1}$, for each valid $i$
- The Sum of $N$ over all test cases does not exceed $10^6$
-----Sample Input:-----
1
3
8 4 2
-----Sample Output:-----
2
-----EXPLANATION:-----
After $2$ hours there are two plants with the same height.
$[8,4,2] \rightarrow [9,6,5] \rightarrow [10,8,8]$.
|
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 strip is is Ni, then there will be Ni integers, Hi1, Hi2, .. HiNi, which represent the heights of the ground at various parts of the strip, in sequential order. That is, the strip has been divided into Ni parts and the height of each part is given. This strip is valid, if and only if all these conditions are satisfied:
- There should be an unique 'centre' part. This is where the actual temple will be built. By centre, we mean that there should be an equal number of parts to the left of this part, and to the right of this part.
- Hi1 = 1
- The heights keep increasing by exactly 1, as you move from the leftmost part, to the centre part.
- The heights should keep decreasing by exactly 1, as you move from the centre part to the rightmost part. Note that this means that HiNi should also be 1.
Your job is to look at every strip and find if it's valid or not.
-----Input-----
- The first line contains a single integer, S, which is the number of strips you need to look at. The description of each of the S strips follows
- The first line of the i-th strip's description will contain a single integer: Ni, which is the length and number of parts into which it has been divided.
- The next line contains Ni integers: Hi1, Hi2, .., HiNi. These represent the heights of the various parts in the i-th strip.
-----Output-----
- For each strip, in a new line, output "yes" if is a valid strip, and "no", if it isn't.
-----Constraints-----
- 1 ≤ S ≤ 100
- 3 ≤ Ni ≤ 100
- 1 ≤ Hij ≤ 100
-----Example-----
Input:
7
5
1 2 3 2 1
7
2 3 4 5 4 3 2
5
1 2 3 4 3
5
1 3 5 3 1
7
1 2 3 4 3 2 1
4
1 2 3 2
4
1 2 2 1
Output:
yes
no
no
no
yes
no
no
-----Explanation-----
In the first strip, all the conditions are satisfied, hence it is valid.
In the second strip, it does not start with a 1, and hence is invalid.
In the third strip, it keeps increasing even past the centre, instead of decreasing. Hence invalid.
The fourth strip does not increase and decrease by exactly 1. Hence invalid.
The fifth satisfies all conditions and hence is valid.
The sixth and seventh strip do not have a 'centre' part. Because for every part, there are either more parts to its right than its left, or more parts on its left than its right. Hence both the strips are invalid.
|
# 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 family gets $K$ slices of cakes. Each family has a lucky number of $R$ and they agree to distribute the slices such that the member gets $R$ times more slices than the member just smaller than them. Since the family is busy in festival preparations, find out if the number of slices would be sufficient for the family or not. Also, find how many extra slices they have or how many slices are they short of.
Also, the locality is kind and believes in sharing. So, you also need to determine if each family would have sufficient slices if families shared their cakes among each other!
-----Input :-----
- First line of input will have a single integer $T$ i.e. the number of families in the locality
- For next $T$ lines, each line will describe one family through 4 integers i.e. $S$, $N$, $K$, $R$ separated by spaces
-----Output-----
- First $T$ lines of output will show if slices are enough for the family or not, followed by extra or required slices. For example, if slices are sufficient, the output would be $POSSIBLE$ $10$ which implies 10 slices are extra. If slices are insufficient, the output would be $IMPOSSIBLE$ $15$ which implies 15 slices are required to fulfill the requirement.
- Last line of output would be $IMPOSSIBLE$ or $POSSIBLE$ depending on whether each family would get enough slices after sharing.
-----Constraints:-----
- 1 ≤ $T$ ≤ 50
- 1 ≤ $N$ ≤ 15
- 1 ≤ $S$ ≤ 10^9
- 1 ≤ $K$ ≤ 5
- 1 ≤ $R$ ≤ 5
-----Sample Input:-----
5
100 4 2 2
100 4 3 2
100 4 3 3
200 4 4 2
10 3 2 2
-----Sample Output:-----
POSSIBLE 70
POSSIBLE 55
IMPOSSIBLE 20
POSSIBLE 140
IMPOSSIBLE 4
POSSIBLE
-----Explanation-----
For the first home, the youngest member has got 2 slices, the one older than them gets 2 times more slices, and so forth. So, first home needs 2 + 4 + 8 + 16 = 30 slices. But since they made 100, they have 70 extra, hence we print 'POSSIBLE 70'.
Doing the same for other houses, we find 20 + 4 = 24 slices extra are required so that all families have enough slices. In this case we have 70 + 55 + 140 = 265 extra slices which is > 24, so we print 'POSSIBLE' in last line.
|
# 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:
less += total-sli
print('IMPOSSIBLE',total-sli)
if extra >= less:
print('POSSIBLE')
else:
print('IMPOSSIBLE')
|
|
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 simple :)
By the way, because of this the answer could be quite large. Hence you should output it modulo 109 + 7. That is you need to find the remainder of the division of the number of required triples by 109 + 7.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains three space-separated integers N1, N2, N3.
-----Output-----
For each test case, output a single line containing the number of required triples modulo 109 + 7.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ Ni ≤ 1018
-----Example-----
Input:
5
3 3 3
2 4 2
1 2 3
25 12 2012
1 1 2013
Output:
6
4
1
578880
0
-----Explanation-----
Example case 1. We have the following triples composed of different numbers up to 3:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Example case 2. Here the triples are:
(1, 3, 2)
(1, 4, 2)
(2, 3, 1)
(2, 4, 1)
Example case 3. Here the only triple is (1, 2, 3).
Example case 4. Merry Christmas!
Example case 5. ... and Happy New Year! By the way here the answer is zero since the only choice for X1 and for is X2 is 1, so any such triple will have equal numbers.
|
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.
Chef wants to construct a string of length N that is a palindrome and has a period P. It's guaranteed that N is divisible by P. This string can only contain character 'a' or 'b'. Chef doesn't like the strings that contain all a's or all b's.
Given the values of N, P, can you construct one such palindromic string that Chef likes? If it's impossible to do so, output "impossible" (without quotes)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The only line of each test case contains two space separated integers N, P.
-----Output-----
For each test case, output a single line containing the answer of the problem, i.e. the valid string if it exists otherwise "impossible" (without quotes). If there are more than possible answers, you can output any.
-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ P, N ≤ 105
-----Subtasks-----
- Subtask #1 (25 points) : P = N
- Subtask #2 (75 points) : No additional constraints
-----Example-----
Input
5
3 1
2 2
3 3
4 4
6 3
Output
impossible
impossible
aba
abba
abaaba
-----Explanation-----
Example 1: The only strings possible are either aaa or bbb, which Chef doesn't like. So, the answer is impossible.
Example 2: There are four possible strings, aa, ab, ba, bb. Only aa and bb are palindromic, but Chef doesn't like these strings. Hence, the answer is impossible.
Example 4: The string abba is a palindrome and has a period of 4.
Example 5: The string abaaba is a palindrome and has a period of length 3.
|
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"
r=""
s=n//m
for e in l:
r=r+e
print(r*s)
|
|
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 (153 is an Armstrong number)
1634 = 1^4 + 6^4 + 3^4 + 4^4 (1634 is an Armstrong number)
As a love guru of chef you have to help chef to find Armstrong numbers Among the numbers which chef has initially so that Chefina feels good
-----Input:-----
First line will contain a positive Integer $T$ which is the number of testcases
Next $T$ lines follows an Integer $N$.
-----Output:-----
For Every n You have to print "FEELS GOOD" without qoutes if it is an armstrong number otherwise Print "FEELS BAD" without quotes
-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq N \leq 10^6$
-----Sample Input:-----
3
153
11
1634
-----Sample Output:-----
FEELS GOOD
FEELS BAD
FEELS GOOD
-----EXPLANATION:-----
For test case 1 --> 153 = 1^3 + 5^3 + 3^3 (153 is an armstrong number)
|
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 to check whether the given
# number is Armstrong number or not
def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0
while (temp != 0):
r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10
# If condition satisfies
return (sum1 == x)
# Driver code
for _ in range(int(input())):
num = int(input())
if isArmstrong(num):
print("FEELS GOOD")
else:
print("FEELS BAD")
|
|
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 of the cooks took care of some of the jobs before they left so only a subset of the n jobs remain. The Chef and his assistant divide up the remaining jobs in the following manner. The Chef takes the unfinished job with least index, the assistant takes the unfinished job with the second least index, the Chef takes the unfinished job with the third least index, etc. That is, if the unfinished jobs were listed in increasing order of their index then the Chef would take every other one starting with the first job in the list and the assistant would take every other one starting with the second job on in the list.
The cooks logged which jobs they finished before they left. Unfortunately, these jobs were not recorded in any particular order. Given an unsorted list
of finished jobs, you are to determine which jobs the Chef must complete and which jobs his assitant must complete before closing the kitchen for the
evening.
-----Input-----
The first line contains a single integer T ≤ 50 indicating the number of test cases to follow. Each test case consists of two lines. The first line contains two numbers n,m satisfying 0 ≤ m ≤ n ≤ 1000. Here, n is the total number of jobs that must be completed before closing and m is the number of jobs that have already been completed. The second line contains a list of m distinct integers between 1 and n. These are the indices of the jobs that have already been completed. Consecutive integers are separated by a single space.
-----Output-----
The output for each test case consists of two lines. The first line is a list of the indices of the jobs assigned to the Chef. The second line is a list of the indices of the jobs assigned to his assistant. Both lists must appear in increasing order of indices and consecutive integers should be separated by a single space. If either the Chef or the assistant is not assigned any jobs, then their corresponding line should be blank.
-----Example-----
Input:
3
6 3
2 4 1
3 2
3 2
8 2
3 8
Output:
3 6
5
1
1 4 6
2 5 7
|
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(jobs[i]))
print(' '.join(chef))
print(' '.join(ass))
|
|
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 layers of such a tree:
Let's consider four operations that you are allowed to apply during the tree traversal:
- move to the left child - move from $v$ to $2 \cdot v$
- move to the right child - move from $v$ to $2 \cdot v + 1$
- move to the parent as a left child - move from $v$ to $\frac{v}{2}$ if $v$ is an even integer
- move to the parent as a right child - move from $v$ to $\frac{v - 1}{2}$ if $v$ is an odd integer
It can be proven, that for any pair of nodes $u$ and $v$, there is only one sequence of commands that moves from $u$ to $v$ and visits each node of the tree at most once. Let's call such a sequence of commands a path configuration for a pair of nodes $(u, v)$.
You are asked to process a series of the following queries:
You are given three integers $n$, $u$ and $v$ ($1 \leq u, v \leq n$). Count the pairs of nodes $(w, t)$ ($1 \leq w, t \leq n$) such that the path configuration for $(w, t)$ is the same with the path configuration for $(u, v)$.
-----Input-----
- The first line of input contains a single integer $Q$, denoting the number of queries to process.
- Each of the next $Q$ lines contains three space-separated integers $n$, $u$ and $v$ denoting a query.
-----Output-----
For each query, print the answer on a separate line.
-----Constraints-----
- $1 \leq Q \leq 2 \cdot 10^4$
- $1 \leq u, v \leq n \leq 10^{9}$
-----Example Input-----
3
11 9 11
10 2 2
8 1 8
-----Example Output-----
2
10
1
-----Explanation-----
In the first query from the example test case, you should count pairs $(5, 7)$ and $(9, 11)$.
In the second query from the example test case, you should count the following pairs: $(1, 1)$, $(2, 2)$, $(3, 3)$, $(4, 4)$, $(5, 5)$, $(6, 6)$, $(7, 7)$, $(8, 8)$, $(9, 9)$ and $(10, 10)$.
In the third query from the example test case, you should only count a pair $(1, 8)$.
|
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 = max(len(a),len(b))
#print m;
zz = bin(n)[2:]
x= len(zz)
y = zz[:x-m]
f1 = y+a;
f2 = y+b;
ans = int(y,2)
if(int(f1,2)>n or int(f2,2)>n):
ans-=1;
print(ans)
|
|
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?"
Chefu is confused how to solve it. I hope you are not. Please solve this by finding a right angled triangle with hypotenuse H and area S. If it not possible to do so, then output -1.
-----Input-----
The first line of the input contains a single integer T denoting the number of test-cases. T test cases follow.
For each test case, there will be a single line containing two space separated integers H and S.
-----Output-----
Output the answer for each test-case in a single line. If it is not possible to find such a triangle, output -1. Otherwise print 3 real numbers corresponding to the lengths of the sides of the triangle sorted in non-decreasing order. Please note that the length of the triangle sides should not differ by more than 0.01 in absolute value from the correct lengths.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ H ≤ 106
- 1 ≤ S ≤ 1012
-----Example-----
Input:4
5 6
6 10
258303 89837245228
616153 77878145466
Output:3.00000 4.00000 5.00000
-1
-1
285168.817674 546189.769984 616153.000000
|
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:
print('{0:.6f}'.format(B),'{0:.6f}'.format(P),'{0:.6f}'.format(h))
t = t-1
|
|
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 and ending cells for each are given to you. Now consider a graph, where each cell in the 2d-grid is a vertex. And there is an edge between 2 vertices if and only if the cells corresponding to these two vertices are consecutive cells in at least one of the two snakes. That is, at least in one of the snakes, when you go from one end point to the other end point, these two cells should occur consecutively.
The two sightings/snakes are said to be same, if both these conditions are satisfied:
- The union of the set of cells in the first snake and the set of cells in the second snake, should form a connected component in this graph.
- No vertex should have degree more than 2 in the graph.
In other words, the induced subgraph on the union set must be a path graph.
-----Input-----
- The first line contains a single integer, T, which is the number of testcases. The description of each testcase follows.
- The first line of each testcase contains four integers: X11, Y11, X12, Y12. This represents the fact that the first snake's end points are (X11, Y11) and (X12, Y12).
- The second line of each testcase contains four integers: X21, Y21, X22, Y22. This represents the fact that the second snake's end points are (X21, Y21) and (X22, Y22).
-----Output-----
- For each testcase, output "yes" if the snakes are the same, as per the definition given above. Output "no" otherwise.
-----Constraints-----
- 1 ≤ T ≤ 105
- -109 ≤ Xij,Yij ≤ 109
- The two end points of every snake is guaranteed to be either on the same row or on the same column. Thus, the snake occupies all the cells between these cells, including the end points.
-----Example-----
Input:
4
2 1 8 1
11 1 7 1
2 1 8 1
11 1 9 1
2 1 8 1
3 1 3 -2
2 1 8 1
2 1 2 -2
Output:
yes
no
no
yes
-----Explanation-----
In the images, the first snake is red, the second snake is yellow, and the intersections, if any, are in orange.
The first test case corresponds to:
Both the conditions on the graph are satisfied, and hence this is a "yes".
The second test case corresponds to:
There is no edge between the vertex corresponding to the (8,1) cell and the vertex corresponding to (9,1), Hence, the union set is disconnected, and thus the answer is "no".
The third test case corresponds to:
The vertex corresponding to the cell (3,1) has degree 3, which is more than 2, and thus the answer is "no".
The fourth test case corresponds to:
Both the conditions on the graph are satisfied, and hence this is a "yes".
|
# 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=min(x1,x2)
b1=max(x3,x4);b2=min(x3,x4)
if a1>=b2 and a2<=b1:
print("yes")
else:
print("no")
elif (x1==x2)and(x1==x3)and(x1==x4):
a1=max(y1,y2);a2=min(y1,y2)
b1=max(y3,y4);b2=min(y3,y4)
if a1>=b2 and a2<=b1:
print("yes")
else:
print("no")
else:
print("no")
|
|
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 neighbourhood (i.e. from the street where he lives). There are N houses on the street in a single line (not considering the brother's house). He wants the party to be fun and he will not like to invite people who might spoil the mood of the party. If people are invited from three consecutive houses on the street, they might create trouble. As they say, three's a crowd! He doesn't want to ruin the Chef's Welcome Party and so he will not want to send invites to any three consecutive houses. He wants you to tell him how many ways are there for him to go wrong. Note that he can play safe by not inviting anyone to avoid a crowd.
-----Input:-----
First line of the input contains a single integer T, the number of test cases.
Each test case contains a line containing a single integer N described above.
-----Output:-----
For each test case output a single integer denoting the number of ways the brother can go wrong with planning the party.
The answer can get quite large. So output the total number of ways modulo 109+7.
-----Constraints:-----
1<=T<=10000
1<=N<=1015
-----Example:-----Input:
2
3
4
Output:
1
3
Explanation:
Case 1: The only way he can go wrong is by inviting all the houses.
Case 2: First way of getting wrong is by inviting houses (1,2,3). Second way to get wrong is by inviting houses (2,3,4). Third way of going wrong is by inviting all 4 houses i.e. (1,2,3,4).
|
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]
for _ in range(53):
p = powers[-1]
powers.append(mult(p ,p))
def pow2(e):
y = ident
i = 0
for p in powers:
if e & (1 << i):
y = mult(p, y)
i += 1
return y
t = eval(input())
for _ in range(t):
n = eval(input())
if n < 3:
print(0)
continue
r = pow(2, n, MOD)
b = pow2(n - 2)
# print(b)
r -= (4 * b[0][0]) % MOD
r -= (2 * b[1][0]) % MOD
r -= b[2][0]
r = (MOD + r) % MOD
print(r)
|
|
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 substring. You have to determine whether at least one of them is rich.
-----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 two space-separated integers $N$ and $Q$.
- The second line contains a single string $S$ with length $N$.
- Each of the next $Q$ lines contains two space-separated integers $L$ and $R$ describing a query.
-----Output-----
For each query, print a single line containing the string "YES" if the given substring contains a rich substring or "NO" if it does not contain any rich substring.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, Q \le 10^5$
- $1 \le L \le R \le N$
- $S$ contains only lowercase English letters
-----Example Input-----
1
10 2
helloworld
1 3
1 10
-----Example Output-----
NO
YES
|
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('NO')
continue
if (l[right-2]-l[left-1])>0:
print('YES')
else:
print('NO')
|
|
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
• The first line of the input contains a single integer T.
• The first and only line of each test case contain two integer N,P.
————————————————————————————————————————
OUTPUT
For each test case, print a single line containing one integer — the total number of good
pairs
————————————————————————————————————————
CONSTRAINTS
• 1 ≤ T≤ 50
• 2 ≤ N,P ≤10^5
—————————————————————————————————————
Example Input
2
2 3
3 3
————————————————————————————————————————
Example Output
1
1
|
# 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 a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000
-----Example-----
Input
3
12345
31203
2123
Output
15
9
8
|
# 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 become sick), while Bob can eat at most B candies in total.
Who will win the game?
Print "Limak" or "Bob" accordingly.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains two integers A and B denoting the maximum possible number of candies Limak can eat and the maximum possible number of candies Bob can eat respectively.
-----Output-----
For each test case, output a single line containing one string — the name of the winner ("Limak" or "Bob" without the quotes).
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A, B ≤ 1000
-----Example-----
Input:
10
3 2
4 2
1 1
1 2
1 3
9 3
9 11
9 12
9 1000
8 11
Output:
Bob
Limak
Limak
Bob
Bob
Limak
Limak
Bob
Bob
Bob
-----Explanation-----
Test case 1. We have A = 3 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies. Then Limak is supposed to eat 3 candies but that would mean 1 + 3 = 4 candies in total. It's impossible because he can eat at most A candies, so he loses. Bob wins, and so we print "Bob".
Test case 2. Now we have A = 4 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies, then Limak eats 3 candies (he has 1 + 3 = 4 candies in total, which is allowed because it doesn't exceed A). Now Bob should eat 4 candies but he can't eat even a single one (he already ate 2 candies). Bob loses and Limak is the winner.
Test case 8. We have A = 9 and B = 12. The game looks as follows:
- Limak eats 1 candy.
- Bob eats 2 candies.
- Limak eats 3 candies (4 in total).
- Bob eats 4 candies (6 in total).
- Limak eats 5 candies (9 in total).
- Bob eats 6 candies (12 in total).
- Limak is supposed to eat 7 candies but he can't — that would exceed A. Bob wins.
|
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 eating % 2 == 0 and bobEat <= bobMax:
bobEat += eating
eating += 1
if bobEat > bobMax:
print("Limak")
break
|
|
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; restaurants do not have to lie on the roads. The slope of each road must be $1$ or $-1$, i.e. for any two points $(x_1, y_1)$ and $(x_2, y_2)$ on the same road, $|x_1-x_2| = |y_1-y_2|$ must hold.
Let's denote the minimum distance Chef has to walk from restaurant $i$ to reach a road by $D_i$. Then, let's denote $a = \mathrm{max}\,(D_1, D_2, \ldots, D_N)$; Chef wants this distance to be minimum possible.
Chef is a busy person, so he decided to give you the job of building the roads. You should find a way to build them that minimises $a$ and compute $a \cdot \sqrt{2}$.
-----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 a single integer $N$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $Y_i$.
-----Output-----
For each test case, print a single line containing one real number — the minimum distance $a$ multiplied by $\sqrt{2}$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.
-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 10^4$
- $|X_i|, |Y_i| \le 10^9$ for each valid $i$
-----Subtasks-----
Subtask #1 (10 points):
- $1 \le T \le 10$
- $2 \le N \le 5$
- $|X_i|, |Y_i| \le 10$ for each valid $i$
- $a \cdot \sqrt{2}$ is an integer
Subtask #2 (90 points): original constraints
-----Example Input-----
2
3
0 0
0 1
0 -1
3
0 1
1 0
-1 0
-----Example Output-----
0.5
0
-----Explanation-----
Example case 1: We should build roads described by equations $y-x+0.5 = 0$ and $y-x-0.5 = 0$.
Example case 2: We should build roads described by equations $y-x-1 = 0$ and $y+x-1 = 0$.
|
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 range(n):
x,y=rinput()
p.append(x+y)
mi.append(x-y)
p.sort()
mi.sort()
m=float('inf')
for i in range(1,n):
if(p[i]-p[i-1]<m):
m=p[i]-p[i-1]
if(mi[i]-mi[i-1]<m):
m=mi[i]-mi[i-1]
if m%2==0:
print(m//2)
else:
print(m/2)
|
|
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 (either to the left or to the right) by a distance of at most K. Find the maximum possible area of intersections of all these three squares that you can achieve. That is, the maximum area of the region which is part of all the three squares in the final configuration.
-----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 two space-separated integers a, K denoting side length of the squares, and the maximum distance that you can move the center of any square.
- The second line contains three space separated integers x1, x2, x3
-----Output-----
For each test case, output a real number corresponding to the maximum area of the intersection of the three squares that you can obtain. Your answer will be considered correct if it has an absolute error of less than or equal to 10-2.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ a ≤ 105
- 0 ≤ K ≤ 106
- -106 ≤ x1, x2, x3 ≤ 106
-----Example-----
Input
3
1 0
1 2 3
1 1
1 2 3
1 1
1 4 6
Output
0.000000
1.0000
0.0
-----Explanation-----
Testcase 1: The figure below shows the three squares:
Since K = 0, they cannot be moved, and since there is no region which belongs to all three squares, the answer is 0.
Testcase 2: The starting configuration is the same as above, but now each of the squares can move 1 unit. So we can move the first square 1 unit to the right and the third square one unit to the left, and have all the three squares at x-coordinate = 2. Thus the entire square is part of all three squares, and the answer is 1.
|
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 and initializing an integer, in C/C++, you can't do something like:
int = x ;4
as the semantics of such statement is incorrect, as we all know that the datatype must precede an identifier and only afterwards should come the equal sign and the initialization value, so, the corrected statement should be:
int x = 4;
Today, Lira is concerned with an abstract instruction which is composed of the characters "<" and ">" , which she will use on the design of her language, L++ :D.
She is using it as an abstraction for generating XML code Tags in an easier fashion and she understood that, for an expression to be valid, a "<" symbol must always have a corresponding ">" character somewhere (not necessary immediately) after it. Moreover, each ">" symbol should correspond to exactly one "<" symbol.
So, for instance, the instructions:
<<>>
<>
<><>
are all valid. While:
>>
><><
are not.
Given some expressions which represent some instructions to be analyzed by Lira's compiler, you should tell the length of the longest prefix of each of these expressions that is valid, or 0 if there's no such a prefix.
-----Input-----
Input will consist of an integer T denoting the number of test cases to follow.
Then, T strings follow, each on a single line, representing a possible expression in L++.
-----Output-----
For each expression you should output the length of the longest prefix that is valid or 0 if there's no such a prefix.
-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ The length of a single expression ≤ 106
- The total size all the input expressions is no more than 5*106
-----Example-----
Input:
3
<<>>
><
<>>>
Output:
4
0
2
|
# 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
else:
st.append('<')
print(ans)
|
|
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$, $\mathop{\mathrm{digitsum}}(100)=1+0+0=1$, $\mathop{\mathrm{digitsum}}(365)=3+6+5=14$.
You may perform any number of operations (including zero) in any order. Please find the minimum obtainable value of $N$ and the minimum number of operations required to obtain this value.
-----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 and only line of each test case contains two space-separated integers $N$ and $D$.
-----Output-----
For each test case, print a single line containing two space-separated integers — the minimum value of $N$ and the minimum required number of operations.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, D \le 10^{10}$
-----Subtasks-----
Subtask #1 (30 points): $1 \le N, D \le 100$
Subtask #2 (70 points): original constraints
-----Example Input-----
3
2 1
9 3
11 13
-----Example Output-----
1 9
3 2
1 4
-----Explanation-----
Example case 1: The value $N=1$ can be achieved by 8 successive "add" operations (changing $N$ to $10$) and one "digit-sum" operation.
Example case 2: You can prove that you cannot obtain $N=1$ and $N=2$, and you can obtain $N=3$.
The value $N=3$ can be achieved by one "add" and one "digitsum" operation, changing $9$ to $12$ and $12$ to $3$.
Example case 3: $N=1$ can be achieved by operations "add", "add", "digitsum", "digitsum": $11 \rightarrow 24 \rightarrow 37 \rightarrow 10 \rightarrow 1$.
|
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 range(0,len(num)):
temp=temp+int(num[i])
num=temp
return (num)
while(T):
queue=deque()
count_n=0
count_d=0
T=T-1
N,d=[i for i in input().split()]
n,count_n=break_down(N)
D,count_D=break_down(d)
dic={}
if(D==1 or D==2 or D==4 or D==5 or D==7 or D==8):
mini=1
elif(D==3 or D==6):
mini=min(digit_sum(str(n+3)),digit_sum(str(n+6)),digit_sum(str(n+9)))
else:
mini=n
queue.append((int(N),0))
ele=int(N)
count=0
while(len(queue)!=0):
ele,count=queue.popleft()
if(ele==mini):
break
else:
if(len(str(ele))==1):
temp1=ele+int(d)
queue.append((temp1,count+1))
else:
temp2=digit_sum(str(ele))
temp1=ele+int(d)
queue.append((temp2,count+1))
queue.append((temp1,count+1))
print(ele,count)
|
|
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 of N straight cuts among all the pizzas. Each pizza is also of different size and to avoid the slices getting too small the chef can only make a max of Ai cuts to the ith pizza. He wants to maximize the number of slices of pizza. Since chef is busy with preparing other aspects of the party he wants you to find out the maximum number of slices he can get following the constraints.
If a pizza is not cut at all then it is considered as 1 slice.
-----Input-----
First line contains two integers M and N.
The second line of input contains the array A.
-----Output-----
Output a single integer - the maximum number of slices chef can get.
-----Constraints-----
- 1 ≤ M ≤ 2*105
- 1 ≤ N,Ai ≤ 2*105
-----Subtasks-----
- Subtask 1: 1 ≤ M,N ≤ 100 - 10 points
- Subtask 2: 1 ≤ N ≤ 100,
1 ≤ M ≤ 105 - 20 points
- Subtask 3: Original Constraints - 70 points
-----Example-----
Input:
5 10
1 2 3 4 5
Output:
31
-----Explanation-----
Example case 1. One of the optimal way to cut would be to do {0, 1, 0, 4, 5} cuts.
|
# 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):
print(ans+q-m+(n*(n+1))//2)
else:
print(ans)
|
|
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 contains three angles A, B and C, of the triangle separated by space.
-----Output-----
For each test case, display 'YES' if the triangle is valid, and 'NO', if it is not, in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A,B,C ≤ 180
-----Example-----
Input
3
40 40 100
45 45 90
180 1 1
Output
YES
YES
NO
|
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 give any user exbook login link using this site and when anyone login into exbook using your link ,you can see his/her password .
But I made a mistake and so you cannot find original password in your portal . The portal showing you by adding two in every digit . So , now you have to find out the original password of an user if I give you the password which is showing in your portal .
-----Input:-----
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n which is showing in your portal . Mind it , every digit of n is greater than one .
-----Output:-----
Print , original password of user .
-----Sample Input:-----
2
3527
47269
-----Sample Output:-----
1305
25047
|
# 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 numbers
-----Output-----
Output a single integer answering what is asked in the problem.
-----Subtask 1 (20 points)-----
- 1 ≤ N ≤ 5000
- 1 ≤ A[i] ≤ 2*(10^9)
-----Subtask 2 (80 points)-----
- 1 ≤ N ≤ 1000000
- 1 ≤ A[i] ≤ 2*(10^9)
-----Example-----
Input:
2
1
2
Output:
1
-----Explanation-----
There will be four values, A[0]%A[0] = 0, A[0]%A[1]=1, A[1]%A[0]=0, A[1]%A[1]=0, and hence the output will be the maximum among them all, that is 1.
|
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 following condition:
The substring should start with 0 and end with 1 or the substring should start with 1 and end with 0 but not start with 0 and end with 0 and start with 1 and end with 1.
More formally, strings such as 100,0101 are allowed since they start and end with different characters. But strings such as 0110,1101 are not allowed because they start and end with same characters.
Both Chef and Abhishek try their best to solve it but couldn't do it. You being a very good friend of Chef, he asks for your help so that he can solve it and become the Chairperson.
-----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 a single integer N denoting the length of the string.
The second line of each test case contains a binary string of length N.
-----Output:-----
For each test case, print a single line containing one integer ― the number of sub strings satisfying above conditions.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^9$
Binary string consist's only 0 and 1.
-----Sample Input:-----
1
4
1010
-----Sample Output:-----
4
-----EXPLANATION:-----
All possible substring are : { (1),(0),(1),(0),(10),(01),(10),(101),(010),(1010) }. Out of these only 4 substrings {(10),(01),(10),(1010)} start and end with different characters. Hence the answer 4.
|
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()
x='0'
y='1'
x1='1'
y1='0'
c1=countSubstr(str,n,x,y)
c2=countSubstr(str,n,x1,y1)
print(c1+c2)
|
|
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 Precedence of operators while evaluating the expression.
After some time of consistent work Chef starts feeling exhausted and wants you to automate this process for him. Can you help him out?
The expression has Bitwise operators in symbol format:
- & stands for AND
- | stands for OR
- ^ stands for XOR
NOTE : It is guaranteed that the expression will always be valid, also each OPERATOR will always be preceded and succeeded by an OPERAND.
-----Input:-----
- The first line of input contains a single integer $T$ denoting the number of test cases.
- The only line of input for each test case is a $string$ which is the Chef's expression to evaluate.
-----Output:-----
For each test case print a single integer i.e the maximum possible value of Chef's expression.
-----Constraints-----
- $1 \leq T \leq 100$.
- The number of OPERATORS in the expression will be atleast 1 and atmost 10.
- Each OPERAND may range from 0 to $10^9$.
-----Subtasks-----
- 10 points : The number of OPERATORS in the expression will be atmost 5.
- 20 points : The number of OPERATORS in the expression will be atmost 8.
- 70 points : Original constraints.
-----Sample Input:-----
2
3^40|10^2
92^95|56&2&3
-----Sample Output:-----
43
95
-----EXPLANATION:-----CASE 2 :
- If we first compute (56 & 2), the expression becomes 92^95|0&3, since (56 & 2) yields $0$.
- Now on computing (95 | 0), the expression becomes 92^95&3.
- Further on computing (95 & 3), the expression becomes 92^3.
- Finally (92 ^ 3) yields 95, which is the maximum value of the expression.
|
# 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_ans = []
for i in range(1,len(n)):
l1 = n[:i]
l2 = n[i:]
o1 = operator[:i]
o2 = operator[i:]
l1_ans = break_rules(l1, o1)
l2_ans = break_rules(l2, o2)
for k in l1_ans:
for j in l2_ans:
cont_ans.append(value(k, j, operator[i - 1]))
return cont_ans
t = int(input())
while t > 0 :
operator = []
num = []
exp = input()
temp = ''
for i in range(len(exp)):
if(ord(exp[i]) > 47 and ord(exp[i]) < 58):
temp = temp + exp[i]
else:
num.append(int(temp))
temp = ''
operator.append(exp[i])
if(i == len(exp) - 1):
num.append(int(temp))
t -= 1
# print(num,operator)
print(max(break_rules(num, operator)))
|
|
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
Now you are given a no and chef
wants you to find out largest "nice" integer which is smaller than or equal to the
given integer.
-----Constraints-----
1< t < 1000
1< N < 10^18
-----Input Format-----
First line contains no. of test cases t. Then t test cases follow. Each test case
contain a integer n.
-----Output-----
Output a integer for each test case in a new line which is largest nice
integer smaller or equal to the given integer.
-----Example Text Case-----
Input:
1
132
Output:
129
|
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
print("".join(n[i:]))
|
|
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 student should occupy a table that is adjacent to that student's original table, i.e. immediately to the left, right, top or bottom of that table.
Is it possible for the students to shuffle while satisfying all conditions of the teacher?
-----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 and only line of each test case contains two space-separated integers $N$ and $M$.
-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to satisfy the conditions of the teacher or "NO" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 5,000$
- $2 \le N, M \le 50$
-----Example Input-----
2
3 3
4 4
-----Example Output-----
NO
YES
-----Explanation-----
Example case 2: The arrows in the following image depict how the students moved.
|
# 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 test cases. Then follow T lines, each line contains two Integers A and B.
-----Output-----
For each test case, add A and B and display it in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 0 ≤ A,B ≤ 10000
-----Example-----
Input
3
1 2
100 200
10 40
Output
3
300
50
|
#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(' ')))
ans = a + b
print(ans)
|
|
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 can only move with constant speed 1$1$.
For each valid i$i$, the i$i$-th cat is initially sleeping at a point a_i$a_i$. At a time s_i$s_i$, this cat wakes up and starts moving to a final point b_i$b_i$ with constant velocity and without any detours (so it arrives at this point at the time e_i = s_i + |a_i-b_i|$e_i = s_i + |a_i-b_i|$). After it arrives at the point b_i$b_i$, it falls asleep again.
For each valid i$i$, the i$i$-th rat is initially hiding at a point c_i$c_i$. At a time r_i$r_i$, this rat stops hiding and starts moving to a final point d_i$d_i$ in the same way as the cats ― with constant velocity and without any detours, arriving at the time q_i = r_i + |c_i-d_i|$q_i = r_i + |c_i-d_i|$ (if it does not get eaten). After it arrives at the point d_i$d_i$, it hides again.
If a cat and a rat meet each other (they are located at the same point at the same time), the cat eats the rat, the rat disappears and cannot be eaten by any other cat. A sleeping cat cannot eat a rat and a hidden rat cannot be eaten ― formally, cat i$i$ can eat rat j$j$ only if they meet at a time t$t$ satisfying s_i \le t \le e_i$s_i \le t \le e_i$ and r_j \le t \le q_j$r_j \le t \le q_j$.
Your task is to find out which rats get eaten by which cats. It is guaranteed that no two cats will meet a rat at the same time.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- N$N$ lines follow. For each i$i$ (1 \le i \le N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers a_i$a_i$, b_i$b_i$ and s_i$s_i$.
- M$M$ more lines follow. For each i$i$ (1 \le i \le M$1 \le i \le M$), the i$i$-th of these lines contains three space-separated integers c_i$c_i$, d_i$d_i$ and r_i$r_i$.
-----Output-----
For each test case, print M$M$ lines. For each valid i$i$, the i$i$-th of these lines should contain a single integer ― the number of the cat that will eat the i$i$-th rat, or -1$-1$ if no cat will eat this rat.
-----Constraints-----
- 1 \le T \le 10$1 \le T \le 10$
- 0 \le N \le 1,000$0 \le N \le 1,000$
- 1 \le M \le 1,000$1 \le M \le 1,000$
- 1 \le a_i, b_i, s_i \le 10^9$1 \le a_i, b_i, s_i \le 10^9$ for each valid i$i$
- 1 \le c_i, d_i, r_i \le 10^9$1 \le c_i, d_i, r_i \le 10^9$ for each valid i$i$
- all initial and final positions of all cats and rats are pairwise distinct
-----Example Input-----
2
8 7
2 5 1
1 4 1
9 14 10
20 7 9
102 99 1
199 202 1
302 299 3
399 402 3
6 3 1
10 15 10
100 101 1
201 200 1
300 301 5
401 400 5
1000 1010 1020
8 8
2 8 2
12 18 2
22 28 4
32 38 4
48 42 2
58 52 3
68 62 1
78 72 3
3 6 3
13 19 3
21 25 3
31 39 3
46 43 4
59 53 2
65 61 4
79 71 2
-----Example Output-----
1
4
5
6
7
8
-1
1
2
3
4
5
6
7
8
|
# 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
self.start = start
self.end = end
self.starting_time = starting_time
def will_collide(self, z):
if self.starting_time > z.ending_time or self.ending_time < z.starting_time:
return False
if self.velocity == z.velocity:
if self.starting_time > z.starting_time:
self, z = z, self
if z.start == self.start + self.velocity * (z.starting_time - self.starting_time):
return z.starting_time
else:
return False
if self.velocity == -1:
self, z = z, self
t = ( z.start - self.start + z.starting_time + self.starting_time ) / 2
return t if self.starting_time <= t <= self.ending_time and z.starting_time <= t <= z.ending_time else False
def main():
for _ in range(int(input())):
no_cats, no_rats = map(int, input().split())
Cats = [Animal() for i in range(no_cats)]
for i in range(no_rats):
rat = Animal()
for j in range(no_cats):
time = rat.will_collide(Cats[j])
if time:
# print(time)
if time < rat.eaten_by[1]:
rat.eaten_by = j + 1, time
print(rat.eaten_by[0])
main()
|
|
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 in as possible and for it he has decided to make from the available logs as many frames as possible. Help him in finding the number of window Frames that he can make.
Note : Chef do not need to use all the logs
Input:
The first line of the input contains a single integer T denoting the number of test cases. The description of each test case follows :.
The first line of each test case contains a single integer n the number of wooden logs.
The second line contains n space-separated integers l1,l2,l3….ln The length of each wooden log
Output:
The only line in Output Contains single Integer denoting the maximum possible number of Wooden Frames.
Constraints:
1 ≤ T ≤ 10
1 ≤ n ≤ 100
1 ≤ li ≤ 10000
Example Input:
2
4
1 2 1 2
8
1 2 1 3 4 1 5 6
Example Output:
1
0
Explanation :
First Case : We can build a frame of dimension 1x2 as two logs of each dimension are available.
Second Case : We can’t build any Frame as no logs of length except 1 have more than one piece.
|
# 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:
print((x-1)//2)
j+=1
|
|
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, a) = d_a$ and d(x,b)=db$d(x, b) = d_b$, or determine that there is no such node.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and Q$Q$.
- Each of the next N−1$N-1$ lines contains two space-separated integers u$u$ and v$v$ denoting that nodes u$u$ and v$v$ are connected by an edge.
- Each of the next Q$Q$ lines contains four space-separated integers a$a$, da$d_a$, b$b$ and db$d_b$ describing a query.
-----Output-----
For each query, print a single line containing one integer ― the number of a node satisfying the given requirements, or −1$-1$ if no such node exists.
If there are multiple solutions, you may output any one.
-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N,Q≤106$1 \le N, Q \le 10^6$
- 1≤u,v≤N$1 \le u, v \le N$
- the graph on the input is a tree
- 1≤a,b≤N$1 \le a, b \le N$
- 1≤da,db<N$1 \le d_a, d_b < N$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
- the sum of Q$Q$ over all test cases does not exceed 106$10^6$
-----Subtasks-----
Subtask #1 (50 points):
- 1≤N,Q≤1,000$1 \le N, Q \le 1,000$
- the sum of N$N$ over all test cases does not exceed 1,000$1,000$
- the sum of Q$Q$ over all test cases does not exceed 1,000$1,000$
Subtask #2 (50 points): original constraints
-----Example Input-----
1
5 3
1 2
2 3
3 4
3 5
2 1 4 1
2 2 4 2
1 1 2 1
-----Example Output-----
3
5
-1
|
# 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()
self.nodes[new_node_1].append(new_node_2)
self.nodes[new_node_2].append(new_node_1)
def resolve_query(self, query):
a, d_a, b, d_b = query
suiting_a = self.find_nodes_with_distance(a, d_a)
suiting_b = self.find_nodes_with_distance(b, d_b)
fitting = [node for node in suiting_a if node in suiting_b]
if len(fitting) == 0:
return -1
else:
return fitting[0]
def find_nodes_with_distance(self, start_node, distance):
from_nodes = {start_node}
passed_nodes = from_nodes
for i in range(distance):
to_nodes = set()
# add all adjacent nodes
for node in from_nodes:
to_nodes.update(self.nodes[node])
# no backtracking
for node in passed_nodes:
if node in to_nodes:
to_nodes.remove(node)
# update which nodes are passed
passed_nodes.update(to_nodes)
# go another round with the new nodes found
from_nodes = to_nodes
return list(from_nodes)
def read_line():
line = input()
return [int(s) for s in line.split(' ')]
num_testcases = int(input())
for i in range(num_testcases):
testcase = TestCase()
testcase.fill_nodes()
for q in range(testcase.query_count):
query = read_line()
print(testcase.resolve_query(query))
|
|
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 does not exceed $S$; the topmost $k$ bricks break and are removed from the stack. Before each hit, Ada may also decide to reverse the current stack of bricks, with no cost.
Find the minimum number of hits Ada needs in order to break all bricks if she performs the reversals optimally. You are not required to minimise the number of reversals.
-----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 and only line of each test case contains four space-separated integers $S$, $W_1$, $W_2$ and $W_3$.
-----Output-----
For each test case, print a single line containing one integer ― the minimum required number of hits.
-----Constraints-----
- $1 \le T \le 64$
- $1 \le S \le 8$
- $1 \le W_i \le 2$ for each valid $i$
- it is guaranteed that Ada can break all bricks
-----Subtasks-----
Subtask #1 (50 points): $W_1 = W_2 = W_3$
Subtask #2 (50 points): original constraints
-----Example Input-----
3
3 1 2 2
2 1 1 1
3 2 2 1
-----Example Output-----
2
2
2
-----Explanation-----
Example case 1: Ada can reverse the stack and then hit it two times. Before the first hit, the widths of bricks in the stack (from top to bottom) are $(2,2,1)$. After the first hit, the topmost brick breaks and the stack becomes $(2,1)$. The second hit breaks both remaining bricks.
In this particular case, it is also possible to hit the stack two times without reversing. Before the first hit, it is $(1, 2, 2)$. The first hit breaks the two bricks at the top (so the stack becomes $(2)$) and the second hit breaks the last brick.
|
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 unlucky. Please see note section for formal definition of alternating code.
You are given a ticket code. Please determine, whether the day will be successful for Mike or not. Print "YES" or "NO" (without quotes) corresponding to the situation.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S denoting the letter code on the ticket.
-----Output-----
For each test case, output a single line containing "YES" (without quotes) in case the day will be successful and "NO" otherwise.
-----Note-----
Two letters x, y where x != y are said to be alternating in a code, if code is of form "xyxyxy...".
-----Constraints-----
- 1 ≤ T ≤ 100
- S consists only of upper-case Latin letters
Subtask 1 (50 points):
- |S| = 2
Subtask 2 (50 points):
- 2 ≤ |S| ≤ 100
-----Example-----
Input:
2
ABABAB
ABC
Output:
YES
NO
|
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:
print("NO")
else:
print("NO")
def __starting_point():
t = int(input())
for _ in range(t):
stri = str(input())
res(stri)
__starting_point()
|
|
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 the 1s in the prefix to 0s. You can use this operation as many number of times as you want over any prefix of the string.
-----Input-----
The only line of the input contains the binary string, S .
-----Output-----
Output a single line containing one integer, the minimum number of operations that are needed to transform the given string S into the string of equal length consisting only of zeros.
-----Constraints-----
- 1 ≤ |S| ≤ 100,000
-----Subtasks-----
- Subtask #1 (30 points): 1 ≤ |S| ≤ 2000
- Subtask #2 (70 points): Original constraints.
-----Example-----
Input:
01001001
Output:
6
-----Explanation-----
For the given sample case, let us look at the way where we achieved minimum number of operations.
Operation 1: You flip values in the prefix of length 8 and transform the string into 10110110
Operation 2: You flip values in the prefix of length 7 and transform the string into 01001000
Operation 3: You flip values in the prefix of length 5 and transform the string into 10110000
Operation 4: You flip values in the prefix of length 4 and transform the string into 01000000
Operation 5: You flip values in the prefix of length 2 and transform the string into 10000000
Operation 6: You flip values in the prefix of length 1 and finally, transform the string into 00000000
|
# 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, 2, 2]$ is gcd(1,2)+gcd(1,2)+gcd(2,2)=4$gcd(1, 2) + gcd(1, 2) + gcd(2, 2) = 4$.
You are given a sequence A1,A2,…,AN$A_1, A_2, \dots, A_N$; each of its elements is either a positive integer or missing.
Consider all possible ways to replace each missing element of A$A$ by a positive integer (not necessarily the same for each element) such that the sum of all elements is equal to S$S$. Your task is to find the total niceness of all resulting sequences, i.e. compute the niceness of each possible resulting sequence and sum up all these values. Since the answer may be very large, compute it modulo 109+7$10^9 + 7$.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and S$S$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Missing elements in this sequence are denoted by −1$-1$.
-----Output-----
For each test case, print a single line containing one integer — the total niceness modulo 109+7$10^9 + 7$.
-----Constraints-----
- 1≤T≤20$1 \le T \le 20$
- 1≤N,S≤50$1 \le N, S \le 50$
- 1≤Ai≤50$1 \le A_i \le 50$ or Ai=−1$A_i = -1$ for each valid i$i$
-----Subtasks-----
Subtask #1 (30 points):
- 1≤N,S≤18$1 \le N, S \le 18$
- 1≤Ai≤18$1 \le A_i \le 18$ or Ai=−1$A_i = -1$ for each valid i$i$
Subtask #2 (70 points): original constraints
-----Example Input-----
3
3 3
1 1 -1
4 8
1 -1 -1 3
3 10
-1 -1 -1
-----Example Output-----
3
23
150
-----Explanation-----
Example case 1: There is only one possible way to fill in the missing element; the resulting sequence is [1,1,1]$[1, 1, 1]$. Its niceness is 3$3$.
Example case 2: There is only three possible ways to fill in the missing elements; the resulting sequences are [1,1,3,3]$[1, 1, 3, 3]$, [1,3,1,3]$[1, 3, 1, 3]$, and [1,2,2,3]$[1, 2, 2, 3]$. The sum of their niceness is 8+8+7=23$8 + 8 + 7 = 23$.
|
# 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,gcds = fac50(),gcd110()
def rule_asc(n,l):
a,k = [0 for i in range(n + 1)],1
a[1] = n
while k != 0:
x,y = a[k - 1] + 1,a[k] - 1
k -= 1
while x <= y and k < l - 1:
a[k],y = x,y-x
k += 1
a[k] = x + y
yield a[:k + 1]
def niceness(s):
t = 0
for i in range(len(s)):
for j in range(i+1,len(s)):t = (t + gcds[s[i]][s[j]])%mod
return t
def permcount(s,c):
f,p = [s.count(x) for x in set(s)],factorials[c]
for e in f:p = (p*pow(factorials[e],mod-2,mod))%mod
return p
def main():
for i in range(int(input())):
n,s = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]
b = [i for i in a if i != -1]
s , ones = s - sum(b),a.count(-1)
if s < 0:print(0)
elif (s == 0 and ones == 0):print(niceness(a)%mod)
elif (s > 0 and ones == 0):print(0)
else:
t = 0
for seq in rule_asc(s,ones):
if len(seq) == ones: t = (t + (((permcount(seq,ones))%mod)*(niceness(b+seq)%mod))%mod)%mod
print(t)
def __starting_point():main()
__starting_point()
|
|
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 2015.
They have carefully counted a total of exactly 1 billion (109) dollars in the bank vault. Now they must decide how to divide the booty. But there is one problem: the thieves have only M minutes to leave the bank before the police arrives. Also, the more time they spend in the vault, the less amount could carry away from the bank. Formally speaking, they can get away with all of the billion dollars right now, but after t minutes they can carry away only 1 billion * pt dollars, where p is some non-negative constant less than or equal to unity, and at t = M, they get arrested and lose all the money.
They will not leave the vault until a decision on how to divide the money has been made.
The money division process proceeds in the following way: at the beginning of each minute starting from the 1st (that is, t = 0), one of them proposes his own way to divide the booty. If his colleague agrees, they leave the bank with pockets filled with the proposed amounts of dollars. If not, the other one proposes his way at the next minute etc. To escape arrest, they can only propose plans till the beginning of the Mth minute (i.e., till t = M-1).
Each thief wants to maximize his earnings, but if there are two plans with the same amounts for him, he would choose the one which leads to a larger total amount of stolen dollars.
Chef is about to start this procedure, and he is the first to propose a plan. You are wondering what will be the final division of money, if each thief chooses the optimal way for himself and money is considering real.
-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of input for each test case contains an integer M denoting the number of minutes until arrest and a double denoting the constant p.
-----Output-----
For each test case, output a single line containing two space-separated doubles denoting the amount of dollars each thief will get in the optimal division. First number: dollars amassed by Chef, and second: by his colleague. The answer will be considered correct if its absolute error doesn't exceed 10-2.
-----Constraints and subtasks-----
- 1 ≤ T ≤ 105
- 0 ≤ p ≤ 1
Subtask 1 (15 points) :
1 ≤ M ≤ 3
Subtask 2 (55 points) :
1 ≤ M ≤ 103
Subtask 3 (30 points) :
1 ≤ M ≤ 109
-----Example-----
Input:
2
1 0.5
2 0.5
Output:
1000000000.0 0.0
500000000.0 500000000.0
-----Explanation-----
Example case 1. In the second case, if decision isn't made at t = 0, total amount of money decreases to 5*108 at t = 1 which leads to a situation worse than the given solution.
|
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 parent node(which has a valid leaf node attached to it), he cuts $x$ leaf nodes, such that $x$ is a multiple of 3.
Example : If a parent node has 7 leaf nodes, 6 leaf nodes will be cut and 1 will be left.
- If a parent has all its leaf nodes cut, only then the parent node itself becomes a new leaf node. If new leaf nodes are created, Gardner repeats step 1 until he can cut no more leaf nodes.
After completing all operations, gardner wants to know the minimum number of nodes left on the tree.
It is guaranteed that the given input is a rooted tree.
The root of the tree is vertex 1.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains an integer $n$, the number of vertices in the tree.
- Second line of each testcase contains array $A$ of size $n-1$, where $A_{i}(1≤i≤n-1)$, is the index of the parent of the $(i+1)^{th}$ vertex.
-----Output:-----
For each testcase, output single integer, the number of nodes finally left on the tree.
-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq n \leq 10^5$
- $1 \leq A_i \leq i$
-----Sample Input:-----
1
13
1 1 1 1 1 4 3 4 4 3 4 3
-----Sample Output:-----
4
-----EXPLANATION:-----
|
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)
for i in range(2,n+1):
#print(i,arr[i-2])
adj[arr[i-2]].append(i)
dfs(1)
print(n-leaf)
|
|
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 as an even integer, and the line drawn from the opposite vertex to the mid-point of the altered side is of integral length.
Since Rupsa is in a hurry to record a song for Chef as he really loves her songs, you must help her solve the problem as fast as possible.
-----Input-----
The first line of input contains an integer T denoting the number of test cases.
Each test-case contains a single integer N.
-----Output-----
For each test case, output "YES" if the triangle transformation is possible, otherwise "NO" (quotes for clarity only, do not output).
-----Constraints-----
- 1 ≤ T ≤ 106
- 1 ≤ N ≤ 5 x 106
-----Sub tasks-----
- Subtask #1: 1 ≤ T ≤ 100, 1 ≤ N ≤ 104 (10 points)
- Subtask #2: 1 ≤ T ≤ 104, 1 ≤ N ≤ 106 (30 points)
- Subtask #3: Original Constraints (60 points)
-----Example-----
Input:2
5
3
Output:YES
NO
-----Explanation-----
- In test case 1, make the length of any one side 6, and it will suffice.
|
# 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 'YES'
return 'NO'
test = int(input())
for __ in range(test):
num=int(input())
print(isPos(num))
|
|
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 number of words N
Next N words follow . They’ll contain only alphabets from ‘a’-‘z’.
-----Output-----
Print case number (for each test case) of the format Case : num followed by the words that rhyme in a new line.
-----Constraints-----
1 <= T <= 5
1 <= N <= 1000
3 <= length of each word <= 1000
-----Example-----
Input:
3
3
nope qwerty hope
5
brain drain request grain nest
4
these words dont rhyme
Output:
Case : 1
hope nope
qwerty
Case : 2
brain drain grain
nest request
Case : 3
these
dont
words
rhyme
-----Explanation-----
Case : 2
brain drain grain
nest request
Case : 3
these
dont
words
rhyme
Explanation for case 1: since hope and nope rhyme (suffix “ope” matches), we print them in the same line and qwerty In a new line.
Note that
qwerty
nope hope
is also correct (the output can be in any order )
|
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 + " " for b in sorted(suffixes[a])).strip())
|
|
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 a different place in the shelf. Suppose Indraneel has $5$ books and they are initially arranged in the order
21453214532 \quad 1 \quad 4 \quad 5 \quad 3
Indraneel will rearrange this in ascending order by first moving book $1$ to the beginning of the shelf to get
12453124531 \quad 2 \quad 4 \quad 5 \quad 3
Then, moving book $3$ to position $3$, he gets
12345123451 \quad 2 \quad 3 \quad 4 \quad 5
Your task is to write a program to help Indraneel determine the minimum number of moves that are necessary to sort his book shelf.
-----Input:-----
The first line of the input will contain a single integer $N$ indicating the number of books in Indraneel's library. This is followed by a line containing a permutation of $1, 2, ..., N$ indicating the intial state of Indraneel's book-shelf.
-----Output:-----
A single integer indicating the minimum number of moves necessary to sort Indraneel's book-shelf.
-----Constraints:-----
- $1 \leq N \leq 200000$.
- You may also assume that in $50 \%$ of the inputs, $1 \leq N \leq 5000$.
-----Sample Input-----
5
2 1 4 5 3
-----Sample Output-----
2
|
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 addition.
- Choose a subset of elements of the triple.
- Apply arithmetic operation to each of the chosen elements.
For example, if we have a triple $(3,5,7)$, we may choose to add $3$ to the first and third element, and we get $(6,5,10)$ using one operation.
You are given an initial triple $(p,q,r)$ and a target triple $(a,b,c)$. Find the maximum number of operations needed to transform $(p,q,r)$ into $(a,b,c)$ or say the conversion is impossible .
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.Output:
For each test case, print a single line containing one integer ― the maximum required number of operations(if the conversion is possible), or else print "-1"
Constraints:
- $1 \leq T \leq 1,000$
- $2 \leq |p|,|q|,|r|,|a|,|b|,|c| \leq 10^9$Sample Input:
1
2 2 1
3 3 2
Sample Output:
3
|
# 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.
Output:
For each test case, print a single line containing one integer ― the maximum required number of operations(if the conversion is possible), or else print "-1"
"""
T=int(input())
while T>0:
T-=1
p,q,r=list(map(int,input().split()))
a,b,c=list(map(int,input().split()))
#ds=list()
s=0
d1=a-p
if d1>0:
#ds.append(d1)
s+=d1
d2=b-q
if d2>0:
#ds.append(d2)
s+=d2
d3=c-r
if d3>0:
#ds.append(d3)
s+=d3
if(d1==0 and d2==0 and d3==0):
print(0)
elif(d1<0 or d2<0 or d3<0):
print(-1)
else:
print(s)
|
|
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 colours. He draws N$N$ lines (numbered 1$1$ through N$N$) in a 2D Cartesian coordinate system; for each valid i$i$, the i$i$-th line is drawn with the ci$c_i$-th pencil and it is described by the equation y=ai⋅x+bi$y = a_i \cdot x + b_i$.
Now, infinitepro calls a triangle truly-geometric if each of its sides is part of some line he drew and all three sides have the same colour. He wants to count these triangles, but there are too many of them! After a lot of consideration, he decided to erase a subset of the N$N$ lines he drew. He wants to do it with his eraser, which has length K$K$.
Whenever erasing a line with a colour i$i$, the length of the eraser decreases by Vi$V_i$. In other words, when the eraser has length k$k$ and we use it to erase a line with a colour i$i$, the length of the eraser decreases to k−Vi$k-V_i$; if k<Vi$k < V_i$, it is impossible to erase such a line.
Since infinitepro has to study for the re-exam, he wants to minimise the number of truly-geometric triangles. Can you help him find the minimum possible number of truly-geometric triangles which can be obtained by erasing a subset of the N$N$ lines in an optimal way? He promised a grand treat for you if he passes the examination!
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of the input contains three space-separated integers N$N$, C$C$ and K$K$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers ai$a_i$, bi$b_i$ and ci$c_i$.
- The last line contains C$C$ space-separated integers V1,V2,…,VC$V_1, V_2, \ldots, V_C$.
-----Output-----
For each test case, print a single line containing one integer ― the smallest possible number of truly-geometric triangles after erasing lines.
-----Constraints-----
- 1≤T≤10$1 \le T \le 10$
- 1≤C≤N≤3,000$1 \le C \le N \le 3,000$
- 0≤K≤3,000$0 \le K \le 3,000$
- 0≤ai,bi≤109$0 \le a_i, b_i \le 10^9$ for each valid i$i$
- 1≤ci≤C$1 \le c_i \le C$ for each valid i$i$
- 0≤Vi≤K$0 \le V_i \le K$ for each valid i$i$
- no two lines coincide, regardless of their colours
- no three lines are concurrent
-----Subtasks-----
Subtask #1 (10 points):
- N≤10$N \le 10$
- K≤100$K \le 100$
Subtask 2 (15 points):
- V1=V2=…=VC$V_1 = V_2 = \ldots = V_C$
- no two lines are parallel
Subtask #3 (25 points): no two lines are parallel
Subtask #4 (50 points): original constraints
-----Example Input-----
2
7 2 13
1 10 1
1 14 2
6 4 1
2 2 1
0 12 2
2 11 2
0 6 1
8 10
6 1 20
1 5 1
2 11 1
4 0 1
6 8 1
0 11 1
3 3 1
9
-----Example Output-----
2
4
-----Explanation-----
Example case 1: We can remove exactly one line. Initially, we have 5$5$ truly geometric triangles (see the image below; red is colour 1$1$ and green is colour 2$2$).
- Removing any line with colour 2$2$ brings the total number of truly-geometric triangles down to 4+0=4$4+0=4$.
- Removing any line with colour 1$1$ brings the total number of truly-geometric triangles down to 1+1=2$1+1=2$.
Thus, the smallest number of truly-geometric triangles we can obtain is 2$2$.
Example case 2: We can remove at most 2$2$ lines and removing any 2$2$ lines gives us a total of 4$4$ truly-geometric triangles.
|
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[i][1]
else:
ch=1/s[i][1]
if t<ch:
t=ch
x=i
return x
t=int(input())
for x in range(t):
n,c,k=map(int,input().split())
l={}
for i in range(n):
a,b,e=map(int,input().split())
if e in l:
l[e].append(a)
else:
l[e]=[]
l[e].append(a)
v=list(map(int,input().split()))
s=[]
for i in range(1,c+1):
if i in l:
s+=[[len(l[i]),v[i-1]]]
s.sort(key = lambda x: x[0],reverse=True)
while True:
ma=rem(s,k)
if ma<=-1:
break
else:
s[ma][0]-=1
k=k-s[ma][1]
re=0
for i in s:
if i[0]>2:
re=re+nc3(i[0])
print(int(re))
|
|
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 time $0$
- During the first round, he moves towards $x=1$ and comes back to the $x=0$ position.
- In the second round, he moves towards the $x=2$ and comes back again to $x=0$.
- So , at $Kth$ round , he moves to $x=K$ and comes back to $x=0$
So in this way game goes ahead.
For Example, the path of Kabir for $3rd$ round is given below.
$0−1−2−3−2−1−0$
The overall path followed by Kabir would look somewhat like this:
$0−1−0−1−2−1−0−1−2−3−2−1−0−1−2−3−4−3−…$
Now the task is , You are given Two Non-Negative integers $N$ , $K$ .
You have to tell the time at which Kabir arrives at $x=N$ for the $Kth$ time.
Note - Kabir visits all the points , he can not skip or jump over one point.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $N, K$.
-----Output:-----
For each testcase, output in a single line answer i.e Time Taken by Kabir Singh modulo 1000000007.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $0 \leq N \leq 10^9$
- $1 \leq K \leq 10^9$
-----Sample Input:-----
4
0 1
1 1
1 3
4 6
-----Sample Output:-----
0
1
5
46
-----EXPLANATION:-----
Test Case 1:
Kabir starts the journey from the $N=0$ at time $t=0$ and it's the first time$ (K=1)$, he is here. So, the answer is $0$.
Test Case 3:
The path followed by Kabir to reach 1 for the third time is given below.
$0−1−0−1−2−1$
He reaches $1$ for the third time at $ t=5$.
|
# 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 large, output it modulo 1,000,000,007 (10^9+7).
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains the pair of integers L and R, separated by a single space.
-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.
-----Constraints-----
- 1 ≤ T ≤ 1,000
- 1 ≤ L ≤ R ≤ 1,000,000,000 (10^9)
-----Example-----
Input:
1
9 12
Output:
75
-----Explanation-----
Example case 1. The answer is 9*1 + 10*2 + 11*2 + 12*2 = 75.
|
# 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())):
l,r=map(int, stdin.readline().strip().split())
low=len(str(l))
high=len(str(r))
ans=0
if low==high:
ans=get_sum(l,r,low)
else:
ans+=get_sum(l,((10**low)-1),low)
ans+=get_sum((10**(high-1)),r,high)
for i in range(low+1,high):
ans+=get_sum(10**(i-1),(10**i)-1,i)
print(ans%mod)
def __starting_point():
solve()
__starting_point()
|
|
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 after that they find all its divisors.Suppose first sumit took a divisor then dhiraj and so on.The player who will be having the last divisor with him will win the game.Rohit their mutual friend,was observing them play. Can you help Rohit predict the outcome of game? If Sumit wins print "YES" without quotes and "NO" without quotes, if Dhiraj wins
the game.
-----Input-----
Input starts with an integer T denoting the number of test cases Each test case starts with a line containing an integer N the number.
-----Output-----
Outcome of each game in a separate line
-----Constraints-----
- 1 ≤ T ≤ 10^3
- 1 ≤ N ≤ 10^18
-----Sub tasks-----
- Subtask #1:(10 points)
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 103
- Subtask #2:(25 points)
- 1 ≤ T ≤ 50
- 1 ≤ N ≤ 1016
- Subtask #3:(65 points)
- 1 ≤ T ≤ 103
- 1 ≤ N ≤ 1018
-----Example-----
Input:
2
4
5
Output:
YES
NO
|
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 cases. Each case begins with a single integer N, the length of A. Then follow N space separated integers in next line. Assume that 1 <= T <= 100, 1 <= N <= 100 and for all i in [1..N] : 1 <= A[i] <= 10000
-----Output-----
For each test case, output two space separated integers V & C. V is the value which occurs maximum number of times and C is its count.
-----Example-----
Input:
2
5
1 2 3 2 5
6
1 2 2 1 1 2
Output:
2 2
1 3
Description:
In first case 2 occurs twice whereas all other elements occur only once.
In second case, both 1 and 2 occur 3 times but 1 is smaller than 2.
|
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, find any i, j such that i < j
and Ai + Aj is maximum possible
unfortunately, there's no much time left before the end of the contest, so Chefu doesn't have time to think of correct solution, so instead, he wrote a solution that selects a random pair (i, j) (i < j) and output Ai + Aj. each pair is equiprobable to be selected.
Now Chefu wants your help to calculate the probability that his solution will pass a particular input.
-----Input-----
First line contains an integer T denoting the number of test-cases.
First line of each test-case contains a single integer N
Second line of each test-case contains N space-separated integers A1 A2 ... AN
-----Output-----
For each test-case output a single line containing a single number denoting the probability that Chefu's solution to output a correct answer. your answer will be accepted if the absolute difference between it and correct answer is less than 1e-6
-----Constraints-----
- 1 ≤ T ≤ 100
- 2 ≤ N ≤ 100
- 1 ≤ Ai ≤ 1,000
-----Example-----
Input:
3
4
3 3 3 3
6
1 1 1 2 2 2
4
1 2 2 3
Output:
1.00000000
0.20000000
0.33333333
|
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 between two vertices $u$ and $v$ is the sum of the values assigned to the vertices on that path (including $u$ and $v$).
Let's consider only (undirected) paths that start at a leaf and end at a different leaf. Calculate the maximum possible value of the sum of profits of all such paths. Since this value could be very large, compute it modulo $10^9 + 7$.
-----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 a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- Each of the following $N−1$ lines contains two space-separated integers $u$ and $v$ denoting that vertices $u$ and $v$ are connected by an edge.
-----Output-----
For each test case, print a single line containing one integer — the maximum sum of profits, modulo $10^9 + 7$.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 300,000$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$
-----Example Input-----
2
4
1 2 3 4
1 2
2 3
2 4
5
1 2 3 4 5
1 2
2 3
3 4
4 5
-----Example Output-----
24
15
-----Explanation-----
Example case 1: $(1, 4, 2, 3)$ is one of the possible permutations that give the optimal answer. Then, the profits of paths between pairs of vertices $(1, 3)$, $(1, 4)$ and $(3, 4)$ are $7$, $8$ and $9$ respectively.
Example case 2: Here, any permutation could be chosen.
|
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].append(v)
B[v].append(u)
total_leaves = 0
for i in B:
if len(B[i]) == 1:
total_leaves += 1
S = [0]
visited = [False] * N
parent = [-1] * N
total_visits = [0] * N
while len(S) > 0:
current = S.pop(len(S) - 1)
if visited[current]:
p = parent[current]
if p != -1:
total_visits[p] += total_visits[current]
if p not in C:
C[p] = {}
C[p][current] = total_visits[current]
if current not in C:
C[current] = {}
C[current][p] = total_leaves - C[p][current]
else:
S.append(current)
visited[current] = True
for i, j in enumerate(B[current]):
if not visited[j]:
parent[j] = current
S.append(j)
if len(B[current]) == 1:
total_visits[current] = 1
p = parent[current]
if p != -1:
if p not in C:
C[p] = {}
C[p][current] = 1
D = {}
for i in C:
sum1 = 0
for j in C[i]:
sum1 += C[i][j]
D[i] = sum1
E = [0] * N
for i in C:
sum1 = 0
for j in C[i]:
D[i] -= C[i][j]
sum1 += C[i][j] * D[i]
E[i] = sum1
for i, j in enumerate(E):
if j == 0:
for k in C[i]:
E[i] = C[i][k]
E.sort()
E.reverse()
A.sort()
A.reverse()
E = [x % M for x in E]
A = [x % M for x in A]
ans = 0
for i, j in zip(E, A):
a = i * j
a %= M
ans += a
ans %= M
print(ans)
|
|
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 individually if they are taken from different positions.
-----Input-----
Input is given in the following format:
$N$
$A_1$ $A_2$ . . . $A_N$
-----Output-----
Find the number of the non-empty contiguous subsequences of $A$ whose sum is $0$.
-----Constraints-----
- $1 \leq N \leq 2\times10^5$
- $-10^9 \leq A_i \leq 10^9$
- All values in input are integers.
-----Sample Input-----
6
1 3 -4 2 2 -2
-----Sample Output-----
3
-----EXPLANATION-----
There are three contiguous subsequences whose sums are $0$: $(1, 3, -4)$, $(-4, 2, 2)$ and $(2, -2)$
|
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 current element to sum so far.
currsum += arr[i]
# If currsum is equal to desired sum,
# then a new subarray is found. So
# increase count of subarrays.
if currsum == Sum:
res += 1
# currsum exceeds given sum by currsum - sum.
# Find number of subarrays having
# this sum and exclude those subarrays
# from currsum by increasing count by
# same amount.
if (currsum - Sum) in prevSum:
res += prevSum[currsum - Sum]
# Add currsum value to count of
# different values of sum.
prevSum[currsum] += 1
return res
n=int(input())
lst=list(map(int,input().split()))
if(n==1):
if(lst[0]==0):
print(1)
else:
print(0)
else:
print(findSubarraySum(lst,n,0))
|
|
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 three parameters Li$L_i$, Ri$R_i$ and Xi$X_i$ with the following meaning: for each player between the Li$L_i$-th and Ri$R_i$-th inclusive, if this player participates in this challenge, their skill level increases by Xi$X_i$ (Xi$X_i$ does not have to be positive).
The organizers of the Cooking Challenge decided that the contest would be boring if they let the participants participate in the challenges directly, so they decided to use the compos.
There are Q$Q$ compos (numbered 1$1$ through Q$Q$). For each valid i$i$, the i$i$-th compo has two parameters Ai$A_i$ and Bi$B_i$, which means that it includes the challenges Ai,Ai+1,…,Bi$A_i, A_i+1, \ldots, B_i$.
Each participant has to select a subset of the compos (possibly empty or the set of all Q$Q$ compos) and participate in all challenges those compos include. A participant may not select the same compo twice, but may participate in the same challenge more than once if it is included in multiple chosen compos.
For each player, find the maximum skill level this player can reach if the compos are chosen optimally.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains three space-separated integers N$N$, M$M$ and Q$Q$.
- M$M$ lines follow. For each valid i$i$, the i$i$-th of these lines contains three space-separated integers Li$L_i$, Ri$R_i$ and Xi$X_i$.
- Q$Q$ more lines follow. For each valid i$i$, the i$i$-th of these lines contains two space-separated integers Ai$A_i$ and Bi$B_i$.
-----Output-----
For each test case, print a single line containing N$N$ space-separated integers. For each valid i$i$, the i$i$-th of these integers should denote the maximum skill level of the i$i$-th player.
-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N≤100,000$1 \le N \le 100,000$
- 1≤M≤1,000$1 \le M \le 1,000$
- 1≤Q≤10,000$1 \le Q \le 10,000$
- 1≤Li≤Ri≤N$1 \le L_i \le R_i \le N$ for each valid i$i$
- 1≤Ai≤Bi≤M$1 \le A_i \le B_i \le M$ for each valid i$i$
- |Xi|≤1,000,000$|X_i| \le 1,000,000$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed 1,000,000$1,000,000$
- the sum of M$M$ over all test cases does not exceed 5,000$5,000$
- the sum of Q$Q$ over all test cases does not exceed 50,000$50,000$
-----Example Input-----
1
5 3 4
1 1 3
1 2 -4
4 5 2
1 2
1 3
1 1
2 3
-----Example Output-----
3 0 0 4 4
-----Explanation-----
Example case 1:
- The first player will select the 3$3$-rd compo.
- The second and third players will not select any compo.
- The fourth player will select the 1$1$-st, 2$2$-nd and 4$4$-th compos.
- The fifth player will select all the compos.
|
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:
start = mid+1
new_list.insert(start,array[i])
return new_list
tests = int(input())
for _ in range(tests):
n, m, q = [int(j) for j in input().split()]
challenges = [[0] * 3 for _ in range(m)]
combos = [[0] * 2 for _ in range(q)]
for i in range(m):
challenges[i] = [int(j) for j in input().split()]
for i in range(q):
combos[i] = [int(j) for j in input().split()]
sorted_chalenges = np.zeros((2 * m, 3),dtype=np.intc)
for i in range(m):
sorted_chalenges[2*i] = [challenges[i][0]-1,challenges[i][2],i]
sorted_chalenges[2*i+1] = [challenges[i][1],-challenges[i][2],i]
sorted_chalenges = np.array(sort_it(sorted_chalenges))
types_of_players = np.zeros((m + 1, 2 * m + 1),dtype=np.intc)
player_type = np.zeros(n,dtype=np.intc)
last_player = 0
for i in range(2 * m):
start, value, chal = sorted_chalenges[i]
types_of_players[chal+1:,i+1:] += value
player_type[last_player:start] = i
last_player = start
player_type[last_player:] = 2 * m
combo_types = np.zeros((q, 2 * m + 1),dtype = np.intc)
for i in range(q):
first, last = combos[i]
r, p = [types_of_players[first - 1], types_of_players[last]]
combo_types[i] = np.maximum(p-r,0)
output = np.sum(combo_types,axis=0)[player_type]
for i in range(n):
print(output[i], end = " ")
print("")
|
|
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 line will contain $T$, number of test cases. Then the test cases follow.
- First line of each test case, contains the size of the string $N$
- Seond line contains a single line of input, the binary string.
-----Output:-----
For each testcase, output in a single line answer - the minimum operations.
-----Constraints-----
- $1 \leq T \leq 100$
- $2 \leq |S| \leq 10^3$
-----Sample Input:-----
1
4
1011
-----Sample Output:-----
1
|
'''
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])-0:
fp1+=1
fl1=1-fl1
print(fp) if fp<fp1 else print(fp1)
|
|
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 called Codepur Cares Fund (CCF). So they decided to run a survey.
Each building eihter has permanent donors, whose impact value is represented as a positive integer, or potential donors, whose impact value is represented by negative integers.
Overwhelmed by the response, and sticking to their resource optimized philosophy, they decided to hire you to determine the contiguous buildings which are allowed to donate to CCF with the following rule:
The contiguous buildings / areas with the maximum sum impact shall be allowed for donating to Codepur Cares Fund (CCF).
Help them out to get a stunning Diwali bonus and rest of your trip sponsered!
-----Input:-----
The first line consists of two tab spaced integers m and n, indicating number of rows and columns respectively in the Codepur's city plan (which is a 2-D Matrix).
The next $m$ lines consist of $n$ tab spaced integers $ti$ indicating rows in the matrix.
-----Output:-----
Print the bulidings (represented by their donors numbers) which are eligible to donate to CCF (i.e, have the largest sum contiguously) as a 2-D matrix with the elements being tab-spaced.
-----Constraints-----
- $0 \leq m,n \leq 10^{15}$
- $-10^{15} \leq ti \leq 10^5$
-----Sample Input:-----
6 5
0 -2 -7 0 -1
9 2 -6 2 0
-4 1 -4 1 0
-1 8 0 -2 1
-10 1 1 -5 6
-15 -1 1 5 -4
-----Sample Output:-----
9 2
-4 1
-1 8
|
#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):
Sum += arr[i]
if Sum < 0:
Sum = 0
local_start = i + 1
elif Sum > maxSum:
maxSum = Sum
start[0] = local_start
finish[0] = i
if finish[0] != -1:
return maxSum
maxSum = arr[0]
start[0] = finish[0] = 0
for i in range(1, n):
if arr[i] > maxSum:
maxSum = arr[i]
start[0] = finish[0] = i
return maxSum
def findMaxSum(M):
nonlocal ROW, COL
maxSum, finalLeft = float('-inf'), None
finalRight, finalTop, finalBottom = None, None, None
left, right, i = None, None, None
temp = [None] * ROW
Sum = 0
start = [0]
finish = [0]
for left in range(COL):
temp = [0] * ROW
for right in range(left, COL):
for i in range(ROW):
temp[i] += M[i][right]
Sum = kadane(temp, start, finish, ROW)
if Sum > maxSum:
maxSum = Sum
finalLeft = left
finalRight = right
finalTop = start[0]
finalBottom = finish[0]
for i in range(finalTop,finalBottom+1):
print(*M[i][finalLeft:finalRight+1])
ROW,COL = ip()
M = [ip() for i in range(ROW)]
findMaxSum(M)
|
|
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 the angle he has to cover is minimum possible.
You will be given a clock time in $UTC$ format denoting time of chef's jump and you have to compute the minimum angle that chef needs to cover while completing the jump.
For some reason chef times his jump only when the number of minutes is a multiple of 5.
-----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 a string denoting time in UTC format (e.g. 10:20 i.e. 10 hours and 20 minutes)
-----Output-----
For each test case, print a single line denoting the smallest angle of jump.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $0 \leq hours \leq 23$
- $0 \leq minutes \leq 59$
-----Example Input-----
3
14:20
02:10
09:30
-----Example Output-----
50 degree
5 degree
105 degree
-----Explanation-----
- In the second case, once the hour hand reaches 2 it starts moving towards 3 with the passing of every minute, hence when the minute hand points 10 minutes, the hour hand has already covered some angle towards 3.
In this scenario the two angles made by hour and minute hand are 355 and 5 degrees. Since chef will jump on the side with minimum angle, he chooses the one with 5-degree angle.
|
# 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(ans1,ans2)
if ans==int(ans):
ans3=int(ans)
y=str(ans3)+" degree"
print(y)
else:
y=str(ans)+" degree"
print(y)
t-=1
|
|
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 information about the extra amount paid by each creature, by an array A of size N, where Ai denotes the extra amount paid by the i-th creature, in rupees.
After the end of the trip, Lumpy noticed that he had P one rupee coins and Q two rupee coins. He wants to pay back the creatures using this money. Being a kind hearted moose, Lumpy wants to pay back as many creatures as he can. Note that Lumpy will
not pay back the i-th creature if he can't pay the exact amount that the i-th creature requires with the coins that he possesses.
Lumpy is busy driving the bus and doesn't want to calculate the maximum number of creatures he can satisfy - He will surely cause an accident if he tries to do so. Can you help him out with this task?
-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- For each test case, first line consists of three space separated integers N, P and Q.
- Second line consists of N space separated integers A containing N space integers, where i-th integer denotes Ai.
-----Output-----
- For each test case, output a single line containing an integer corresponding to maximum number of creatures that Lumpy can pay back.
-----Constraints-----
- 1 ≤ T ≤ 106
- 1 ≤ N ≤ 105
- 1 ≤ Ai ≤ 109
- 0 ≤ P, Q ≤ 1014
- Sum of N over all the cases does not exceed 106
-----Subtasks-----
- Subtask #1 (15 points): P = 0
- Subtask #2 (15 points): Q = 0
- Subtask #3 (70 points): Original constraints
-----Example-----
Input:3
3 3 0
1 2 2
3 2 1
1 2 1
4 5 4
2 3 4 5
Output:2
3
3
-----Explanation-----
Example 1. Lumpy has just 3 one rupee coins.
He can pay creatures numbered {1, 2} or creatures numbered {1, 3} with these coins. Thus, answer is 2.
Example 2. Lumpy has 2 one rupee coins and 1 two rupee coin.
In the optimal solution, Lumpy can give the two rupee coin to creature 2 and the one rupee coins to creatures 1 and 3. Thus, answer is 3.
|
# 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(i%2==0 and a>=i):
a=a-i
b=b+1
elif(i%2!=0 and p!=0 and a>=i):
a=a-i
b=b+1
p=p-1
print(b)
|
|
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 would like to properly format it.
A name can have at most three parts: first name, middle name and last name. It will have at least one part. The last name is always present. The rules of formatting a name are very simple:
- Only the first letter of each part of the name should be capital.
- All the parts of the name except the last part should be represented by only two characters. The first character should be the first letter of the part and should be capitalized. The second character should be ".".
Let us look at some examples of formatting according to these rules:
- gandhi -> Gandhi
- mahatma gandhI -> M. Gandhi
- Mohndas KaramChand ganDhi -> M. K. Gandhi
-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The only line of each test case contains the space separated parts of the name.
-----Output-----
For each case, output the properly formatted name.
-----Constraints-----
- 1 ≤ T ≤ 100
- 2 ≤ Length of each part of the name ≤ 10
- Each part of the name contains the letters from lower and upper case English alphabets (i.e. from 'a' to 'z', or 'A' to 'Z')
-----Subtasks-----
Subtask #1 (40 points)
- There is exactly one part in the name.
Subtask #2 (60 points)
- Original constraints.
-----Example-----
Input:
3
gandhi
mahatma gandhI
Mohndas KaramChand gandhi
Output:
Gandhi
M. Gandhi
M. K. Gandhi
-----Explanation-----
The examples are already explained in the problem statement.
|
# 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 input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of weights on the array. The second line contains N space-separated integers A1, A2, ..., AN denoting the weights
-----Output-----
For each test case, output a single line containing the index of the first balance point. If no such index exists, output -1
-----Constraints-----
For Subtask 1:
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10
- -1000 ≤ A1, A2, ..., AN ≤ 1000
For Subtask 1:
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 1000
- -10000 ≤ A1, A2, ..., AN ≤ 10000
-----Example-----
Input:
2
7
7 8 9 1 9 8 7
6
1 100 50 -51 1 1
Output:
3
1
-----Explanation-----
Example case 1. In the first case, at the midpoint of the array 1, the sum of the left side {7,8,9} is equal to the sum of the right side {9,8,7}
Example case 1. In the second case, at index 1, the sum of left side =1 is equal to the sum of the right side {50,-51,1,1}
|
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:
for i in range(1, n - 1):
if(s1[i - 1] == s2[i + 1]):
print(i)
ch = 1
break
if(ch == 0):
if(n == 1):
print(0)
else:
print(-1)
|
|
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$ ($1 \leq i \leq N$)
- Choose another integer $j \space \space \{ (i \neq j) \text{ and } (1 \leq j \leq N) \}$
- Make an edge between $V_i$ and $V_j$
- Set $i = j$
- Repeat steps $2, 3$ and $4$ in order $M-1$ more times.
Find the number of ways in which Chef can construct a Love Graph. Since the answer can be very large, compute it modulo $10^9+7$.
-----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 two space-separated integers $N$ and $M$.
-----Output-----
For each test case, print a single line containing one integer — the number of ways in which Chef can construct a Love Graph modulo $10^9+7$.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $2 \leq N \leq 10^9$
- $1 \leq M \leq 10^{18}$
-----Subtasks-----
- 30 points:
- $1 \leq T \leq 100$
- $2 \leq N \leq 10$
- $1 \leq M \leq 10$
- 70 points: original constraints
-----Sample Input-----
1
2 1
-----Sample Output-----
2
-----Explanation-----
There are two ways of constructing Love Graph.
In first way, we pick Vertex 1 and then join with Vertex 2.
In second way, we pick Vertex 2 and then join with Vertex 1.
|
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]
w=(n*(fastpow(n-1,r)))%((10**9)+7)
print(w)
|
|
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$ people per day. Anyone whose age is $\ge 80$ or $\le 9$ is considered to be at risk. On each day, you may not vaccinate both a person who is at risk and a person who is not at risk. Find the smallest number of days needed to vaccinate everyone.
-----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 two space-separated integers $N$ and $D$.
- The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$.
-----Output-----
For each test case, print a single line containing one integer ― the smallest required number of days.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^4$
- $1 \le D \le 10^5$
- $1 \le a_i \le 100$ for each valid $i$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
2
10 1
10 20 30 40 50 60 90 80 100 1
5 2
9 80 27 72 79
-----Example Output-----
10
3
-----Explanation-----
Example case 1: We do not need to worry about how the people are grouped, since only one person can be vaccinated in a single day. We require as many days as there are people.
Example case 2: There are two people at risk and three people who are not at risk. One optimal strategy is to vaccinate the two people at risk on day $1$ and the remaining three on the next $2$ days.
|
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_norm=norm//d
else:
days_norm=(norm//d)+1
print(days_risk+days_norm)
|
|
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.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, two integers $N, K$.
-----Output:-----
For each test case, output in a single line answer as Maximum sweetness the chef will have.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$
- $1 \leq K \leq 10^5$
-----Sample Input:-----
2
1 2
4 3
-----Sample Output:-----
2
6
-----EXPLANATION:-----
For 1) Chef will get only 1 laddu with sweetness 2.
For 2) Chef will have multiple ways as
[1,3], [2,4], [1,4] with sweetness 6
[1],[2],[3],[4] with sweetness 3.
Maximum sweetness will be 6.
|
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 prices are also displayed, Now Vishal is asking for your help to buy gifts, as he wants to impress Annabelle this time.
Note: Vishal cannot buy the same item more than once.
-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains a single integer $N$. $N$ denotes the total number of items in store.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes the price of $ith$ element.
-----Output:-----
- For each test-case print "Accepted"(without quotes) if the gifts are accepted by Annabelle, else print "Rejected"(without quotes)
-----Constraints:-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^5$
- $1 \leq A1, A2, A3...An \leq 10^7$
-----Sample Input:-----
1
5
10 2 1000 50 1000
-----Sample Output:-----
Accepted
-----Explanation:-----
- As the given list of items have 2 items whose price sum up to the age times 100 of Annabelle i.e. 1000+1000 = (20 *100)
|
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:
ANS.append("Rejected")
for ans in ANS:
print(ans)
|
|
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 find the minimum sum of two distinct numbers x and y such that x, y > 0 and xy = N.
-----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.
Each testcase contains single integer N.
-----Output:-----
For each testcase, output minimum x + y such that x*y = N and x,y >0.
-----Constraints :-----
$1 \leq T \leq 100$
$1 < N \leq 10^{12}$
-----Sample Input:-----
1
852140
-----Sample Output:-----
1929
|
# 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 <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
t=int(input())
for i in range(0,t):
n=int(input())
if n==1:
print("2")
continue
if isPrime(n):
print(n+1)
continue
if n%2==0:
k=n//2
min=2+k
else:
min=n+1
for j in range(2,(n//2)+1):
if n%j==0:
k=n//j
if k!=j:
l=j+k
if l<min:
min=l
print(min)
|
|
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 position X so King (i.e. You) needs to decide the order of his backward or forward step in such a way that he can reach its destination in minimum number of steps. Remember he always travels in a straight line and the length of the board is infinite.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases, for each test case enter value X ( i.e. destination)
Note : initially knight is at n = 1.
-----Output-----
For each test case the output should be string of numbers 1 & 2 where 1 denotes backward step and 2 denote the forward step
Note : for no solution print 0.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ X ≤ 10^10
-----Example-----
Input:
2
17
10
Output:
2111
0
-----Explanation-----
Case 1 : starting from n = 1 , knight moves to n = 3 ('2') , 5 ('1') , 9 ('1') , 17 ('1') i.e. string printed is 2 1 1 1
Case 2 : no solution is possible
|
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:
s=s+"2"
clv=clv+1
cno=(2*cno)+1
a.append(s)
for i in a:
print(i)
|
|
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 well as areas of Thailand, Laos and Burma which have significant Chinese populations. Chopsticks are most commonly made of wood, bamboo or plastic, but in China, most are made out of bamboo. Chopsticks are held in the dominant hand, between the thumb and fingers, and used to pick up pieces of food.]
Retrieved from wikipedia
Actually, the two sticks in a pair of chopsticks need not be of the same length. A pair of sticks can be used to eat as long as the difference in their length is at most D. The Chef has N sticks in which the ith stick is L[i] units long. A stick can't be part of more than one pair of chopsticks. Help the Chef in pairing up the sticks to form the maximum number of usable pairs of chopsticks.
-----Input-----
The first line contains two space-separated integers N and D. The next N lines contain one integer each, the ith line giving the value of L[i].
-----Output-----
Output a single line containing the maximum number of pairs of chopsticks the Chef can form.
-----Constraints-----
- 1 ≤ N ≤ 100,000 (10 5 )
- 0 ≤ D ≤ 1,000,000,000 (10 9 )
- 1 ≤ L[i] ≤ 1,000,000,000 (10 9 ) for all integers i from 1 to N
-----Example-----
Input:
5 2
1
3
3
9
4
Output:
2
-----Explanation-----
The 5 sticks have lengths 1, 3, 3, 9 and 4 respectively. The maximum allowed difference in the lengths of two sticks forming a pair is at most 2.
It is clear that the 4th stick (length 9) cannot be used with any other stick.
The remaining 4 sticks can can be paired as (1st and 3rd) and (2nd and 5th) to form 2 pairs of usable chopsticks.
|
# 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, size of string.
- Second line of each testcase contains string S.
-----Output:-----
For each test case, print a single line containing one integer ― the minimum number of characters needed(can be 0) to make it palindrome.
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$
-----Sample Input:-----
3
1
a
9
abbbcbddd
6
abcdef
-----Sample Output:-----
0
2
5
-----EXPLANATION:-----
- Example case 1: a is already a palindrome.
- Example case 2: abbddcddbba is palindrome by adding 2 more characters.
- Example case 3: abdefcfedba is palindrome by adding 5 more characters.
|
# 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)
odd_counts += count%2
print(max(odd_counts-1, 0))
|
|
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. He then takes the remaining Circles and repeats the procedure. A square of side $S$ requires $S^2$ Circles to create.
Find the number of squares he will be able to form at the end of the process.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single integer $N$.
-----Output:-----
For each testcase, output a single integer denoting the number of squares.
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 1000$
-----Sample Input:-----
2
85
114
-----Sample Output:-----
2
4
-----EXPLANATION:-----
Test case 1 : Mr Sphere forms a square of side 9 using 81 Circles and then forms a square of side 2 using the remaining 4.
|
# 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:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of Each Test Case is $N, M$, denoting the number of shops and the number of roads respectively.
- Next M lines consist of two integers $A$ and $B$ denoting that there exists a road between Shop A and Shop B
-----Output:-----
For each testcase, output the number of markets.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N,M \leq 10^3$
- $0 \leq A,B < N$
-----Sample Input:-----
1
5 3
0 1
2 3
3 4
-----Sample Output:-----
2
|
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()))
d = {}
for i in range(m):
u, v = list(map(int, stdin.readline().split()))
if u in d:
d[u].append(v)
else:
d[u] = [v]
if v in d:
d[v].append(u)
else:
d[v] = [u]
visited = {}
for i in range(n):
visited[i] = 0
ans = 0
for i in range(n):
if visited[i] == 0:
ans += 1
if i in d:
dfs(i, visited)
print(ans)
|
|
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 number. Also remember that numbers can be duplicate. Can you help out Chef in finding the imposter?
Input :
First line contains the value of N. Second line contains the N numbers that Chef’s friends used as their names. Third line contains the N+1 numbers that people in the game have used as their names.
Output :
Print the extra number in new line.
Constraints :
1 ≤ Numbers used as names ≤ 1,000
1 ≤ N ≤ 1,000,000
Sample Input :
3
4 2 5
4 2 3 5
Sample Output :
3
|
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 two regions may overlap”. You have been asked to remove some regions from the “deployment area” so the remaining regions do not obscure each other. To keep the disturbance to the minimum level, you should remove the minimum number of regions to achieve this goal. You may not remove a region and place it in another position; all regions you leave in “deployment area” must be in their original position.
When you examined the “deployment area”, you noticed something very nice. Every region was placed on the deployment area by placing each autobot in the four corners. This was done in a very courteous manner since each autobot is guarding only the region it is holding.
The reason Optimus Prime wants your help because you are good at taking down a single region without disturbing the rest, even if that region is obscured by many others.
-----Input-----
The first line consists of a single integer T indicating the number of test cases (about 25).
Each test case consists begins with a single integer n indicating the number of regions. The next n lines consist of 4 integers x0, x1, y0, and y1 satisfying x0 < x1 and y0 < y1. This means the region covers all points (x,y) satisfying x0 <= x <= x1 and y0 <= y <= y1.
As stated before hand, no corner of any region will intersect any other region anywhere. That is, if (x,y) is a corner point of one region and another region is described by x0, x1, y0, and y1, then we do not have x0 <= x <= x1 and y0 <= y <= y1.
Bounds: 1 <= n <= 100 and each integer in a region description fits in a signed 32 bit integer.
-----Output-----
The output for each test case is a single line containing a single integer that is the maximum number of regions that can be left on the wall such that no two regions share a common point in the deployment area.
-----Example-----
Input:
1
4
0 4 0 4
1 3 1 2
2 3 1 3
3 4 1 3
Output:
2
|
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 the given string or -1 depending on conditions, in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- -20 ≤ N ≤ 20
-----Example-----
Input
3
1
12
-5
Output
Thanks for helping Chef!
-1
Thanks for helping Chef!
|
# 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 sequence if the heights of tree first increases or decreases, then alternates between decreasing/increasing respectively. Formally, the trees will be said to in Zig-zag sequence if one of the following two conditions holds.
- h1 < h2 > h3 < h4 and so on..
- h1 > h2 < h3 > h4 and so on..
Chef wants to know intervals of time when the heights of the trees will form a zig-zag sequence.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer n, denoting the number of trees.
The ith of following N lines contains two space separated integers hi and mi, denoting the initial height and the growth speed for ith tree.
-----Output-----
For each test case, output an integer Q - the amount of the periods of consecutive moments of time, when the trees for a zig-zag sequence.
On the following Q lines, output the intervals of time when the trees' heights form a zig-zag sequence. For each intervals, output its' smallest and the largest instants of time. If the range is infinite, output Inf as the right bound.
The test cases are designed in such a way that the total output won't exceed 2 MB.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 10
- Subtask 1 (23 points): 0 ≤ hi, mi ≤ 10
- Subtask 2 (77 points): 0 ≤ hi, mi ≤ 109
- 1 ≤ sum of n over a test cases in a single test file ≤ 5 × 105
-----Example-----
Input:3
3
0 1
2 2
0 3
2
2 1
1 2
3
1 1
2 2
3 3
Output:1
0 1
2
0 0
2 Inf
0
-----Explanation-----
Example case 1. In the first case 0 2 0 is already a zig-zag sequence, but on the 2nd second it will become 2 6 6 and will never turn back into zig-zag
|
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,10**20)]
elif(h1==h2):
if (m1 > m2):
l1 += [(1,10**20)]
l2 += [(-1,-1)]
elif(m1==m2):
l1 += [(-1,-1)]
l2 += [(-1,-1)]
else:
l2 += [(1,10**20)]
l1 += [(-1,-1)]
else:
if (m1 <= m2):
l2 += [(0,10**20)]
l1 += [(-1,-1)]
else:
d = (h2-h1)//(m1-m2)
if ((h2-h1)%(m1-m2) == 0):
l2 += [(0,d-1)]
l1 += [(d+1,10**20)]
else:
l2 += [(0,d)]
l1 += [(d+1,10**20)]
i += 1
h1,m1 = h2,m2
return l1,l2
def intersect(k1,k2):
k1,k2 = min(k1,k2),max(k1,k2)
c1,c2 = k1
c3,c4 = k2
l = [c1,c2,c3,c4]
l.sort()
if (l[2]==c2):
return (c3,min(c2,c4))
elif (l[3]==c2):
return k2
else:
return (-1,-1)
def union(k1,k2):
k1,k2 = min(k1,k2),max(k1,k2)
c1,c2 = k1
c3,c4 = k2
l = [c1,c2,c3,c4]
l.sort()
if (c2==l[3]):
return ([c1,c2])
elif(c2==l[2] or ((c3-c2) == 1)):
return([c1,c4])
else:
return([c1,c2,c3,c4])
def aa(l1,l2,n):
c1,c2 = 0,10**20
i = 0
n -= 1
while (i < n):
if (i%2 == 0):
k1,k2 = l1[i]
else:
k1,k2 = l2[i]
i += 1
if ((k1,k2) == (-1,-1)):
return (-1,-1)
c1,c2 = intersect((c1,c2),(k1,k2))
if ((c1,c2) == (-1,-1)):
return (c1,c2)
return (c1,c2)
test = int(input())
while (test != 0):
test -= 1
n = int(input())
l = []
i = 0
while (i < n):
c1,c2 = list(map(int,input().split()))
l += [(c1,c2)]
i += 1
if (n == 1):
print(1)
print("0 Inf")
else:
l1,l2 = (get(l,n))
k1,k2 = aa(l1,l2,n)
if ((k1,k2) == (-1,-1)):
k1,k2 = aa(l2,l1,n)
if ((k1,k2) == (-1,-1)):
print(0)
else:
print(1)
if (k2 == 10**20):
k2 = "Inf"
print(str(k1) + " " +str(k2))
else:
k3,k4 = aa(l2,l1,n)
if ((k3,k4) == (-1,-1)):
print(1)
if (k2 == 10**20):
k2 = "Inf"
print(str(k1) + " " +str(k2))
else:
p = union((k1,k2),(k3,k4))
if (len(p)==2):
c1,c2 = p
if (c2==10**20):
c2 = "Inf"
print(1)
print(str(c1) + " " +str(c2))
else:
c1,c2,c3,c4 = p
if (c4 == 10**20):
c4 = "Inf"
print(2)
print(str(c1) + " " +str(c2))
print(str(c3) + " " +str(c4))
|
|
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 mongoose.
You might have heard about the age-old rivalry between hares and tortoises, but in Snakeland, the rivalry between snakes and mongooses is much more famous. The snakes and the mongooses want to hold a final poll in which the ultimate winner of this age-old battle will be decided. If the snakes get more votes than the mongooses, they will be the ultimate winners. Similarly, if the mongooses get more votes than snakes, they will be the ultimate winners. Obviously, each animal is loyal to their species, i.e. each snake will vote for the snakes to be the ultimate champions and each mongoose for the mongooses.
Tomorrow's the election day. Before the elections, the mongooses decided to cheat. They planned that each mongoose will eat at most one of its neighbor snakes. Two animals are said to be neighbors of each other if they are consecutive to each other in the row. After this, the elections will be held. The mongooses planned in such a way that the number of snakes eaten is maximized. Can you find out who will win the final poll? Output "snakes", "mongooses" or "tie" correspondingly.
-----Input-----
First line of the input contains an integer T denoting the number of test cases. The description of T test cases follow.
The only line of each test case contains a string consisting of characters 's' and 'm'.
-----Output-----
For each test case output a single line containing "snakes", "mongooses" or "tie" correspondingly (without quotes).
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ |s| ≤ 100
-----Example-----
Input
4
sm
ssm
sms
ssmmmssss
Output
mongooses
tie
tie
snakes
-----Explanation-----
Example 1. The mongoose will eat the snake. Only the mongoose will be left. So, on the election day, there is one mongoose and zero snakes. So mongooses will win.
Example 2. The mongoose will eat the snake at position 2 (1-based indexing). One mongoose and one snake will be left. Hence, there will be a tie.
Example 3. The mongoose can eat either the snake to its left or to the right. But, it can eat only one of them. Afterwards, there will be a single snake and mongoose. So, it will result in a tie.
Example 4. The mongooses can eat at max two snakes. For example, s*mmm*sss, where * denotes the snakes that were eaten by mongooses. After this, we have four snakes and three mongooses. So, the snakes win.
|
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')
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 22