Solve in Python:
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.

The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.

You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.

-----Input-----

First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≤ n ≤ 1000), the number of days.

Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.

The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.

-----Output-----

Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.

-----Examples-----
Input
ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler

Output
ross rachel
joey rachel
joey phoebe
joey monica
joey chandler

Input
icm codeforces
1
codeforces technex

Output
icm codeforces
icm technex

-----Note-----

In first example, the killer starts with ross and rachel.   After day 1, ross is killed and joey appears.  After day 2, rachel is killed and phoebe appears.  After day...

a=input().split()
n=int(input())
for i in range(n):
    print(a[0],a[1])
    s1,s2=input().split()
    a[a.index(s1)]=s2
print(a[0],a[1])


Solve in Python:
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.

Your job is to replicate this!

---

**Step 1: Transcription**

Your input will be a string of DNA that looks like this:

`"TACAGCTCGCTATGAATC"`

You then must transcribe it to mRNA. Each letter, or base, gets transcribed.

```T -> A
A -> U
G -> C
C -> G```

Also, you will split it into groups of three, or _codons_.

The above example would become:

`"AUG UCG AGC GAU ACU UAG"`

---

**Step 2: Translation**

After you have the mRNA strand, you will turn it into an amino acid chain.

Each codon corresponds to an amino acid:

```
Ala     GCU, GCC, GCA, GCG
Leu     UUA, UUG, CUU, CUC, CUA, CUG
Arg     CGU, CGC, CGA, CGG, AGA, AGG
Lys     AAA, AAG
Asn     AAU, AAC
Met     AUG
Asp     GAU, GAC
Phe     UUU, UUC
Cys     UGU, UGC
Pro     CCU, CCC, CCA, CCG
Gln     CAA, CAG
Ser     UCU, UCC, UCA, UCG, AGU, AGC
Glu     GAA, GAG
Thr     ACU, ACC, ACA, ACG
Gly     GGU, GGC, GGA, GGG
Trp     UGG
His     CAU, CAC
Tyr     UAU, UAC
Ile     AUU, AUC, AUA
Val     GUU, GUC, GUA, GUG
Stop   UAG, UGA, UAA```

Phew, that's a long list!

The above example would become:

`"Met Ser Ser Thr Asp Stop"`

Any additional sets of bases that aren't in a group of three aren't included. For example:

`"AUG C"`

would become

`"Met"`

---

Anyway, your final output will be the mRNA sequence and the polypeptide.

Here are some examples:

*In:*

`"TACAGCTCGCTATGAATC"`

*Out:*

`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`

---

*In:*

`"ACGTG"`

*Out:*

`["UGC AC","Cys"]`

def protein_synthesis(dna):
    rna = ""
    protein = ""
    for i in range(len(dna)):
        if i % 3 == 0 and i != 0:
            rna += " "
        if dna[i] == "C":
            rna += "G"
        elif dna[i] == "G":
            rna += "C"
        elif dna[i] == "T":
            rna += "A"
        elif dna[i] == "A":
            rna += "U"
    rna_list = rna.split(" ")
    for element in rna_list:
        if len(element) == 3:
            protein += CODON_DICT[element] + " "
    return (rna, protein.strip())


Solve in Python:
Our chef has been assigned a task to make a necklace of length N, from gold, diamond and platinum.There is single kind of gold, two types of diamond and three types of platinum available.
A necklace can be represented as strings of the form (G)∗(D1|D2)∗(P1|P2|P3)∗$ (G)*(D1|D2)*(P1|P2|P3)* $ where (x|y) means we can use x or y and ∗$ * $ means we can repeat the previous parenthesized expression 0 or more times.
Instead of making necklace he choose to count all such distinct necklaces possible for a given length N.

-----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.
-Only line of every test case contains an integer N$N$ denoting the length of the necklace required.

-----Output:-----
For each test case, print the number of all such distinct necklaces, with given length. As the number can be really large, print it modulo  109+7$10^{9}+7$.

-----Constraints-----
- 1≤T≤10000$1 \leq T \leq 10000$
- 2≤N≤1000000000$2 \leq N \leq 1000000000$
- String S$S$ consists of only upper case english alphabets.

-----Subtasks-----
- 20 points : 1≤N≤5$1 \leq N \leq 5$
- 70 points : Original$Original$ Constraints$Constraints$

-----Sample Input:-----
2
1
2

-----Sample Output:-----
6
25


Solve in Python:
Our chef has recently opened a new restaurant with a unique style. The restaurant is divided into K compartments (numbered from 1 to K) and each compartment can be occupied by at most one customer.
Each customer that visits the restaurant has a strongly preferred compartment p (1 ≤ p ≤ K), and if that compartment is already occupied, then the customer simply leaves. Now obviously, the chef wants to maximize the total number of customers that dine at his restaurant and so he allows (or disallows) certain customers so as to achieve this task. You are to help him with this.
Given a list of N customers with their arrival time, departure time and the preferred compartment, you need to calculate the maximum number of customers that can dine at the restaurant.

-----Input-----
The first line contains an integer T denoting the number of test cases. Each of the next T lines contains two integers N and  K , the number of customers that plan to visit the chef's restaurant and the number of compartments the restaurant is divided into respectively. Each of the next N lines contains three integers si, fi and pi , the arrival time, departure time and the strongly preferred compartment of the ith customer respectively.

Note that the ith customer wants to occupy the pith compartment from [si, fi)  i.e the ith customer leaves just before   fi  so that another customer can occupy that compartment from   fi  onwards.

-----Output-----
For every test case, print in a single line the maximum number of customers that dine at the restaurant.

-----Constraints-----
-  1 ≤  T ≤   30
-  0  ≤ N  ≤  105
-  1  ≤  K  ≤  109
-  0  ≤  si < fi ≤   109
-  1  ≤  pi  ≤  K

-----Example-----
Input:
2
3 3
1 3 1
4 6 2
7 10 3
4 2
10 100 1
100 200 2
150 500 2
200 300 2

Output:
3
3

-----Explanation-----
Example case 1.

All three customers want different compartments and hence all 3 can be accommodated.

Example case 2.

If we serve the 1st, 2nd and 4th customers, then we can get a maximum of 3.

t=int(input())
for _ in range (t):
 n,k=map(int,input().split())
 d={}
 for i in range(n):
  s,f,p=map(int,input().split())
  try:
   d[p].append((f,s))
  except:
   d[p]=[(f,s)]
 ans=0
 for i in d:
  d[i].sort()
  start=-1
  for j in d[i]:
   if j[1]>=start:
    ans+=1
    start=j[0]
 print(ans)


Solve in Python:
Our football team finished the championship.
The result of each match look like "x:y". Results of all matches are recorded in the collection.

For example:
```["3:1", "2:2", "0:1", ...]```

Write a function that takes such collection and counts the points of our team in the championship.
Rules for counting points for each match:
- if x>y - 3 points
- if x<y - 0 point
- if x=y - 1 point

Notes:
- there are 10 matches in the championship
- 0 <= x <= 4
- 0 <= y <= 4

def points(games):
    points = 0

    for v in games:
        x = int(v[0])
        y = int(v[2])
        if x > y:
            points += 3
        elif x == y:
            points += 1

    return points


Solve in Python:
Our friendly friend Pete is really a nice person, but he tends to be rather... Inappropriate.

And possibly loud, if given enough ethanol and free rein, so we ask you to write a function that should take its not always "clean" speech and cover as much as possible of it, in order not to offend some more sensible spirits.

For example, given an input like
```
What the hell am I doing here? And where is my wallet? PETE SMASH!
```
You are expected to turn it into something like:
```
W**t t*e h**l am i d***g h**e? A*d w***e is my w****t? P**e s***h!
```
In case you didn't figure out the rules yet: any words longer than 2 characters need to have its "inside" (meaning every character which is not the first or the last) changed into `*`;  as we do not want Pete to scream too much, every uppercase letter which is not at the beginning of the string or coming after a punctuation mark among [".","!","?"] needs to be put to lowercase; spaces and other punctuation marks can be ignored.

Conversely, you need to be sure that the start of each sentence has a capitalized word at the beginning. Sentences are divided by the aforementioned punctuation marks.

Finally, the function will take an additional parameter consisting of an array/list of allowed words (upper or lower case) which are not to be replaced (the match has to be case insensitive).

Extra cookies if you can do it all in some efficient way and/or using our dear regexes ;)

**Note:** Absolutely not related to [a certain codewarrior I know](http://www.codewars.com/users/petegarvin1) :p

import re
def pete_talk(*args):
    speech = args[0].lower()
    permitted = args[1] if len(args) == 2 else []
    speech = re.sub('([!\?\.] )(\w+)', upper, speech)
    speech = re.sub('^(\w)', upper, speech)
    speech = re.sub('(\w{3,})', lambda match: bleep(match, permitted), speech)
    return speech

def bleep(match, perm):
    st = match.group(1)
    bleeped = st[0] + ('*' * (len(st) - 2)) + st[-1]
    return bleeped if st.lower() not in [x.lower() for x in perm] else st

def upper(match):
    groups = list(match.groups())
    groups[-1] = groups[-1].capitalize()
    return ''.join(groups)


Solve in Python:
Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given `["apple","rottenBanana","apple"]` the replaced array should be `["apple","banana","apple"]`. Your task is to implement a method that accepts an array of strings containing fruits should returns an array of strings where all the rotten fruits are replaced by good ones.

### Notes

- If the array is null/nil/None or empty you should return empty array (`[]`).
- The rotten fruit name will be in this camelcase (`rottenFruit`).
- The returned array should be in lowercase.

import re
rotten_pattern = re.compile("rotten")

def remove_rotten(bag_of_fruits):
  return [re.sub(rotten_pattern, "", fruit.lower()) for fruit in bag_of_fruits] if bag_of_fruits else []


Solve in Python:
Pair of gloves
=============

Winter is coming, you must prepare your ski holidays. The objective of this kata is to determine the number of pair of gloves you can constitute from the gloves you have in your drawer.

A pair of gloves is constituted of two gloves of the same color.

You are given an array containing the color of each glove.

You must return the number of pair you can constitute.

You must not change the input array.

Example :
```python
my_gloves = ["red","green","red","blue","blue"]
number_of_pairs(my_gloves) == 2;// red and blue

red_gloves = ["red","red","red","red","red","red"];
number_of_pairs(red_gloves) == 3; // 3 red pairs
```

from collections import Counter

def number_of_pairs(gloves):
    return sum(v // 2 for v in Counter(gloves).values())


Solve in Python:
Pankaj likes to eat Ice cream when he is working late into the night. Today has been yet another long day for Pankaj. So, he wants to eat ice cream now. He opens the fridge and sees that he has 2 types of containers holding the ice cream.
The first container is a cone with radius r1 and height h1. There is also a hemisphere on the top of the cone which has the same radius. The other container is a cylindrical with radius r2 and height h2. Pankaj wants to know the amount (volume) of ice cream in both the containers. Since Pankaj is tired after coding all day, you have to help him 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.
- Each test case consists of a single line having the r1, h1, r2 and h2. Each value is given upto 2 decimal places. See example for more information.

-----Output-----
- For each test case, output a single line containing the volumes of the two containers separated by space. The answer is considered correct if it is correct upto 6 decimal places.

-----Constraints-----
- 1 ≤ T ≤ 100
- 0 <  r1, h1, r2, h2 ≤ 100

-----Example-----
Input:
2
1.00 1.00 1.00 1.00
3.02 7.23 5.20 6.00

Output:
3.141592654 3.141592654
126.739919445 509.691992118

import math
pi=math.pi
#print pi
t=eval(input())
while(t!=0):
    a=list(map(float,input().split(' ')))
    vc=pi/3*(a[0]*a[0]*a[1]+2*a[0]*a[0]*a[0])
    vp=pi*a[2]*a[2]*a[3]
    print("%.10f %.10f"%(vc,vp))
    t=t-1


Solve in Python:
Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule)

The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoidal rules averages those approximations! The same assumptions exist but are pasted here for convenience.

- f will always take a single float argument
- f will always be a "nice" function, don't worry about NaN
- n will always be a natural number (0, N]
- b > a
- and n will be chosen appropriately given the length of [a, b] (as in I will not have step sizes smaller than machine epsilon)
- *!!! round answers to the nearest hundredth!!!*

def riemann_trapezoidal(f, n, a, b):
    delta_x = (b - a)/float(n)
    middle_height = lambda i: (f(a + i * delta_x) + f(a + (1 + i) * delta_x))/2
    arr = map(middle_height, xrange(n))
    return round(sum(arr) * delta_x, 2)


Solve in Python:
Part of Series 2/3

This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-for-real).

In this kata you have to write a Morse code decoder for wired electrical telegraph.

Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key).

When transmitting the Morse code, the international standard specifies that:
"Dot" – is 1 time unit long.
"Dash" – is 3 time units long.
Pause between dots and dashes in a character – is 1 time unit long.
Pause between characters inside a word – is 3 time units long.
Pause between words – is 7 time units long.

However, the standard does not specify how long that "time unit" is. And in fact different operators would transmit at different speed. An amateur person may need a few seconds to transmit a single character, a skilled professional can transmit 60 words per minute, and robotic transmitters may go way faster.

For this kata we assume the message receiving is performed automatically by the hardware that checks the line periodically, and if the line is connected (the key at the remote station is down), 1 is recorded, and if the line is not connected (remote key is up), 0 is recorded. After the message is fully received, it gets to you for decoding as a string containing only symbols 0 and 1.

For example, the message HEY JUDE, that is ···· · −·−−   ·−−− ··− −·· · may be received as follows:

1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011

As you may see, this transmission is perfectly accurate according to the standard, and the hardware sampled the line exactly two times per...

from re import split
def decodeBits(bits):
    unit = min([len(s) for s in split(r'0+',bits.strip('0'))] + [len(s) for s in split(r'1+',bits.strip('0'))  if s != ''])
    return bits.replace('0'*unit*7,'   ').replace('0'*unit*3,' ').replace('1'*unit*3,'-').replace('1'*unit,'.').replace('0','')
def decodeMorse(morseCode):
    # ToDo: Accept dots, dashes and spaces, return human-readable message
    return ' '.join(''.join(MORSE_CODE[letter] for letter in word.split(' ')) for word in morseCode.strip().split('   '))


Solve in Python:
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks.
I knew a rating of 100 is pretty good, but never knew what makes up the rating.
So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating

## Formula

There are four parts to the NFL formula:
```python
A = ((Completions / Attempts) - .3) * 5
B = ((Yards / Attempts) - 3) * .25
C = (Touchdowns / Attempt) * 20
D = 2.375 - ((Interceptions / Attempts) * 25)
```
However, if the result of any calculation is greater than `2.375`, it is set to `2.375`. If the result is a negative number, it is set to zero.

Finally the passer rating is: `((A + B + C + D) / 6) * 100`

Return the rating rounded to the nearest tenth.

## Example

Last year Tom Brady had 432 attempts, 3554 yards, 291 completions, 28 touchdowns, and 2 interceptions.
His passer rating was 112.2

Happy coding!

def passer_rating(att, yds, comp, td, ints):
    cap = lambda x: max(0, min(x, 2.375))
    a = cap(((comp / att) - 0.3) * 5)
    b = cap(((yds / att) - 3) * 0.25)
    c = cap((td / att) * 20)
    d = cap(2.375 - ((ints /att) * 25))
    return round((a + b + c + d) / 6 * 100, 1)


Solve in Python:
Patlu has recently got a new problem based on Pallindromes. A Pallindrome is a number that is same from front and back, example $121$ is pallindrome but $123$ is not . He wants to calculate sum of all $N$ digit number which are Pallindromic in nature and divisible by $9$ and does not contain any zero in their decimal representation. As the answer can be very large so print the sum modulo $10^9 + 7$.

-----Input:-----
- First line of input contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains single line of input , one integer $N$.

-----Output:-----
- For each testcase, output in a single line answer having $N$ digits pallindromic string.

-----Constraints-----
- $1\leq T \leq 100$
- $1\leq N \leq 10^5$

-----Sample Input:-----
2
1
2

-----Sample Output:-----
9
99

def getsum(N):
	if N==1:
		return 9
	if N==2:
		return 99
	s = ""
	for i in range(0,N):
		s = s+'5'
	s = int(s)
	if N%2==0:
		s = s*pow(9,N//2-1)
	else:
		s = s*pow(9,N//2)
	return s%(pow(10,9)+7)

def main():
	t = int(input())
	for _ in range(0,t):
		N = int(input())
		result = getsum(N)
		print(result)
def __starting_point():
	main()

__starting_point()


Solve in Python:
Paul is an excellent coder and sits high on the CW leaderboard. He solves kata like a banshee but would also like to lead a normal life, with other activities. But he just can't stop solving all the kata!!

Given an array (x) you need to calculate the Paul Misery Score. The values are worth the following points:

kata = 5
Petes kata = 10
life = 0
eating = 1

The Misery Score is the total points gained from the array. Once you have the total, return as follows:

<40        = 'Super happy!'<70   >=40 = 'Happy!'<100  >=70 = 'Sad!'\>=100       = 'Miserable!'

points = {"life": 0, "eating": 1, "kata": 5, "Petes kata": 10}

def paul(lst):
    score = sum(points[activity] for activity in lst)
    return "Super happy!" if score < 40 else "Happy!" if score < 70 else "Sad!" if score < 100 else "Miserable!"


Solve in Python:
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.

Strictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$, where $(x_1, y_1)$ and $(x_2, y_2)$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.

After taking the photo, Pavel wrote down coordinates of $n$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.

Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.

Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.

-----Input-----

The first line of the input contains an only integer $n$ ($1 \leq n \leq 100\,000$), the number of points in Pavel's records.

The second line contains $2 \cdot n$ integers $a_1$, $a_2$, ..., $a_{2 \cdot n}$ ($1 \leq a_i \leq 10^9$), coordinates, written by Pavel in some order.

-----Output-----

Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.

-----Examples-----
Input
4
4 1 3 2 3 2 1 3

Output
1
Input
3
5 8 5 5 7 5

Output
0

-----Note-----

In the first sample stars in Pavel's records can be $(1, 3)$, $(1, 3)$, $(2, 3)$, $(2, 4)$. In this case, the minimal area of the rectangle, which contains all these points is $1$ (rectangle with corners at $(1, 3)$ and $(2, 4)$).

import sys
ioRead = sys.stdin.readline
ioWrite = lambda x: sys.stdout.write(f"{x}\n")

n = int(ioRead())
points = sorted(map(int, ioRead().split(" ")))

answer = points[-1] ** 2

for c in range(n):
    axis_1 = [points[c], points[c+n - 1]]
    axis_2 = [points[n if c==0 else 0], points[-1]]
    c_answer = (axis_1[1] - axis_1[0]) * (axis_2[1] - axis_2[0])
    answer = min(answer, c_answer)

ioWrite(answer)


Solve in Python:
People in Karunanagar are infected with Coronavirus. To understand the spread of disease and help contain it as early as possible, Chef wants to analyze the situation in the town. Therefore, he does the following:
- Chef represents the population of Karunanagar as a binary string of length $N$ standing in a line numbered from $1$ to $N$ from left to right, where an infected person is represented as $1$ and an uninfected person as $0$.
- Every day, an infected person in this binary string can infect an adjacent (the immediate left and right) uninfected person.
- Therefore, if before Day 1, the population is $00100$, then at the end of Day 1, it becomes $01110$ and at the end of Day 2, it becomes $11111$.
But people of Karunanagar are smart and they know that if they 'socially isolate' themselves as early as possible, they reduce the chances of the virus spreading. Therefore on $i$-th day, person numbered $P_i$ isolates himself from person numbered $P_i - 1$, thus cannot affect each other. This continues in the town for $D$ days.
Given the population binary string before Day 1, Chef wants to calculate the total number of infected people in Karunanagar at the end of the day $D$. Since Chef has gone to wash his hands now, can you help do the calculation for him?

-----Input:-----
- First line will contain $T$, number of testcases. Then the test cases follow.
- The first line of each test case contains a single integer $N$ denoting the length of the binary string.
- The next line contains a binary string of length $N$ denoting the population before the first day, with $1$ for an infected person and $0$ for uninfected.
- The next line contains a single integer $D$ - the number of days people isolate themselves.
- The next line contains $P$ - a list of $D$ distinct space-separated integers where each $P_{i}$ denotes that at the start of $i^{th}$ day, person $P_{i}$ isolated him/herself from the person numbered $P_i-1$.

-----Output:-----
For each test case, print a single integer denoting the total number of people...

# cook your dish here
T = int(input())

for _ in range(T):

  N = int(input())
  s = list(input())
  n = int(input())
  days = list(map(int,input().split()))
  total_infected = sum(1 for x in s if x == '1')

  def seperate(s,d):
    s.insert(d-1,'#')
    return s

  def infect(s,k,total_infected):
    index_list = set()

    if s[0] == '1' and s[1] == '0':
      s[1] = '1'
      total_infected += 1

    for i in range(1,(N+k)):
      present = s[i]
      prev = s[i-1]
      next = s[i+1]

      if present == '1':
        if prev == '0':
          index_list.add(i-1)
        if next == '0':
          index_list.add(i+1)

    for i in index_list:
      s[i] = '1'
      total_infected += 1
    return (s, total_infected)

  for i in range(n):
    s = seperate(s,i+days[i])
    s,total_infected = infect(s,i,total_infected)

  print(total_infected)


Solve in Python:
Permutation $p$ is a sequence of integers $p=[p_1, p_2, \dots, p_n]$, consisting of $n$ distinct (unique) positive integers between $1$ and $n$, inclusive. For example, the following sequences are permutations: $[3, 4, 1, 2]$, $[1]$, $[1, 2]$. The following sequences are not permutations: $[0]$, $[1, 2, 1]$, $[2, 3]$, $[0, 1, 2]$.

The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $p$ of length $n$.

You don't know this permutation, you only know the array $q$ of prefix maximums of this permutation. Formally:  $q_1=p_1$,  $q_2=\max(p_1, p_2)$,  $q_3=\max(p_1, p_2,p_3)$,  ...  $q_n=\max(p_1, p_2,\dots,p_n)$.

You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $q$ for this permutation is equal to the given array).

-----Input-----

The first line contains integer number $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.

The first line of a test case contains one integer $n$ $(1 \le n \le 10^{5})$ — the number of elements in the secret code permutation $p$.

The second line of a test case contains $n$ integers $q_1, q_2, \dots, q_n$ $(1 \le q_i \le n)$ — elements of the array $q$ for secret permutation. It is guaranteed that $q_i \le q_{i+1}$ for all $i$ ($1 \le i < n$).

The sum of all values $n$ over all the test cases in the input doesn't exceed $10^5$.

-----Output-----

For each test case, print:  If it's impossible to find such a permutation $p$, print "-1" (without quotes).  Otherwise, print $n$ distinct integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$). If there are multiple possible answers, you can print any of them.

-----Example-----
Input
4
5
1 3 4 5 5
4
1 1 3 4
2
2 2
1
1

Output
1 3 4 5 2
-1
2 1
1

-----Note-----

In the first test case of the example answer $[1,3,4,5,2]$ is the only possible answer:  $q_{1} = p_{1} = 1$;  $q_{2} = \max(p_{1}, p_{2}) = 3$;  $q_{3} = \max(p_{1}, p_{2}, p_{3}) = 4$;  $q_{4} =...

from collections import deque
for i in range(int(input())):
    n = int(input())
    h = deque([i+1 for i in range(n)])
    used = [False]*n
    ans = [0]*n
    c = list(map(int,input().split()))
    ans[0] = c[0]
    used[c[0]-1] = True
    f = True
    for i in range(n):
        if i+1>c[i]:
            f = False
    if not f:
        print(-1)
        continue
    for i in range(n-1):
        if c[i+1]!=c[i]:
            ans[i+1] = c[i+1]
        else:
            x = h.popleft()
            while used[x-1]:
                x = h.popleft()
            ans[i+1] = x
        used[ans[i+1] - 1] = True
    print(*ans)


Solve in Python:
Permutation p is an ordered set of integers p_1,   p_2,   ...,   p_{n}, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p_1,   p_2,   ...,   p_{n}.

Your task is to find such permutation p of length n, that the group of numbers |p_1 - p_2|, |p_2 - p_3|, ..., |p_{n} - 1 - p_{n}| has exactly k distinct elements.

-----Input-----

The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 10^5).

-----Output-----

Print n integers forming the permutation. If there are multiple answers, print any of them.

-----Examples-----
Input
3 2

Output
1 3 2

Input
3 1

Output
1 2 3

Input
5 2

Output
1 3 2 4 5

-----Note-----

By |x| we denote the absolute value of number x.

import sys
import math

n, k = [int(x) for x in (sys.stdin.readline()).split()]
res = []

z = 1
for i in range(n, 1, -1):
    if(i > k):
        res.append(str(i))
    else:
        z = i
        break
l = z
j = 1
for i in range(1, z + 1):
    if(i % 2 != 0):
        res.append(str(j))
        j += 1
    else:
        res.append(str(z))
        z -= 1

print(" ".join(res[::-1]))


Solve in Python:
Pete and his mate Phil are out in the countryside shooting clay pigeons with a shotgun - amazing fun.

They decide to have a competition. 3 rounds, 2 shots each. Winner is the one with the most hits.

Some of the clays have something attached to create lots of smoke when hit, guarenteed by the packaging to generate 'real excitement!' (genuinely this happened). None of the explosive things actually worked, but for this kata lets say they did.

For each round you will receive the following format:

[{P1:'XX', P2:'XO'}, true]

That is an array containing an object and a boolean. Pl represents Pete, P2 represents Phil. X represents a hit and O represents a miss. If the boolean is true, any hit is worth 2. If it is false, any hit is worth 1.

Find out who won. If it's Pete, return 'Pete Wins!'. If it is Phil, return 'Phil Wins!'. If the scores are equal, return 'Draw!'.

Note that as there are three rounds, the actual input (x) will look something like this:

[[{P1:'XX', P2:'XO'}, true], [{P1:'OX', P2:'OO'}, false], [{P1:'XX', P2:'OX'}, true]]

def shoot(results):
    score = sum(rnd[f"P{i+1}"].count("X") * (mul + 1) * (-1)**i for i in (0, 1) for rnd, mul in results)
    return "Pete Wins!" if score > 0 else "Phil Wins!" if score < 0 else "Draw!"


Solve in Python:
Peter can see a clock in the mirror from the place he sits in the office.
When he saw the clock shows 12:22

1
2
3
4
5
6
7
8
9
10
11
12

He knows that the time is 11:38

1
2
3
4
5
6
7
8
9
10
11
12

in the same manner:

05:25 --> 06:35

01:50 --> 10:10

11:58 --> 12:02

12:01 --> 11:59

Please complete the function `WhatIsTheTime(timeInMirror)`, where `timeInMirror` is the mirrored time (what Peter sees) as string.

Return the _real_ time as a string.

Consider hours to be between 1 <= hour < 13.

So there is no 00:20, instead it is 12:20.

There is no 13:20, instead it is 01:20.

def what_is_the_time(time_in_mirror):
    hours, minutes = list(map(int, time_in_mirror.split(':')))

    if minutes == 0:
        mirrored_hours = 12 - hours
        mirrored_minutes = 0
    else:
        mirrored_hours = (11 - hours) % 12
        mirrored_minutes = 60 - minutes
    if mirrored_hours == 0:
        mirrored_hours = 12

    return "{:02d}:{:02d}".format(mirrored_hours, mirrored_minutes)


Solve in Python:
Petr is organizing Petr Mitrichev Contest #11. The top N coders according to codechef ratings (excluding Petr himself) agreed to participate in the contest. The participants have been ranked from 0 to N-1 according to their ratings. Petr had asked each participant to choose a coder with rating higher than himself/ herself, whom he/she would like to be team-mates with, and the ith ranked coder's choice is stored as choice[i]. As expected, programmers turned out to be lazy, and only a few of them actually filled in their choices. If choice[i] = -1, then it means the ith coder was lazy and did not fill his/her choice. Of course, the top-ranked person (i.e., rank = 0),  Gennady Korotkevich  (obviously), despite clearly not being a lazy person, was not able to fill any choice, because he is the top ranked coder, so choice[0] is always equal to -1.

Petr, being the organizer, had to undertake the arduous task of filling in the choices for the lazy participants. Unfortunately, he also got lazy and adopted the following random strategy:

For each lazy person i (i.e., for all i > 0, such that choice[i] = -1), he flips an unbiased coin (i.e. with 1/2 probability it lands Heads, and with 1/2 probability it lands Tails). Notice that no coin is flipped for i=0, since Gennady is not lazy despite his choice being -1.

If it lands Heads, he will not change the choice of this person. That is, he leaves choice[i] as -1.

Otherwise, if it lands Tails, he will uniformly at random select one of the top i ranked participants as choice of ith person. That is, he sets choice[i] = j, where j is randomly and uniformly chosen from 0 to i-1, inclusive.

After this process of filling the choice array, Petr is wondering about the maximum number of teams he can have such that all the valid choices are respected (i.e. if choice[i] = j and j != -1, then i and j should be in the same team).

Petr now has to arrange for computers. As each team will need a computer, he wants to know the expected value of maximum number of teams. As he is too...

import math
def comb(n,r):
 f = math.factorial
 return f(n) / f(r) / f(n-r)
t=int(input())
for i in range(1,t+1):
 n=int(input())
 arr = list(map(int, input().split()))
 m=0
 ans=0.0
 for i in range(0,n):
  if (arr[i]==-1):
   m=m+1
 for i in range(0,m):
  ans=ans+((m-i)*comb(m-1,m-1-i))
 ans=ans/pow(2,m-1)
 print('{0:.7f}'.format(ans))


Solve in Python:
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?!

You somehow get a test from one of these problems and now you want to know from which one.

-----Input-----

In the first line of input there is one integer $n$ ($10^{3} \le n \le 10^{6}$).

In the second line there are $n$ distinct integers between $1$ and $n$ — the permutation of size $n$ from the test.

It is guaranteed that all tests except for sample are generated this way: First we choose $n$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.

-----Output-----

If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).

-----Example-----
Input
5
2 4 5 1 3

Output
Petr

-----Note-----

Please note that the sample is not a valid test (because of limitations for $n$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.

Due to randomness of input hacks in this problem are forbidden.

n=int(input())
a=[0]+list(map(int,input().split()))
ans=0
for i in range(1,len(a)):
    if a[i]==-1:
        continue
    j=i
    while a[j]!=-1:
        prev=j
        j=a[j]
        a[prev]=-1
    ans+=1
if n%2==0:
    #n even ans also even even number of swaps required
    #3*n
    if ans%2==0:
        print("Petr")
    else:
        print("Um_nik")
else:
    #n us odd ans is even odd number of swaps required
    if ans%2==0:
        print("Petr")
    else:
        print("Um_nik")


Solve in Python:
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.

The exam consists of $n$ problems that can be solved in $T$ minutes. Thus, the exam begins at time $0$ and ends at time $T$. Petya can leave the exam at any integer time from $0$ to $T$, inclusive.

All problems are divided into two types:   easy problems — Petya takes exactly $a$ minutes to solve any easy problem;  hard problems — Petya takes exactly $b$ minutes ($b > a$) to solve any hard problem.

Thus, if Petya starts solving an easy problem at time $x$, then it will be solved at time $x+a$. Similarly, if at a time $x$ Petya starts to solve a hard problem, then it will be solved at time $x+b$.

For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $t_i$ ($0 \le t_i \le T$) at which it will become mandatory (required). If Petya leaves the exam at time $s$ and there is such a problem $i$ that $t_i \le s$ and he didn't solve it, then he will receive $0$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $t_i \le s$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $s$ Petya can have both "mandatory" and "non-mandatory" problems solved.

For example, if $n=2$, $T=5$, $a=2$, $b=3$, the first problem is hard and $t_1=3$ and the second problem is easy and $t_2=2$. Then:  if he leaves at time $s=0$, then he will receive $0$ points since he will not have time to solve any problems;  if he leaves at time $s=1$, he will receive $0$ points since he will not have time to solve any problems;  if he leaves at time $s=2$, then he can get a $1$ point by solving the problem with the number $2$ (it must be solved in the range from $0$ to $2$);  if he leaves at time $s=3$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $s=4$, then he will...

t = int(input())
for _ in range(t):
    n, T, a, b = list(map(int, input().split(' ')))
    task_t = list(map(int, input().split(' ')))
    ness = list(map(int, input().split(' ')))

    perm = sorted(list(range(n)), key=lambda i: ness[i])

    score = 0
    tot_hard = sum(task_t)
    tot_easy = n - tot_hard

    must_easy = 0
    must_hard = 0
    for i in range(n):
        if i > 0 and ness[perm[i]] == ness[perm[i - 1]]:
            if task_t[perm[i]] == 0:
                must_easy += 1
            else:
                must_hard += 1
            continue

        tm = ness[perm[i]] - 1

        req_time = must_easy * a + must_hard * b

        if req_time > tm:
            if task_t[perm[i]] == 0:
                must_easy += 1
            else:
                must_hard += 1
            continue

        extra_time = tm - req_time
        extra_easy = min(extra_time // a, tot_easy - must_easy)

        extra_time -= a * extra_easy
        extra_hard = min(extra_time // b, tot_hard - must_hard)

        #print(tm, extra_easy, extra_hard, must_easy, must_hard)

        score = max(score, extra_easy + extra_hard + must_easy + must_hard)

        if task_t[perm[i]] == 0:
            must_easy += 1
        else:
            must_hard += 1

    if tot_easy * a + tot_hard * b <= T:
        score = n
    print(score)


Solve in Python:
Petya is preparing a problem for a local contest in his school. The problem is to find a longest increasing subsequence in a given permutation. A permutation of size n$n$ is a sequence of n$n$ numbers a1,…,an$a_1, \ldots, a_n$ such that every number from 1$1$ to n$n$ occurs in the sequence exactly once. An increasing subsequence of length k$k$ of the sequence a1,…,an$a_1, \ldots, a_n$ is a sequence of indices i1,…,ik$i_1, \ldots, i_k$ such that 1≤i1<…<ik≤n$1 \leq i_1 < \ldots < i_k \leq n$ and ai1<…<aik$a_{i_1} < \ldots < a_{i_k}$. A longest increasing subsequence is an increasing subsequences with the largest length. Note that in general there may be several longest increasing subsequences.
Petya had some tests prepared, but then lost the input part for some of them. He now has a test for a certain value of n$n$, and a sequence i1,…,ik$i_1, \ldots, i_k$ that is supposed to be a longest increasing subsequence. Petya now has to reconstruct a permutation of size n$n$ with this sequence being an answer. Petya doesn't want to take any risks, so he additionally wants this sequence to be the only longest increasing subsequence, that is, all other increasing subsequences have to have strictly smaller length. Help Petya determine if this is possible, and if so, construct any such permutation.

-----Input:-----
The first line contains an integer T$T$, denoting number of test cases.
The first line of every test case contains two integers n$n$ and k−$k-$  the size of the permutation and the length of the longest increasing subsequence (1≤k≤n≤105$1 \leq k \leq n \leq 10^5$).
The second line contains k$k$ integers i1,…,ik−$i_1, \ldots, i_k-$ the longest increasing subsequence (1≤i1<…<ik≤n$1 \leq i_1 < \ldots < i_k \leq n$).

-----Output:-----
If there is no permutation with the sequence i1,…,ik$i_1, \ldots, i_k$ being the only longest increasing subsequence, print NO . Otherwise, print YES on the first line, followed by n$n$ numbers describing any suitable permutation on the second line.

-----Constraints-----
- 1≤T≤10$1...

for _ in range(int(input())):
    n,k=map(int,input().split())
    ls=list(map(int,input().split()))
    if n==1:
        print("YES")
        print(1)
        continue
    if k==1:
        print("NO")
        continue

    if k==2 and n>2:
        if ls[0]!=ls[1]-1:
            print("NO")
            continue
    print("YES")
    mx=n
    arr=[0]*(n)
    for i in range(ls[0]-1):
        arr[i]=mx
        mx-=1
    for i in range(ls[0],ls[1]-1):
        arr[i]=mx
        mx-=1
    for i in range(k-1,-1,-1):
        arr[ls[i]-1]=mx
        mx-=1
    for i in range(1,n):
        if arr[i]==0:
            arr[i]=mx
            mx-=1
    print(*arr)


Solve in Python:
Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.

Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $n$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:  the dish will be delivered by a courier from the restaurant $i$, in this case the courier will arrive in $a_i$ minutes,  Petya goes to the restaurant $i$ on his own and picks up the dish, he will spend $b_i$ minutes on this.

Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.

For example, if Petya wants to order $n = 4$ dishes and $a = [3, 7, 4, 5]$, and $b = [2, 1, 2, 4]$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $3$ minutes, the courier of the fourth restaurant will bring the order in $5$ minutes, and Petya will pick up the remaining dishes in $1 + 2 = 3$ minutes. Thus, in $5$ minutes all the dishes will be at Petya's house.

Find the minimum time after which all the dishes can be at Petya's home.

-----Input-----

The first line contains one positive integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. Then $t$ test cases follow.

Each test case begins with a line containing one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of dishes that Petya wants to order.

The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^9$) — the time of courier delivery of the dish with the number $i$.

The third line of each...

import sys

def input():

    return sys.stdin.readline()

for _ in range(int(input())):

    n = int(input())

    A = list(map(int, input().split()))
    B = list(map(int, input().split()))

    x = 10 ** 9
    y = 0
    while x > y + 1:

        z = (x + y) // 2

        t = 0

        for i in range(n):
            if A[i] > z:
                t += B[i]

        if t > z:
            y = z

        else:
            x = z

    print(x)


Solve in Python:
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.

In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.

Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 5·10^5) — the number of lines.

Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant x_{i} 0 ≤ x_{i} ≤ 1023.

-----Output-----

Output an integer k (0 ≤ k ≤ 5) — the length of your program.

Next k lines must contain commands in the same format as in the input.

-----Examples-----
Input
3
| 3
^ 2
| 1

Output
2
| 3
^ 2

Input
3
& 1
& 3
& 5

Output
1
& 1

Input
3
^ 1
^ 2
^ 3

Output
0

-----Note-----

You can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.

Second sample:

Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.

import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii=lambda:int(input())
kk=lambda:map(int, input().split())
ll=lambda:list(kk())

# xor + 0 --> unchanged(2)
# xor + 1 --> flip(3)
# or + 0 --> unchanged(2)
# or + 1 --> 1(1)
# and + 0 --> 0(0)
# and + 1 --> unchanged(2)
arr = [2]*10
for _ in range(ii()):
	s,v=input().split()
	v = int(v)
	if s == b"|":
		for i in range(10):
			if v&(2**i):
				arr[i]= 1
	elif s == b"^":
		for i in range(10):
			if v&(2**i):
				arr[i]^=1
	elif s == b"&":
		for i in range(10):
			if not (v&(2**i)):
				arr[i]=0
	else:
	    print(s)
print(3)
x=o=a= 0
for i in range(10):
	if arr[i]==3: x += 2**i
	elif arr[i]==0: a+=2**i
	elif arr[i]==1:o+=2**i
print('|',o)
print('^',x)
print('&',2**10 - a - 1)


Solve in Python:
Philip's just turned four and he wants to know how old he will be in various years in the future such as 2090 or 3044. His parents can't keep up calculating this so they've begged you to help them out by writing a programme that can answer Philip's endless questions.

Your task is to write a function that takes two parameters: the year of birth and the year to count years in relation to. As Philip is getting more curious every day he may soon want to know how many years it was until he would be born, so your function needs to work with both dates in the future and in the past.

Provide output in this format: For dates in the future: "You are ... year(s) old." For dates in the past: "You will be born in ... year(s)." If the year of birth equals the year requested return: "You were born this very year!"

"..." are to be replaced by the number, followed and proceeded by a single space. Mind that you need to account for both "year" and "years", depending on the result.

Good Luck!

def calculate_age(birthyear, target):
    if birthyear == target:
        return 'You were born this very year!'
    elif birthyear > target:
        return 'You will be born in {} year{}.'.format(birthyear - target, 's' * ((birthyear - target) > 1))
    else:
        return 'You are {} year{} old.'.format(target - birthyear, 's' * ((target - birthyear) > 1 ))


Solve in Python:
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $k$ have the same sum. A subarray of an array is any sequence of consecutive elements.

Phoenix currently has an array $a$ of length $n$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $1$ and $n$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 50$) — the number of test cases.

The first line of each test case contains two integers $n$ and $k$ ($1 \le k \le n \le 100$).

The second line of each test case contains $n$ space-separated integers ($1 \le a_i \le n$) — the array that Phoenix currently has. This array may or may not be already beautiful.

-----Output-----

For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines.

The first line should contain the length of the beautiful array $m$ ($n \le m \le 10^4$). You don't need to minimize $m$.

The second line should contain $m$ space-separated integers ($1 \le b_i \le n$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $a$. You may print integers that weren't originally in array $a$.

If there are multiple solutions, print any. It's guaranteed that if we can make array $a$ beautiful, we can always make it with resulting length no more than $10^4$.

-----Example-----
Input
4
4 2
1 2 2 1
4 3
1 2 2 1
3 2
1 2 3
4 4
4 3 4 2

Output
5
1 2 1 2 1
4
1 2 2 1
-1
7
4 3 2 1 4 3 2

-----Note-----

In the first test case, we can make array $a$ beautiful by inserting the integer $1$ at index $3$ (in between the two existing $2$s). Now, all subarrays of length $k=2$ have the same sum $3$. There exists many other possible solutions, for example:   $2, 1, 2, 1, 2, 1$...

import collections

t=int(input())
for _ in range(t):
    n,k=map(int,input().split())
    arr=list(map(int,input().split()))
    if len(collections.Counter(arr))>k:
        print(-1)
    else:
        cand=list(collections.Counter(arr).keys())
        cnt=len(cand)
        for i in range(1,n+1):
            if cnt>=k:
                break
            else:
                if i not in cand:
                    cand.append(i)
                    cnt+=1
        print(cnt*n)
        print(*(cand*n))


Solve in Python:
Pied Piper is a startup company trying to build a new Internet called Pipernet. Currently, they have $A$ users and they gain $X$ users everyday. There is also another company called Hooli, which has currently $B$ users and gains $Y$ users everyday.
Whichever company reaches $Z$ users first takes over Pipernet. In case both companies reach $Z$ users on the same day, Hooli takes over.
Hooli is a very evil company (like E-Corp in Mr. Robot or Innovative Online Industries in Ready Player One). Therefore, many people are trying to help Pied Piper gain some users.
Pied Piper has $N$ supporters with contribution values $C_1, C_2, \ldots, C_N$. For each valid $i$, when the $i$-th supporter contributes, Pied Piper gains $C_i$ users instantly. After contributing, the contribution value of the supporter is halved, i.e. $C_i$ changes to $\left\lfloor C_i / 2 \right\rfloor$. Each supporter may contribute any number of times, including zero. Supporters may contribute at any time until one of the companies takes over Pipernet, even during the current day.
Find the minimum number of times supporters must contribute (the minimum total number of contributions) so that Pied Piper gains control of Pipernet.

-----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 six space-separated integers $N$, $A$, $B$, $X$, $Y$ and $Z$.
- The second line contains $N$ space-separated integers $C_1, C_2, \ldots, C_N$ — the initial contribution values.

-----Output-----
For each test case, if Hooli will always gain control of Pipernet, print a single line containing the string "RIP" (without quotes). Otherwise, print a single line containing one integer — the minimum number of times supporters must contribute.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^5$
- $1 \le A, B, X, Y, Z \le 10^9$
- $A, B < Z$
- $0 \le C_i \le 10^9$ for each valid $i$

-----Example Input-----
3
3 10 15 5 10 100
12...

# cook your dish here
import heapq
from math import ceil

t= int(input())
for k in range(t):
 n, a, b, x, y, z = list(map(int,input().split()))
 c = list(map(int,input().split()))
 cont = [ -int(x) for x in c]

 days = int((z-b) / y )

 p_user = days * x + a

 need = z - p_user
 flag = 0

 heapq.heapify(cont)
 count = 0
 if ceil(((z-a) - (2*sum(c)))/x) >= days + 1:
  print("RIP")

 elif p_user > z:
  print(0)
 else:
  while( p_user < z):

   key = heapq.heappop(cont)
   if key ==0:
    flag = 1
    break
   count += 1
   p_user += -key
   #print(need,key,cont)
   heapq.heappush(cont,int(key/2))

  if flag == 0:
   print(count)
  else :
   print("RIP")


Solve in Python:
Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules.

So, the goal of this kata is to wite a function that encodes a single word string to pig latin.

The rules themselves are rather easy:

1) The word starts with a vowel(a,e,i,o,u) -> return the original string plus "way".

2) The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus "ay".

3) The result must be lowercase, regardless of the case of the input. If the input string has any non-alpha characters, the function must return None, null, Nothing (depending on the language).

4) The function must also handle simple random strings and not just English words.

5) The input string has no vowels -> return the original string plus "ay".

For example, the word "spaghetti" becomes "aghettispay" because the first two letters ("sp") are consonants, so they are moved to the end of the string and "ay" is appended.

def pig_latin(s):
    a = ''
    if not s.isalpha(): return None
    s = s.lower()
    for i in s:
        if i in 'aeiou':
            break
        a+= i
    return s + 'way' if s[0] in 'aeiou' else s[len(a):] + a + 'ay'


Solve in Python:
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2^{n} - 1 non-empty subsequences in it.

Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ d

Pikachu was finally left with X subsequences.

However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 10^18.

Note the number of elements in the output array should not be more than 10^4. If no answer is possible, print  - 1.

-----Input-----

The only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 10^9).

-----Output-----

Output should consist of two lines.

First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array.

Second line should consist of n space separated integers — a_1, a_2, ... , a_{n} (1 ≤ a_{i} < 10^18).

If there is no answer, print a single integer -1. If there are multiple answers, print any of them.

-----Examples-----
Input
10 5

Output
6
5 50 7 15 6 100
Input
4 2

Output
4
10 100 1000 10000

-----Note-----

In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid.

Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.

x, d = map(int, input().split())

A = []
a = 1
k = 0
while a < x:
    a *= 2
a //= 2
x = bin(x)[2:][::-1]
y = 1
for i in range(len(x)-1, -1, -1):
    if x[i] == '1':
        A += (i) * [y]
        k += 1
    y += d+1

while k:
    A.append(y)
    y += d+1
    k -= 1

print(len(A))
for i in A:
    print(i, end=' ')


Solve in Python:
Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people.

At long last, we need a way to unscramble what these pirates are saying.

Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might have meant.

For example:
```
grabscrab( "ortsp", ["sport", "parrot", "ports", "matey"] )
```

Should return `["sport", "ports"]`.

Return matches in the same order as in the dictionary. Return an empty array if there are no matches.

Good luck!

grabscrab = lambda w,l:[p for p in l if sorted(p)==sorted(w)]


Solve in Python:
Please notice the unusual memory limit of this problem.

Orac likes games. Recently he came up with the new game, "Game of Life".

You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white.

For each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different.

Two cells are adjacent if they have a mutual edge.

Now Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times.

-----Input-----

The first line contains three integers $n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$, representing the number of rows, columns, and the number of Orac queries.

Each of the following $n$ lines contains a binary string of length $m$, the $j$-th character in $i$-th line represents the initial color of cell $(i,j)$. '0' stands for white, '1' stands for black.

Each of the following $t$ lines contains three integers $i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$, representing a query from Orac.

-----Output-----

Print $t$ lines, in $i$-th line you should print the answer to the $i$-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'.

-----Examples-----
Input
3 3 3
000
111
000
1 1 1
2 2 2
3 3 3

Output
1
1
1

Input
5 2 2
01
10
01
10
01
1 1 4
5 1 4

Output
0
0

Input
5 5 3
01011
10110
01101
11010
10101
1 1 4
1 2 3
5 5 3

Output
1
0
1

Input
1 1 3
0
1 1 1
1 1 2
1 1 3

Output
0
0
0

-----Note----- [Image]

For the first example, the picture above shows the initial situation and the color of cells at the iteration $1$, $2$, and $3$. We can see that the color of $(1,1)$ at the iteration...

import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
H, W, T = list(map(int, input().split()))
Y = [[int(a) for a in input()] for _ in range(H)]
Q = deque([])
D = [-1] * (H * W)
for x in range(H * W):
    i, j = x // W, x % W
    y = Y[i][j]
    if (i and Y[i-1][j] == y) or (i < H - 1 and Y[i+1][j] == y) or (j and Y[i][j-1] == y) or (j < W - 1 and Y[i][j+1] == y):
        D[x] = 0
        Q.append(x)

while Q:
    x = Q.popleft()
    i, j = x // W, x % W
    for di, dj in ((0, 1), (0, -1), (1, 0), (-1, 0)):
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W:
            y = ni * W + nj
            if D[y] == -1:
                D[y] = D[x] + 1
                Q.append(y)
if D[0] < 0:
    D = [10 ** 18] * (H * W)

for _ in range(T):
    i, j, p = list(map(int, input().split()))
    i, j = i-1, j-1
    x = i * W + j
    print(Y[i][j] if max(p - D[x], 0) % 2 == 0 else Y[i][j] ^ 1)


Solve in Python:
Please write a function that sums a list, but ignores any duplicate items in the list.

For instance, for the list [3, 4, 3, 6] , the function should return 10.

sum_no_duplicates = lambda L: sum( [n for n in L if L.count(n) == 1] )


Solve in Python:
Polly is 8 years old. She is eagerly awaiting Christmas as she has a bone to pick with Santa Claus. Last year she asked for a horse, and he brought her a dolls house. Understandably she is livid.

The days seem to drag and drag so Polly asks her friend to help her keep count of how long it is until Christmas, in days. She will start counting from the first of December.

Your function should take 1 argument (a Date object) which will be the day of the year it is currently. The function should then work out how many days it is until Christmas.

Watch out for leap years!

import datetime
def days_until_christmas(year):

    k=year.year

    dc=datetime.date(k,12,25)
    r=dc-year

    ret=r.days

    if ret>=0:
        return ret
    else:
        dc=datetime.date(k+1,12,25)
        r=dc-year

        ret=r.days

        return ret


Solve in Python:
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.

t = int(input())

for i in range(t):

  l,r = map(int,input().split())
  start = len(str(l))
  end = len(str(r))
  if end>start:
   end_start = int(str('9'*start))
   sum_start = ((end_start + l)*start*((end_start-l+1)))//2
  else:
      sum_start = ((l+r)*start*(r-l+1))//2

  sum = 0

  # print(sum_start)
  for j in range(start+1,end):
      sum+=((10**(j-1)+(int(str('9'*j))))*j*(((int(str('9'*j))-(10**(j-1))+1))))//2

  if end>start:
   end = len(str(r))
   end__start = int(str(10**(end-1)))
   sum__start = ((end__start + r)*end*(r-end__start+1))//2
  else:
      sum__start = 0
  # print(end__start)
  # print(sum)
  # print(sum,sum__start,sum_start)
  print((sum+sum__start+sum_start)%1000000007)


Solve in Python:
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $n$ last days: $a_1, a_2, \dots, a_n$, where $a_i$ is the price of berPhone on the day $i$.

Polycarp considers the price on the day $i$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $n=6$ and $a=[3, 9, 4, 6, 7, 5]$, then the number of days with a bad price is $3$ — these are days $2$ ($a_2=9$), $4$ ($a_4=6$) and $5$ ($a_5=7$).

Print the number of days with a bad price.

You have to answer $t$ independent data sets.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 10000$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another.

Each input data set consists of two lines. The first line contains an integer $n$ ($1 \le n \le 150000$) — the number of days. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$), where $a_i$ is the price on the $i$-th day.

It is guaranteed that the sum of $n$ over all data sets in the test does not exceed $150000$.

-----Output-----

Print $t$ integers, the $j$-th of which should be equal to the number of days with a bad price in the $j$-th input data set.

-----Example-----
Input
5
6
3 9 4 6 7 5
1
1000000
2
2 1
10
31 41 59 26 53 58 97 93 23 84
7
3 2 1 2 3 4 5

Output
3
0
1
8
2

t = int(input())
while t > 0:
    n = int(input())
    arr = [int(x) for x in input().split()]
    low = arr[n-1]
    bad = 0
    for i in range(n-2, -1, -1):
        if arr[i] > low: bad += 1
        low = min(low, arr[i])
    print(bad)
    t -= 1


Solve in Python:
Polycarp has $n$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".

Polycarp wants to offer his set of $n$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".

Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".

Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:  the final set of $n$ words still contains different words (i.e. all words are unique);  there is a way to put all words of the final set of words in the order so that the final sequence of $n$ words is consistent with the game rules.

Polycarp wants to reverse minimal number of words. Please, help him.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.

The first line of a test case contains one integer $n$ ($1 \le n \le 2\cdot10^5$) — the number of words in the Polycarp's set. Next $n$ lines contain these words. All of $n$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $4\cdot10^6$. All words are different.

Guaranteed, that the sum of $n$ for all test cases in the input doesn't exceed $2\cdot10^5$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $4\cdot10^6$.

-----Output-----

Print answer for all of $t$ test cases in the order they appear.

If there is no answer for the test case, print -1. Otherwise, the first...


Solve in Python:
Polycarp is making a quest for his friends. He has already made n tasks, for each task the boy evaluated how interesting it is as an integer q_{i}, and the time t_{i} in minutes needed to complete the task.

An interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with "yes" or "no". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks.

We know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than T minutes. Polycarp wants to choose some of the n tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most T minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).

Polycarp wants the total "interest" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in T minutes at any variant of answering questions.

-----Input-----

The first line contains two integers n and T (1 ≤ n ≤ 1000, 1 ≤ T ≤ 100) — the number of tasks made by Polycarp and the maximum time a quest player should fit into.

Next n lines contain two integers t_{i}, q_{i} (1 ≤ t_{i} ≤ T, 1 ≤...

from collections import defaultdict

def __starting_point():
    n, T = [int(_) for _ in input().split()]
    data = defaultdict(list)
    for i in range(n):
        t, q = [int(_) for _ in input().split()]
        data[T - t].append(q)

    prev_level = []
    for level_id in range(1, T + 1):
        level = sorted(data[T - level_id] + prev_level, reverse=True)
        if T - level_id <= 10:
            max_size = 2 ** (T - level_id)
            level = level[:max_size]
        if len(level) % 2 == 1:
            level.append(0)
        prev_level = [
            level[i] + level[i + 1]
            for i in range(0, len(level), 2)
        ]
    print(prev_level[0])

__starting_point()


Solve in Python:
Polycarp is reading a book consisting of $n$ pages numbered from $1$ to $n$. Every time he finishes the page with the number divisible by $m$, he writes down the last digit of this page number. For example, if $n=15$ and $m=5$, pages divisible by $m$ are $5, 10, 15$. Their last digits are $5, 0, 5$ correspondingly, their sum is $10$.

Your task is to calculate the sum of all digits Polycarp has written down.

You have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 1000$) — the number of queries.

The following $q$ lines contain queries, one per line. Each query is given as two integers $n$ and $m$ ($1 \le n, m \le 10^{16}$) — the number of pages in the book and required divisor, respectively.

-----Output-----

For each query print the answer for it — the sum of digits written down by Polycarp.

-----Example-----
Input
7
1 1
10 1
100 3
1024 14
998244353 1337
123 144
1234312817382646 13

Output
1
45
153
294
3359835
0
427262129093995

t=int(input())
for i in range(t):
    n,m = map(int,input().split())
    a = [0]*11
    for j in range(1,11):
        a[j] = (m*j)%10+a[j-1]
    x = n//m
    print(a[10]*(x//10)+a[x%10])


Solve in Python:
Polycarp lives on the coordinate axis $Ox$ and travels from the point $x=a$ to $x=b$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.

On the axis $Ox$ at the point $x=c$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $r$. Thus, if Polycarp is at a distance less than or equal to $r$ from the point $x=c$, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.

Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $x=a$ to $x=b$. His speed — one unit of distance per minute.

-----Input-----

The first line contains a positive integer $t$ ($1 \le t \le 1000$) — the number of test cases. In the following lines are written $t$ test cases.

The description of each test case is one line, which contains four integers $a$, $b$, $c$ and $r$ ($-10^8 \le a,b,c \le 10^8$, $0 \le r \le 10^8$) — the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively.

Any of the numbers $a$, $b$ and $c$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.

-----Output-----

Print $t$ numbers — answers to given test cases in the order they are written in the test. Each answer is an integer — the number of minutes during which Polycarp will be unavailable during his movement.

-----Example-----
Input
9
1 10 7 1
3 3 3 0
8 2 10 4
8 2 10 100
-10 20 -17 2
-3 2 2 0
-3 1 2 0
2 3 2 3
-1 3 -2 2

Output
7
0
4
0
30
5
4
0
3

-----Note-----

The following picture illustrates the first test case.  [Image] Polycarp goes from $1$ to $10$. The yellow area shows the coverage area of the station with a radius of coverage of $1$, which is located at the point of $7$. The green area shows a part of the path when Polycarp is out of coverage area.

for tcase in range(int(input())):
    a,b,c,r = list(map(int, input().split()))

    ca, cb = c-r, c+r

    a,b = min(a,b), max(a,b)

    if b<=ca:
        print(b-a)
    elif cb<=a:
        print(b-a)
    elif a<=ca<=b<=cb:
        print(ca-a)
    elif ca<=a<=cb<=b:
        print(b-cb)
    elif a<=ca<=cb<=b:
        print((ca-a)+(b-cb))
    elif ca<=a<=b<=cb:
        print(0)
    else:
        print(0)


Solve in Python:
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send a_{i} requests.

Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.

Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.

For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.

Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the duration of the load testing.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the number of requests from friends in the i-th minute of the load testing.

-----Output-----

Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.

-----Examples-----
Input
5
1 4 3 2 5

Output
6

Input
5
1 2 2 2 1

Output
1

Input
7
10 20 40 50...

import math

n = int(input())
a = list(map(int, input().split()))
mx = 0
g = [0]*n
r = [0]*n

t1 = [0]*n
t2 = [0]*n

for i in range(n):
	g[i] = max(0, mx-a[i]+1)
	mx = a[i] + g[i]
	t1[i] = mx
	if i > 0:
		g[i] += g[i-1]

mx = 0
for i in range(n-1, -1, -1):
	r[i] = max(0, mx-a[i]+1)
	mx = a[i] + r[i]
	t2[i] = mx
	if i < n-1:
		r[i] += r[i+1]

ans = 10**18
for i in range(n):
	sum = max(t1[i], t2[i]) - a[i];
	if i > 0:
		sum += g[i-1]
	if i < n-1:
		sum += r[i+1]
	ans = min(ans, sum)
print(ans)


Solve in Python:
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.

There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.

For example, suppose that Polycarp knows three spells: a fire spell of power $5$, a lightning spell of power $1$, and a lightning spell of power $8$. There are $6$ ways to choose the order in which he casts the spells:

  first, second, third. This order deals $5 + 1 + 2 \cdot 8 = 22$ damage;  first, third, second. This order deals $5 + 8 + 2 \cdot 1 = 15$ damage;  second, first, third. This order deals $1 + 2 \cdot 5 + 8 = 19$ damage;  second, third, first. This order deals $1 + 2 \cdot 8 + 2 \cdot 5 = 27$ damage;  third, first, second. This order deals $8 + 2 \cdot 5 + 1 = 19$ damage;  third, second, first. This order deals $8 + 2 \cdot 1 + 2 \cdot 5 = 20$ damage.

Initially, Polycarp knows $0$ spells. His spell set changes $n$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of changes to the spell set.

Each of the next $n$ lines contains two integers $tp$ and $d$ ($0 \le tp_i \le 1$; $-10^9 \le d \le 10^9$; $d_i \neq 0$) — the description of the change. If $tp_i$ if equal to $0$, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.

If $d_i > 0$, then Polycarp learns a spell of power $d_i$. Otherwise, Polycarp forgets a spell with power $-d_i$, and it is guaranteed that he knew that spell before the change.

It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the...

class BIT():
    def __init__(self,n):
        self.BIT=[0]*(n+1)
        self.num=n

    def query(self,idx):
        res_sum = 0
        while idx > 0:
            res_sum += self.BIT[idx]
            idx -= idx&(-idx)
        return res_sum

    #Ai += x O(logN)
    def update(self,idx,x):
        while idx <= self.num:
            self.BIT[idx] += x
            idx += idx&(-idx)
        return

import sys,heapq,random

input=sys.stdin.readline

n=int(input())
spell=[tuple(map(int,input().split())) for i in range(n)]

S=set([])
for i in range(n):
    S.add(abs(spell[i][1]))
S=list(S)
S.sort(reverse=True)
comp={i:e+1 for e,i in enumerate(S)}
N=len(S)

x_exist=BIT(N)
y_exist=BIT(N)
power=BIT(N)

X,Y,S=0,0,0
Xmax=[]
Ymin=[]
x_data=[0]*(N+1)
y_data=[0]*(N+1)

for i in range(n):
    t,d=spell[i]
    S+=d
    if d<0:
        id=comp[-d]
        if t==0:
            X-=1
            x_exist.update(id,-1)
            power.update(id,d)
            x_data[id]-=1
        else:
            Y-=1
            y_exist.update(id,-1)
            power.update(id,d)
            y_data[id]-=1
    else:
        id=comp[d]
        if t==0:
            X+=1
            x_exist.update(id,1)
            power.update(id,d)
            heapq.heappush(Xmax,-d)
            x_data[id]+=1
        else:
            Y+=1
            y_exist.update(id,1)
            power.update(id,d)
            heapq.heappush(Ymin,d)
            y_data[id]+=1
    if X==0:
        if Y==0:
            print(0)
        else:
            while not y_data[comp[Ymin[0]]]:
                heapq.heappop(Ymin)
            print(2*S-Ymin[0])
    else:
        if Y==0:
            print(S)
        else:
            start=0
            end=N
            while end-start>1:
                test=(end+start)//2
                if x_exist.query(test)+y_exist.query(test)<=Y:
                    start=test
                else:
                    end=test
            if y_exist.query(start)!=Y:
                print(S+power.query(start))
            else:
              ...


Solve in Python:
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.

Polycarp can summon $n$ different minions. The initial power level of the $i$-th minion is $a_i$, and when it is summoned, all previously summoned minions' power levels are increased by $b_i$. The minions can be summoned in any order.

Unfortunately, Polycarp cannot have more than $k$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.

Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).

Help Polycarp to make up a plan of actions to summon the strongest possible army!

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 75$) — the number of test cases.

Each test case begins with a line containing two integers $n$ and $k$ ($1 \le k \le n \le 75$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively.

Then $n$ lines follow, the $i$-th line contains $2$ integers $a_i$ and $b_i$ ($1 \le a_i \le 10^5$, $0 \le b_i \le 10^5$) — the parameters of the $i$-th minion.

-----Output-----

For each test case print the optimal sequence of actions as follows:

Firstly, print $m$ — the number of actions which Polycarp has to perform ($0 \le m \le 2n$). Then print $m$ integers $o_1$, $o_2$, ..., $o_m$, where $o_i$ denotes the $i$-th action as follows: if the $i$-th action is to summon the minion $x$, then $o_i = x$, and if the $i$-th action is to destroy the minion $x$, then $o_i = -x$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $k$ after every action.

If there are multiple optimal sequences, print any...

def read_int():
    return int(input())

def read_ints():
    return list(map(int, input().split(' ')))

t = read_int()
for case_num in range(t):
    n, k = read_ints()
    p = []
    for i in range(n):
        ai, bi = read_ints()
        p.append((bi, ai, i + 1))
    p.sort()
    dp = [[0 for j in range(k + 1)] for i in range(n + 1)]
    use = [[False for j in range(k + 1)] for i in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(min(i, k) + 1):
            if i - 1 >= j:
                dp[i][j] = dp[i - 1][j] + (k - 1) * p[i - 1][0]
            if j > 0:
                x = dp[i - 1][j - 1] + (j - 1) * p[i - 1][0] + p[i - 1][1]
                if x > dp[i][j]:
                    dp[i][j] = x
                    use[i][j] = True
    used = []
    curr = k
    for i in range(n, 0, -1):
        if use[i][curr]:
            used.append(p[i - 1][2])
            curr -= 1
    used.reverse()
    seq = used[:-1]
    st = set(used)
    for i in range(1, n + 1):
        if not i in st:
            seq.append(i)
            seq.append(-i)
    seq.append(used[-1])
    print(len(seq))
    print(' '.join(map(str, seq)))


Solve in Python:
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time.

Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came.

The i-th request is characterized by two values: s_{i} — the day when a client wants to start the repair of his car, d_{i} — duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on.

Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows:  If the car repair shop is idle for d_{i} days starting from s_{i} (s_{i}, s_{i} + 1, ..., s_{i} + d_{i} - 1), then these days are used to repair a car of the i-th client.  Otherwise, Polycarp finds the first day x (from 1 and further) that there are d_{i} subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + d_{i} - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + d_{i} - 1]. It is possible that the day x when repair is scheduled to start will be less than s_{i}.

Given n requests, you are asked to help Polycarp schedule all of them according to the rules above.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200) — the number of requests from clients.

The following n lines contain requests, one request per line. The i-th request is given as the pair of integers s_{i}, d_{i} (1 ≤ s_{i} ≤ 10^9, 1 ≤ d_{i} ≤ 5·10^6), where s_{i} is the preferred time to start repairing the i-th car, d_{i} is the number of days to repair the i-th car.

The requests should be processed in the order they are given in the input.

-----Output-----

Print n lines. The i-th line should contain two integers — the start day to repair...

import sys

lines = iter(sys.stdin.read().splitlines())

next(lines)

s,d = map(int,next(lines).split())

dates = [[0,0],[s, s + d -1],[10000000001,10000000001]]
res = [[s, s + d -1]]

for line in lines:
	s,d = map(int,line.split())

	nhueco = True

	for i in range(len(dates)):
		if s > dates[i][1] and s+d-1 < dates[i+1][0]:
			dates.insert(i+1,[s, s + d -1])
			res.append([s, s + d -1])
			break
		elif nhueco and -dates[i][1] +dates[i+1][0] -1 >= d:
			nhueco = False
			ld = dates[i][1] + 1
			li = i+1
	else:
		dates.insert(li,[ld, ld + d -1])
		res.append([ld, ld + d -1])

for date in res:
	print(" ".join(map(str,date)))


Solve in Python:
Polycarp took $n$ videos, the duration of the $i$-th video is $a_i$ seconds. The videos are listed in the chronological order, i.e. the $1$-st video is the earliest, the $2$-nd video is the next, ..., the $n$-th video is the last.

Now Polycarp wants to publish exactly $k$ ($1 \le k \le n$) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the $j$-th post is $s_j$ then:

  $s_1+s_2+\dots+s_k=n$ ($s_i>0$),  the first post contains the videos: $1, 2, \dots, s_1$;  the second post contains the videos: $s_1+1, s_1+2, \dots, s_1+s_2$;  the third post contains the videos: $s_1+s_2+1, s_1+s_2+2, \dots, s_1+s_2+s_3$;  ...  the $k$-th post contains videos: $n-s_k+1,n-s_k+2,\dots,n$.

Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same.

Help Polycarp to find such positive integer values $s_1, s_2, \dots, s_k$ that satisfy all the conditions above.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The next line contains $n$ positive integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$), where $a_i$ is the duration of the $i$-th video.

-----Output-----

If solution exists, print "Yes" in the first line. Print $k$ positive integers $s_1, s_2, \dots, s_k$ ($s_1+s_2+\dots+s_k=n$) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists).

If there is no solution, print a single line "No".

-----Examples-----
Input
6 3
3 3 1 4 1 6

Output
Yes
2 3 1
Input
3 3
1 1 1

Output
Yes
1 1 1
Input
3 3
1 1 2

Output
No
Input
3 1
1 10 100

Output
Yes
3

n, k = map(int, input().split())
l = [*map(int, input().split())]

s = sum(l)
res = []
if s % k == 0:
    s //= k
    curr = 0
    prev = 0

    for i, e in enumerate(l):
        curr += e
        if curr == s:
            res.append(str(i - prev + 1))
            prev = i + 1
            curr = 0
        if curr > s:
            res = []
            break

    if curr != 0: res = []

if len(res) != k:
    print('No')
else:
    print('Yes')
    print(' '.join(res))


Solve in Python:
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $26$ lowercase Latin letters will be arranged in some order.

Polycarp uses the same password $s$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $s$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $s$, so, for example, the password cannot be password (two characters s are adjacent).

Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 1000$) — the number of test cases.

Then $T$ lines follow, each containing one string $s$ ($1 \le |s| \le 200$) representing the test case. $s$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $s$.

-----Output-----

For each test case, do the following:

  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of $26$ lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them.

-----Example-----
Input
5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza

Output
YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

for _ in range(int(input())):
    q=input()
    ans=q[0]
    test=[0]*26
    j=0
    c = 1
    for i in q[1:]:
        if j>0 and ans[j-1]==i:
            j-=1
            continue
        if j<len(ans)-1 and ans[j+1]==i:
            j+=1
            continue
        if j==0:
            ans=i+ans
            continue
        if j==len(ans)-1:
            ans+=i
            j+=1
            continue
        c=0
    for i in ans:test[ord(i)-97]+=1
    for i in range(26):
        if test[i]>1:c=0
        if test[i]==0:ans+=chr(i+97)
    if c:
        print('YES')
        print(ans)
    else:
        print('NO')


Solve in Python:
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $n$ problems and lasts for $T$ minutes. Each of the problems is defined by two positive integers $a_i$ and $p_i$ — its difficulty and the score awarded by its solution.

Polycarp's experience suggests that his skill level is defined with positive real value $s$, and initially $s=1.0$. To solve the $i$-th problem Polycarp needs $a_i/s$ minutes.

Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by $10\%$, that is skill level $s$ decreases to $0.9s$. Each episode takes exactly $10$ minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for $a_i/s$ minutes, where $s$ is his current skill level. In calculation of $a_i/s$ no rounding is performed, only division of integer value $a_i$ by real value $s$ happens.

Also, Polycarp can train for some time. If he trains for $t$ minutes, he increases his skill by $C \cdot t$, where $C$ is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.

Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed before solving the first problem.

-----Input-----

The first line contains one integer $tc$ ($1 \le tc \le 20$) — the number of test cases. Then $tc$ test cases follow.

The first line of each test contains one integer $n$ ($1 \le n \le 100$) — the number of problems in the contest.

The second line of the test contains two real values $C, T$ ($0 < C < 10$, $0 \le T \le 2 \cdot 10^5$), where $C$ defines the efficiency of the training and $T$ is the duration of the contest in minutes. Value $C, T$ are given exactly with three digits...

from math import sqrt
class pro(object):
    def __init__(self,dif,sc):
        self.dif=dif
        self.sc=sc

    def __lt__(self,other):
        return self.dif>other.dif

T=int(input())
mul=[1]
for i in range(100):
    mul.append(mul[i]*10/9)
inf=1000000007
for t in range(T):
    n=int(input())
    effi,tim=list(map(float,input().split()))
    prob=[]
    for i in range(n):
        x,y=list(map(int,input().split()))
        prob.append(pro(x,y))
    prob.sort()
    f=[[inf for i in range(n+1)] for j in range(1001)]
    f[0][0]=0
    totsc=0
    for i in range(n):
        totsc+=prob[i].sc
        for j in range(totsc,prob[i].sc-1,-1):
            for k in range(1,i+2):
                f[j][k]=min(f[j][k],f[j-prob[i].sc][k-1]+prob[i].dif*mul[k])
    for i in range(totsc,-1,-1):
        flag=False
        for j in range(n+1):
            if sqrt(effi*f[i][j])>=1:
                res=2*sqrt(f[i][j]/effi)-1/effi+10*j
            else:
                res=f[i][j]+10*j
            if res<=tim:
                print(i)
                flag=True
                break
        if flag==True:
            break


Solve in Python:
Polycarpus has a sequence, consisting of n non-negative integers: a_1, a_2, ..., a_{n}.

Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = a_{l} | a_{l} + 1 | ...  | a_{r}.

Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.

Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.

Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of elements of sequence a. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^6) — the elements of sequence a.

-----Output-----

Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

-----Examples-----
Input
3
1 2 0

Output
4
Input
10
1 2 3 4 5 6 1 2 9 10

Output
11

-----Note-----

In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.

n = int(input())
a = list(map(int, input().split()))

s1, s2 = set(), set()

for each in a:
    st = set()
    st.add(each)
    for i in s1:
        st.add(each | i)
    s1 = st
    s2.update(s1)

print(len(s2))


Solve in Python:
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.

Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.

Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers t_{i}, x_{i}, y_{i} (1 ≤ t_{i} ≤ 2; x_{i}, y_{i} ≥ 0; x_{i} + y_{i} = 10). If t_{i} = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers x_{i}, y_{i} represent the result of executing this command, that is, x_{i} packets reached the corresponding server successfully and y_{i} packets were lost.

It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

-----Output-----

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).

In the second line print the state of server b in the similar format.

-----Examples-----
Input
2
1 5 5
2 6 4

Output
LIVE
LIVE

Input
3
1 0 10
2 0 10
1 10 0

Output
LIVE
DEAD

-----Note-----

Consider the first test case. There 10 packets were sent to...

3

n = int(input())
send = [[], []]
for _ in range(n):
    t, x, y = tuple(map(int, input().split()))
    send[t - 1].append(x)
for _ in range(2):
    print('LIVE' if 2 * sum(send[_]) >= 10 * len(send[_]) else 'DEAD')