Solve in Python:
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M.
A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train.
For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M.
For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0.
Here, assume that it is not allowed to change trains.

-----Constraints-----
 - 1 ≦ N ≦ 3 × 10^{5}
 - 1 ≦ M ≦ 10^{5}
 - 1 ≦ l_i ≦ r_i ≦ M

-----Input-----
The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N}

-----Output-----
Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station.

-----Sample Input-----
3 3
1 2
2 3
3 3

-----Sample Output-----
3
2
2

 - If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.
 - If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.
 - If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.

import sys
def input():
    return sys.stdin.readline()[:-1]

N, M = list(map(int, input().split()))
L = []
for i in range(N):
    l, r = list(map(int, input().split()))
    L.append((r - l + 1, l, r + 1))
L.sort()

class Bit:
    """
    0-indexed
    # 使用例
    bit = Bit(10)  # 要素数
    bit.add(2, 10)
    print(bit.sum(5))  # 10
    """

    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        # [0, i) の要素の総和を返す
        if not (0 <= i <= self.size): raise ValueError("error!")
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        if not (0 <= i < self.size): raise ValueError("error!")
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

class BitImos:
    """
    ・範囲すべての要素に加算
    ・ひとつの値を取得
    の2種類のクエリをO(logn)で処理
    """

    def __init__(self, n):
        self.bit = Bit(n + 1)

    def add(self, s, t, x):
        # [s, t)にxを加算
        self.bit.add(s, x)
        self.bit.add(t, -x)

    def get(self, i):
        return self[i]

    def __getitem__(self, key):
        # 位置iの値を取得
        return self.bit.sum(key + 1)

imos = BitImos(M + 1)
il = 0
a = N
for i in range(1, M + 1):
    while il < N:
        ra, l, r = L[il]
        if i < ra:
            break
        il += 1
        a -= 1
        imos.add(l, r, 1)
    ans = 0
    for j in range(i, M + 1, i):
        ans += imos[j]

    print((ans + a))


Solve in Python:
Snuke is playing a puzzle game.
In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).
The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N.
Here, the curves may not go outside the board or cross each other.
Determine whether this is possible.

-----Constraints-----
 - 1 ≤ R,C ≤ 10^8
 - 1 ≤ N ≤ 10^5
 - 0 ≤ x_{i,1},x_{i,2} ≤ R(1 ≤ i ≤ N)
 - 0 ≤ y_{i,1},y_{i,2} ≤ C(1 ≤ i ≤ N)
 - All given points are distinct.
 - All input values are integers.

-----Input-----
Input is given from Standard Input in the following format:
R C N
x_{1,1} y_{1,1} x_{1,2} y_{1,2}
:
x_{N,1} y_{N,1} x_{N,2} y_{N,2}

-----Output-----
Print YES if the objective is achievable; print NO otherwise.

-----Sample Input-----
4 2 3
0 1 3 1
1 1 4 1
2 0 2 2

-----Sample Output-----
YES

The above figure shows a possible solution.

r, c, n = list(map(int, input().split()))
l = []
for i in range(n):
    x1, y1, x2, y2 = list(map(int, input().split()))
    if (x1 == 0 or x1 == r or y1 == 0 or y1 == c) and (x2 == 0 or x2 == r or y2 == 0 or y2 == c):
        if x1 == 0:
            l.append((y1, i))
        elif y1 == c:
            l.append((c + x1, i))
        elif x1 == r:
            l.append((c * 2 + r - y1, i))
        else:
            l.append((r * 2 + c * 2 - x1, i))
        if x2 == 0:
            l.append((y2, i))
        elif y2 == c:
            l.append((c + x2, i))
        elif x2 == r:
            l.append((c * 2 + r - y2, i))
        else:
            l.append((r * 2 + c * 2 - x2, i))
l.sort()
s = []
d = [False] * n
for x, i in l:
    if d[i]:
        if s[-1] != i:
            print('NO')
            return
        s.pop()
    else:
        s.append(i)
        d[i] = True
print('YES')


Solve in Python:
Snuke loves constructing integer sequences.
There are N piles of stones, numbered 1 through N.
The pile numbered i consists of a_i stones.
Snuke will construct an integer sequence s of length Σa_i, as follows:
 - Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s.
 - Select a pile with one or more stones remaining, and remove a stone from that pile.
 - If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process.
We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence?

-----Constraints-----
 - 1 ≤ N ≤ 10^{5}
 - 1 ≤ a_i ≤ 10^{9}

-----Input-----
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N}

-----Output-----
Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed.

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

-----Sample Output-----
2
1

The lexicographically smallest sequence is constructed as follows:
 - Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2.
 - Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2.
 - Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1.
The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once.

import collections
import heapq
n=int(input())
A=[int(i) for i in input().split()]
Ans=[0]*n
M=[0]#自分より前の最大値をメモ。これ以下だと現れない
for i in range(n):
  M.append(max(M[-1],A[i]))
D=collections.defaultdict(int)
H=[]
for i in range(n):
  j=n-1-i
  if A[j]<=M[j]:
    heapq.heappush(H,-A[j])#出現しないインデックスの数を管理。大きいほうから取り出す。
  else:
    Ans[j]=(A[j]-M[j])*(D[A[j]]+1)#自分より前の最大値と自分の差かける自分自身と同じ数のこれまでの出現回数
    D[M[j]]+=D[A[j]]+1#自分自身より後ろの自分と同じ数全てを自分より前の最大値まで減らすことで増える分
    ct=0
    while H:#自分より後ろで自分より小さいが、自分の前の最大値より大きいものを全て見る
      a=heapq.heappop(H)
      a=-a
      if a<=M[j]:
        heapq.heappush(H,-a)
        break
      else:
        Ans[j]+=a-M[j]
        D[M[j]]+=1

for a in Ans:
  print(a)


Solve in Python:
Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.
The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.
You can change trains at a station where multiple lines are available.
The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.
Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 0 \leq M \leq 2×10^5
 - 1 \leq p_i \leq N (1 \leq i \leq M)
 - 1 \leq q_i \leq N (1 \leq i \leq M)
 - 1 \leq c_i \leq 10^6 (1 \leq i \leq M)
 - p_i \neq q_i (1 \leq i \leq M)

-----Input-----
The input is given from Standard Input in the following format:
N M
p_1 q_1 c_1
:
p_M q_M c_M

-----Output-----
Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

-----Sample Input-----
3 3
1 2 1
2 3 1
3 1 2

-----Sample Output-----
1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

from collections import deque,defaultdict
import sys
input = sys.stdin.readline
N,M=map(int,input().split())
mod =10**7
table=defaultdict(set)
visit=defaultdict(int)
for i in range(M):
    a,b,c=map(int,input().split())
    table[a].add(a+c*mod)
    table[b].add(b+c*mod)
    table[a+c*mod].add(a)
    table[b+c*mod].add(b)
    table[a+c*mod].add(b+c*mod)
    table[b+c*mod].add(a+c*mod)
    visit[a]=0
    visit[b]=0
    visit[b+c*mod]=0
    visit[a+c*mod]=0

H=deque()
H.append((1,0))
visit[1]=1
ans=mod
while H:
    #print(H)
    x,cost=H.popleft()
    visit[x] = 1
    if x==N:
        ans=min(ans,cost)
        break
    for y in table[x]:
        if visit[y]==1:
            continue
        if x<=10**5 and mod<=y:
            H.append((y,cost+1))
        else:
            H.appendleft((y,cost))
if ans==mod:
    print(-1)
else:
    print(ans)


Solve in Python:
So the Beautiful Regional Contest (BeRC) has come to an end! $n$ students took part in the contest. The final standings are already known: the participant in the $i$-th place solved $p_i$ problems. Since the participants are primarily sorted by the number of solved problems, then $p_1 \ge p_2 \ge \dots \ge p_n$.

Help the jury distribute the gold, silver and bronze medals. Let their numbers be $g$, $s$ and $b$, respectively. Here is a list of requirements from the rules, which all must be satisfied:  for each of the three types of medals, at least one medal must be awarded (that is, $g>0$, $s>0$ and $b>0$);  the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $g<s$ and $g<b$, but there are no requirements between $s$ and $b$);  each gold medalist must solve strictly more problems than any awarded with a silver medal;  each silver medalist must solve strictly more problems than any awarded a bronze medal;  each bronze medalist must solve strictly more problems than any participant not awarded a medal;  the total number of medalists $g+s+b$ should not exceed half of all participants (for example, if $n=21$, then you can award a maximum of $10$ participants, and if $n=26$, then you can award a maximum of $13$ participants).

The jury wants to reward with medals the total maximal number participants (i.e. to maximize $g+s+b$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.

-----Input-----

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

The first line of a test case contains an integer $n$ ($1 \le n \le 4\cdot10^5$) — the number of BeRC participants. The second line of a test case contains integers $p_1, p_2, \dots, p_n$ ($0 \le p_i \le 10^6$), where $p_i$ is equal to the number of problems solved by the $i$-th participant from the final standings. The values $p_i$ are sorted in non-increasing order, i.e....

import sys
input = sys.stdin.readline
from collections import Counter

t=int(input())
for testcases in range(t):
    n=int(input())
    P=list(map(int,input().split()))
    C=Counter(P)
    PLIST=sorted(set(P),reverse=True)

    g=C[PLIST[0]]
    s=0
    b=0

    sflag=1

    for i in PLIST[1:]:

        if sflag:
            if s<=g:
                s+=C[i]
            else:
                sflag=0
                bflag=1
                b+=C[i]

        elif bflag:
            if b<=g:
                b+=C[i]
            elif g+s+b+C[i]<=n//2:
                b+=C[i]
            else:
                break

        #print(i,g,s,b)

    if g+s+b<=n//2:
        print(g,s,b)
    else:
        print(0,0,0)


Solve in Python:
So the Chef has become health conscious and is now lifting weights at the gym. But its his first time so the trainer gives him a simple job to do.

He has been given a weight lifting rod and N heavy weights, each weighing 20, 21, .... , 2n-1. He has to stick each of the "N" weights on the rod, one after another, in such a way that the right side is never heavier than the left side. At each step he chooses one of the weights that has not yet been fixed on the rod, and fix it on either the left side of the rod or the right, until all of the weights have been placed.

Now help the chef and find out, in how many ways the chef can accomplish this?

-----Input-----
First line of input contains an integer T, the number of test cases. Then T test cases follow. Each line of test case contains one integer, N denoting the number of weights

-----Output-----
The output contains T lines, each containing an integer denoting all possible combinations

-----Example-----
Input:
3
2
5
18

Output:
3
945
221643095476699771875

t = int(input())

while(t>0):

 n=int(input())
 if(n<=0):
  print(0)

 fact=1
 start=1
 for i in range(1,n+1):
  fact*=start
  start+=2
 print(fact)

 t=t-1


Solve in Python:
So you've found a meeting room - phew! You arrive there ready to present, and find that someone has taken one or more of the chairs!! You need to find some quick.... check all the other meeting rooms to see if all of the chairs are in use.

Your meeting room can take up to 8 chairs. `need` will tell you how many have been taken. You need to find that many.

```if-not:java
Find the spare chairs from the array of meeting rooms. Each meeting room array will have the number of occupants as a string. Each occupant is represented by 'X'. The room array will also have an integer telling you how many chairs there are in the room.
```
```if:java
Find the spare chairs from the array of meeting rooms.
~~~java
public class Room {
  public final String occupants;  // number of occupants, each occupant is represented by 'X'
  public final int chairs;        // number of chairs in the room
}
~~~
```

You should return an array of integers that shows how many chairs you take from each room in order, up until you have the required amount.

```if-not:java
example:
[['XXX', 3], ['XXXXX', 6], ['XXXXXX', 9], ['XXX',2]] when you need 4 chairs:
```
```if:java
example:
`[Room("XXX", 3), Room("XXXXX", 6), Room("XXXXXX", 9), Room("XXX",2)]` when you need 4 chairs:
```

result -- > `[0, 1, 3]` (no chairs free in room 0, take 1 from room 1, take 3 from room 2. No need to consider room 4 as you have your 4 chairs already.

If you need no chairs, return `'Game On'`. If there aren't enough spare chairs available, return `'Not enough!'`

More in this series:

The Office I - Outed
The Office II - Boredeom Score
The Office III - Broken Photocopier
The Office IV - Find a Meeting Room

def meeting(rooms, need):
    if need == 0:
        return "Game On"
    take = []
    for people, seat in rooms:
        take.append(min(need, max(0, seat - len(people))))
        need -= take[-1]
        if need == 0:
            return take
    return "Not enough!"


Solve in Python:
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

If there is exactly one solution for the equation, we ensure that the value of x is an integer.

Example 1:

Input: "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:

Input: "x=x"
Output: "Infinite solutions"

Example 3:

Input: "2x=x"
Output: "x=0"

Example 4:

Input: "2x+3x-6x=x+2"
Output: "x=-1"

Example 5:

Input: "x=x+2"
Output: "No solution"

class Solution:
     def solveEquation(self, equation):
         """
         :type equation: str
         :rtype: str
         """
         left_x = right_x = 0
         left_const = right_const = 0

         cur_left = True
         cur_num = 0
         cur_sign = 1
         has_num = False
         for c in equation:
             if c == "=":
                 left_const += cur_num * cur_sign
                 cur_num = 0
                 cur_sign = 1
                 cur_left = False
                 has_num = False
             elif c in '+-':
                 if cur_left:
                     left_const += cur_num * cur_sign
                 else:
                     right_const += cur_num * cur_sign
                 cur_num = 0
                 cur_sign = 1 if c == '+' else -1
                 has_num = False
             elif c == 'x':
                 if cur_left:
                     left_x += cur_sign* (cur_num if has_num else 1)
                 else:
                     right_x += cur_sign* (cur_num if has_num else 1)
                 cur_num = 0
                 has_num = False
             else:
                 cur_num = cur_num * 10 + int(c)
                 has_num = True

             # print(left_x, right_x, left_const, right_const, cur_num, cur_sign)

         right_const += cur_num*cur_sign
         left_x -= right_x
         right_const -= left_const

         if left_x == 0 and right_const == 0:
             return "Infinite solutions"
         elif left_x == 0 and right_const != 0:
             return "No solution"
         else:
             return "x=" + str(int(right_const/left_x))


Solve in Python:
Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not.  Her King requested for her help in mining precious stones, so she has told him which all stones are jewels and which are not. Given her description, your task is  to count the number of jewel stones.

More formally, you're given a string J composed of latin characters where each character is a jewel. You're also given a string S composed of latin characters where each character is a mined stone. You have to find out how many characters of S are in J as well.

-----Input-----

First line contains an integer T denoting the number of test cases. Then follow T test cases. Each test case consists of two lines, each of which contains a string composed of English lower case and upper characters. First of these is the jewel string J and the second one is stone string S.
You can assume that  1 <= T <= 100, 1 <= |J|, |S| <= 100

-----Output-----
Output for each test case, a single integer, the number of jewels mined.

-----Example-----
Input:
4
abc
abcdef
aA
abAZ
aaa
a
what
none

Output:
3
2
1
0

for case in range(int(input())):
 jewels = set([])
 for char in input().rstrip("\n"):
  jewels.add(char)

 count = 0
 for char in input().rstrip("\n"):
  if char in jewels:
   count += 1
 print(count)


Solve in Python:
Some integral numbers are odd. All are more odd, or less odd, than others.

Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are always less odd than odd numbers, but they also can be more, or less, odd than other even numbers, by the same mechanism.

# Task

Given a _non-empty_ finite list of _unique_ integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
Given the constraints, there will always be exactly one such number.

# Examples

```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => 5
```

# Hint

Do you _really_ want one? Point or tap here.

def oddest(a):
    return max(a, key=lambda n: f'{n+2**32:b}'[::-1])


Solve in Python:
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch".

## MaxMatch
MaxMatch starts at the first character of a sentence and tries to find the longest valid word starting from that character. If no word is found, the first character is deemed the longest "word", regardless of its validity. In order to find the rest of the words, MaxMatch is then recursively invoked on all of the remaining characters until no characters remain. A list of all of the words that were found is returned.

So for the string `"happyday"`, `"happy"` is found because `"happyday"` is not a valid word, nor is `"happyda"`, nor `"happyd"`. Then, MaxMatch is called on `"day"`, and `"day"` is found. The output is the list `["happy", "day"]` in that order.

## The Challenge

```if:javascript
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns an `Array` of all the words found, in the order they were found.
**All valid words are in the** `Set` `VALID_WORDS`, which only contains around 500 English words.
```
```if:haskell
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `[String]` of all the words found, in the order they were found. All valid words are in the `[String]` `validWords`, which only contains around 500 English words.
```
```if:java
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s which are all the words found, in the order they were found. All valid words are in the `Set` `Preloaded.VALID_WORDS`, , which only contains around 500 English words.
```
```if:python
Write `max_match`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s of all the words found, in the...

def max_match(sentence):
    found = []
    while sentence:
        for i in range(len(sentence), 0, -1):
            chunk = sentence[:i]
            if chunk in VALID_WORDS:
                break
        found.append(chunk)
        sentence = sentence[i:]
    return found


Solve in Python:
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit!

If the tail is right return true, else return false.

The arguments will always be strings, and normal letters.

def correct_tail(body, tail):
    bodytail = body[-1]
    if bodytail == tail:
        return True
    else:
        return False


Solve in Python:
Some new cashiers started to work at your restaurant.

They are good at taking orders, but they don't know how to capitalize words, or use a space bar!

All the orders they create look something like this:

`"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"`

The kitchen staff are threatening to quit, because of how difficult it is to read the orders.

Their preference is to get the orders as a nice clean string with spaces and capitals like so:

`"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"`

The kitchen staff expect the items to be in the same order as they appear in the menu.

The menu items are fairly simple, there is no overlap in the names of the items:
```
1. Burger
2. Fries
3. Chicken
4. Pizza
5. Sandwich
6. Onionrings
7. Milkshake
8. Coke
```

def get_order(order):
    menu = [
    "Burger",
    "Fries",
    "Chicken",
    "Pizza",
    "Sandwich",
    "Onionrings",
    "Milkshake",
    "Coke",
]
    return "".join([(item + " ") * order.count(item.lower()) for item in menu]).strip()


Solve in Python:
Some numbers can be expressed as a difference of two squares, for example, 20 = 6^(2)-4^(2) and 21 = 5^(2)-2^(2). Many numbers can be written this way, but not all.

## Your Task
Complete the function that takes a positive integer `n` and returns the amount of numbers between `1` and `n` (inclusive) that can be represented as the difference of two perfect squares.

**Note**: Your code should be able to handle `n` values up to 45000

## Examples

```
n = 4 ==> 3
n = 5 ==> 4
n = 10 ==> 7
n = 20 ==> 15
n = 6427 ==> 4820
```

archive = []
archive_values = {0: 0}
def count_squareable(n):
    def solve(nn):
        return next((1 for x in range(1, int(nn**.5)+1) if not nn%x and x%2==(nn//x)%2), 0)
    first_ind = next((i for i in reversed(archive) if i<=n), 0)
    result = sum(solve(i) for i in range(first_ind+1, n+1))+archive_values[first_ind]
    archive.append(n)
    archive_values[n] = result
    return result


Solve in Python:
Some numbers have funny properties. For example:

> 89 --> 8¹ + 9² = 89 * 1

> 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

> 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
- we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.

In other words:

> Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

**Note**: n and p will always be given as strictly positive integers.

```python
dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
```

def dig_pow(n, p):
    k, fail = divmod(sum(int(d)**(p + i) for i, d in enumerate(str(n))), n)
    return -1 if fail else k


Solve in Python:
Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.
Person A will NOT friend request person B (B != A) if any of the following conditions are true:

age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100

Otherwise, A will friend request B.
Note that if A requests B, B does not necessarily request A.  Also, people will not friend request themselves.
How many total friend requests are made?
Example 1:
Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.

Example 2:
Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
Input: [20,30,100,110,120]
Output: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.

Notes:

1 <= ages.length <= 20000.
1 <= ages[i] <= 120.

import bisect
class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:
        if not ages:
            return 0
        cnt = 0
        N = len(ages)
        ages.sort()
        for i in range(N):
            a = ages[i]
            if a<=14: #含14歲以前不能交朋友 => 數學推導
                continue
            idx1 = bisect.bisect(ages, a)
            x = 0.5*a+7
            idx2 = bisect.bisect(ages, x)
            while idx2<N and ages[idx2]==x: #找出右boundary
                idx2 += 1
            cnt += max(0, idx1-idx2+(-1 if idx2<=i<=idx1 else 0)) #不能跟自己交朋友
        return cnt


Solve in Python:
Some programming contest problems are really tricky: not only do they
require a different output format from what you might have expected, but
also the sample output does not show the difference. For an example,
let us look at permutations.

A permutation of the integers 1 to n is an
ordering of
these integers. So the natural way to represent a permutation is
to list the integers in this order. With n = 5, a
permutation might look like 2, 3, 4, 5, 1.

However, there is another possibility of representing a permutation:
You create a list of numbers where the i-th number is the
position of the integer i in the permutation.
Let us call this second
possibility an inverse permutation. The inverse permutation
for the sequence above is 5, 1, 2, 3, 4.

An ambiguous permutation is a permutation which cannot be
distinguished from its inverse permutation. The permutation 1, 4, 3, 2
for example is ambiguous, because its inverse permutation is the same.
To get rid of such annoying sample test cases, you have to write a
program which detects if a given permutation is ambiguous or not.

-----Input Specification-----
The input contains several test cases.

The first line of each test case contains an integer n
(1 ≤ n ≤ 100000).
Then a permutation of the integers 1 to n follows
in the next line. There is exactly one space character
between consecutive integers.
You can assume that every integer between 1 and n
appears exactly once in the permutation.

The last test case is followed by a zero.

-----Output Specification-----
For each test case output whether the permutation is ambiguous or not.
Adhere to the format shown in the sample output.

-----Sample Input-----
4
1 4 3 2
5
2 3 4 5 1
1
1
0

-----Sample Output-----
ambiguous
not ambiguous
ambiguous

while int(input()) != 0:
 l = list(map(int,input().split()))
 invArray = [0 for j in range(len(l))]
 for i in range(len(l)):
  invArray[l[i]-1] = i + 1
 if invArray == l:
  print("ambiguous")
 else:
  print("not ambiguous")


Solve in Python:
Sometimes Sergey visits fast food restaurants. Today he is going to visit the one called PizzaKing.
Sergey wants to buy N meals, which he had enumerated by integers from 1 to N. He knows that the meal i costs Ci rubles. He also knows that there are M meal sets in the restaurant.
The meal set is basically a set of meals, where you pay Pj burles and get Qj meals - Aj, 1, Aj, 2, ..., Aj, Qj.
Sergey has noticed that sometimes he can save money by buying the meals in the meal sets instead of buying each one separately. And now he is curious about what is the smallest amount of rubles he needs to spend to have at least one portion of each of the meals.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a pair of integer numbers N and M denoting the number of meals and the number of the meal sets.
The second line contains N space-separated integers C1, C2, ..., CN denoting the costs of the meals, bought separately.
Each of the following M lines starts with a pair of integer numbers Pi and Qi, denoting the cost of the meal set and the number of meals in it, followed with the integer numbers Ai, 1 Ai, 2, ..., Ai, Qi denoting the meal numbers.

-----Output-----
For each test case, output a single line containing the minimal total amount of money Sergey needs to spend in order to have at least one portion of each meal.

-----Constraints-----
- 1 ≤ Pi, Ci ≤ 106
- 1 ≤ M ≤ min{2N, 2 × 100000}
- No meal appears in the set twice or more times.
- Subtask 1 (16 points): 1 ≤ T ≤ 103, 1 ≤ N ≤ 8
- Subtask 2 (23 points): For each test file, either 1 ≤ T ≤ 10, 1 ≤ N ≤ 12 or the constraints for Subtask 1 are held.
- Subtask 3 (61 points): For each test file, either T = 1, 1 ≤ N ≤ 18 or the constraints for Subtask 1 or 2 are held.

-----Example-----
Input:1
3 3
3 5 6
11 3 1 2 3
5 2 1 2
5 2 1 3

Output:10

-----Explanation-----
Example case 1. If Sergey buys all the meals separately, it would cost him 3...

INF=5*(10**6)

def solve():
 dp=[INF]*(1<<18 + 1)
 n,m=list(map(int,input().split()))
 line=list(map(int,input().split()))
 for i in range(n):
  dp[(1<<i)]=line[i]
 for i in range(m):
  line=list(map(int,input().split()))
  c=line[0]
  mask=0
  for j in range(line[1]):
   mask= mask | (1<<(line[2+j]-1))
  dp[mask]=min(dp[mask],c)
 mask=(1<<n)-1
 while mask>=0:
  for j in range(n):
   submask = mask & (1<<j)
   if submask>0:
    dp[mask^(1<<j)]=min(dp[mask^(1<<j)],dp[mask])
  mask-=1
 for _ in range(1):
  for i in range(1<<n):
   submask=(i-1)&i
   while submask>0:
    dp[i]=min(dp[i],dp[submask]+dp[i^submask])
    submask=(submask-1)&i
 print(dp[(1<<n)-1])

t=eval(input())
for _ in range(t):
 solve()


Solve in Python:
Sometimes, I want to quickly be able to convert miles per imperial gallon into kilometers per liter.

Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input).

Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5.

Some useful associations relevant to this kata:
1 Imperial Gallon = 4.54609188 litres
1 Mile = 1.609344 kilometres


Solve in Python:
Sonya was unable to think of a story for this problem, so here comes the formal description.

You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array.

Next line contains n integer a_{i} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print the minimum number of operation required to make the array strictly increasing.

-----Examples-----
Input
7
2 1 5 11 5 9 11

Output
9

Input
5
5 4 3 2 1

Output
12

-----Note-----

In the first sample, the array is going to look as follows:

2 3 5 6 7 9 11

|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9

And for the second sample:

1 2 3 4 5

|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12

from heapq import *
class Maxheap:
    def __init__(_): _.h = []
    def add(_, v): heappush(_.h, -v)
    def top(_): return -_.h[0]
    def pop(_): return -heappop(_.h)

class Graph:
    def __init__(_):
        _.change = Maxheap() # increment slope at ...
        _.change.add(-10**18)
        _.a = _.y = 0 # last line has slope a, starts from y
        _.dx = 0      # the whole graph is shifted right by ...
    def __repr__(_): return f"<{[x+_.dx for x in _.change]}; {_.a} {_.y}>"

    def shiftx(_, v): _.dx+= v
    def shifty(_, v): _.y+= v
    def addleft(_, v):
        if _.change.top() < v-_.dx:
            dx = v-_.dx - _.change.top()
            _.y+= _.a*dx
        _.change.add(v-_.dx)
    def addright(_, v):
        if _.change.top() < v-_.dx:
            dx = v-_.dx - _.change.top()
            _.y+= _.a*dx; _.a+= 1
            _.change.add(v-_.dx)
            return
        _.change.add(v-_.dx)
        _.a+= 1; _.y+= _.change.top()-(v-_.dx)
    def cutright(_):
        dx = _.change.pop()-_.change.top()
        _.a-= 1; _.y-= _.a*dx

n = int(input())
G = Graph()
for x in map(int,input().split()):
    G.shiftx(1)
    G.addleft(x)
    G.addright(x)
    while G.a > 0: G.cutright()
print(G.y)


Solve in Python:
Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

# Definition for singly-linked list.
 # class ListNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.next = None

 class Solution:
     def sortList(self, head):
         l = []
         traverse, traverse2 = head, head
         while(traverse) != None:
             l.append(traverse.val)
             traverse = traverse.next
         l.sort()
         for num in l:
             traverse2.val = num
             traverse2 = traverse2.next
         return head


Solve in Python:
Sort array by last character

Complete the function to sort a given array or list by last character of elements.

```if-not:haskell
Element can be an integer or a string.
```

### Example:

```
['acvd', 'bcc']  -->  ['bcc', 'acvd']
```

The last characters of the strings are `d` and `c`. As `c` comes before `d`, sorting by last character will give `['bcc', 'acvd']`.

If two elements don't differ in the last character, then they should be sorted by the order they come in the array.

```if:haskell
Elements will not be empty (but the list may be).
```

def sort_me(arr):
    print((len(arr)))
    a=[str(x) for x in arr]
    print(a)
    b=[x[-1] for (x) in a]
    c=list(zip(arr,b))
    c=sorted(c, key=lambda x: x[1] )
    print(c)
    d=[x[0] for x in c]
    return d
    # Good Luck!


Solve in Python:
Sort the given strings in alphabetical order, case **insensitive**. For example:
```
["Hello", "there", "I'm", "fine"]  -->  ["fine", "Hello", "I'm", "there"]
["C", "d", "a", "B"])              -->  ["a", "B", "C", "d"]
```

sortme = lambda words: sorted(words, key=lambda w: (w.upper(), w[0].islower()))


Solve in Python:
Special Numbers
Mani has encountered a problem on Special numbers in Bytecode. A number S is called a special number if its digits are in an arithmetic progression modulo 10. He has an array consisting of all numbers from 1 to N and needs your help to find the number of special numbers in the array. He has promised you a significant share of the prize money if he wins the contest :p
Note:
123,99,802 are special numbers.
146 is not a special number

-----Input-----

Input consists of 1 integer - the value of N

-----Output-----
Print one integer in the first line - the solution to this problem

-----Constraints-----
- 1 ≤ Number of digits in N ≤ 105

Example

Input

123

Output

102

# cook your code here
n=input()
x=len(n)
no=list(map(int,n))
temp=[0]*x
if (x>2):
 sum=99
 for i in range(3,x):
  sum=sum+90
 sum=sum+10*(int(n[0])-1)
 sum=sum+int(n[1])
 f=int(n[0])%10

 s=int(n[1])%10

 cd=s-f

 temp[0]=n[0]
 temp[1]=n[1]
 for i in range(2,x):
  nxt=(s+cd)%10
  temp[i]=(chr(nxt+48))
  s=nxt
 temp=list(map(int,temp))
 if(temp<=no):
  sum=sum+1
 print(sum)
else:
  print(n)


Solve in Python:
Speedcubing is the hobby involving solving a variety of twisty puzzles, the most famous being the 3x3x3 puzzle or Rubik's Cube, as quickly as possible.

In the majority of Speedcubing competitions, a Cuber solves a scrambled cube 5 times, and their result is found by taking the average of the middle 3 solves (ie. the slowest and fastest times are disregarded, and an average is taken of the remaining times).

In some competitions, the unlikely event of a tie situation is resolved by comparing Cuber's fastest times.

Write a function ```cube_times(times)``` that, given an array of floats ```times``` returns an array / tuple with the Cuber's result (to 2 decimal places) AND their fastest solve.

For example:
```python
cube_times([9.5, 7.6, 11.4, 10.5, 8.1]) = (9.37, 7.6)
# Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```

Note: ```times``` will always be a valid array of 5 positive floats (representing seconds)

def cube_times(times):
    times = sorted(times)
    return (round(sum(times[1:-1])/3,2), times[0])


Solve in Python:
Spider-Man ("Spidey") needs to get across town for a date with Mary Jane and his web-shooter is low on web fluid. He travels by slinging his web rope to latch onto a building rooftop, allowing him to swing to the opposite end of the latch point.
Write a function that, when given a list of buildings, returns a list of optimal rooftop latch points for minimal web expenditure.
Input
Your function will receive an array whose elements are subarrays in the form [h,w] where h and w represent the height and width, respectively, of each building in sequence
Output
An array of latch points (integers) to get from 0 to the end of the last building in the input list
Technical Details

An optimal latch point is one that yields the greatest horizontal distance gain relative to length of web rope used. Specifically, the highest horizontal distance yield per length unit of web rope used. Give this value rounded down to the nearest integer as a distance from Spidey's origin point (0)
At the start of each swing, Spidey selects a latch point based on his current position.
At the end of each swing, Spidey ends up on the opposite side of the latch point equal to his distance from the latch point before swing.
Spidey's initial altitude is 50, and will always be the same at the start and end of each swing. His initial horizontal position is 0.
To avoid collision with people/traffic below, Spidey must maintain a minimum altitude of 20 at all times.
Building height (h) range limits: 125 <= h < 250
Building width (w) range limits: 50 <= w <= 100
Inputs will always be valid.

Test Example

- Spidey's initial position is at `0`. His first latch point is marked at `76` (horizontal position) on `buildings[0]`.
- At the end of the swing, Spidey's position is at the point marked `B` with a horizontal position of `152`. The green arc represents Spidey's path during swing.
- The marker on the 3rd building and the arc going from point `B` to point `C` represent the latch point (`258`) and arc path for the next swing.

```python
buildings =...

import math

def calc_web_length(current_loc, swing_point):
    x = swing_point[0] - current_loc[0]
    y = swing_point[1] - current_loc[1]
    x_travel = 2 * x
    web_length = math.sqrt(pow(x, 2) + pow(y, 2))
    bottom_height = swing_point[1] - web_length
    return x_travel, web_length, bottom_height

def spidey_swings(ar):
    buildings = ar

    # replace the building X positions with cumulative distances and
    # ALL integer points along the way (inclusive)
    # swap the order while we're at it to get normal (x,y) points
    latch_points = []
    prev_x = 0
    for building in buildings:
        for x in range(building[1] + 1):
            latch_points.append([x + prev_x, building[0]])
        prev_x += building[1]

    # Record the final X position to be used for termination criteria
    max_x = latch_points[-1][0]

    # Loop Variables
    current_location = [0, 50]
    swing_list = []
    swing_end = None
    best_ratio = -999.0
    best_building = None

    while True:
        building = latch_points.pop(0)

        # Skip all latch points we may have passed during the swing
        if building[0] <= current_location[0]:
            continue

        # Calculate data for the current 'test' latch point
        x_travel, length, height = calc_web_length(current_location, building)
        ratio = float(x_travel) / length

        # Special check for end condition, this may be an non 'optimal' swing but
        # if it lands exactly on the final position, it is the final latch point
        if current_location[0] + x_travel >= max_x:
            best_ratio = ratio
            best_building = building
            for ltch_pt in latch_points[:20]:
                x_travel2, length2, height2 = calc_web_length(current_location, ltch_pt)
                swing_end2 = current_location[0] + x_travel2

                # Since this is at the end, we might over-travel, remove that extra
                # distance when calculating the web ratio
                extra_x = swing_end2 - max_x
               ...


Solve in Python:
Spin-off of this kata, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers starting from 1 up to n.

Hints: a solution in linear time can be found; using the most intuitive ones to search for duplicates that can run in O(n²) time won't work.

def find_dup(arr):
    return sum(arr) - sum(range(1, max(arr)+1))


Solve in Python:
Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway!  If you don't yet know what a spoonerism is and haven't yet tried my spoonerism kata, please do [check it out](http://www.codewars.com/kata/spoonerize-me) first.

You will create a function which takes an array of two positive integers, spoonerizes them, and returns the positive difference between them as a single number or ```0``` if the numbers are equal:
```
[123, 456] = 423 - 156 = 267
```
Your code must test that all array items are numbers and return ```"invalid array"``` if it finds that either item is not a number.  The provided array will always contain 2 elements.

When the inputs are valid, they will always be integers, no floats will be passed.  However, you must take into account that the numbers will be of varying magnitude, between and within test cases.

def noonerize(numbers):
    output = '{}{}'.format
    if any(not isinstance(a, int) for a in numbers):
        return 'invalid array'
    b, c = (str(d) for d in numbers)
    return abs(int(output(c[0], b[1:])) - int(output(b[0], c[1:])))


Solve in Python:
Spring is interesting season of year. Chef is thinking about different things, but last time he thinks about interesting game - "Strange Matrix".
Chef has a matrix that consists of n rows, each contains m elements. Initially, the element aij of matrix equals j. (1 ≤ i ≤ n, 1 ≤ j ≤ m).
Then p times some element aij is increased by 1.
Then Chef needs to calculate the following:

- For each row he tries to move from the last element (with number m) to the first one (with the number 1).
- While staying in aij Chef can only move to aij - 1 only if aij - 1 ≤ aij.
- The cost of such a movement is aij - aij - 1.
- Otherwise Chef can't move and lose (in this row).
- If Chef can move from the last element of the row to the first one, then the answer is the total cost of all the movements.
- If Chef can't move from the last element of the row to the first one, then the answer is -1.

Help Chef to find answers for all the rows after P commands of increasing.

-----Input-----

- The first line contains three integers n, m and p denoting the number of rows, the number of elements a single row and the number of increasing commands.
- Each of next p lines contains two integers i and j denoting that the element aij  is increased by one.

-----Output-----
- For each row in a single line print the answer after the P increasing commands.

-----Constraints-----
- 1 ≤ n, m, p ≤ 10 ^ 5
- 1 ≤ i ≤ n
- 1 ≤ j ≤ m

-----Example-----
Input:
4 4 6
2 2
3 2
3 2
4 3
4 4
4 3

Output:
3
3
-1
4

-----Explanation-----

Here is the whole matrix after P commands:
1 2 3 4
1 3 3 4
1 4 3 4
1 2 5 5

Explanations to the answer:
- The first line is without changes: 4-3=1, 3-2=1, 2-1=1. answer = 3.
- The second line: 4-3=1, 3-3=0, 3-1=2. The answer is 3.
- The third line: 4-3=1, 3-4=-1, Chef can't move to the first number here. Therefore, the answer is -1.
- The fourth line: 5-5=0, 5-2=3, 2-1=1. The answer is 4.

def __starting_point():
 n,m,p = list(map(int, input().split()))
 hit={}
 sums={}
 for i in range(1,n+1):
  hit[i]={}
  sums[i]=m-1
 for _ in range(p):
  i,j = list(map(int, input().split()))
  if j not in hit[i]:
   hit[i][j]=1
  else:
   hit[i][j]+=1
 for i in range(1,n+1):
  done = True
  for j in hit[i]:
   if j!=m and (hit[i][j] - hit[i].get(j+1,0)) > 1:
    done=False
    break
   if j==1 and m>1: sums[i]-=hit[i][j]
   elif j==m and m>1: sums[i]+=hit[i][j]
  if done:
   print(sums[i])
  else:
   print(-1)

__starting_point()


Solve in Python:
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.

The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].

You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

-----Input-----

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 10^6). Each character in s will be either "l" or "r".

-----Output-----

Output n lines — on the i-th line you should print the i-th stone's number from the left.

-----Examples-----
Input
llrlr

Output
3
5
4
2
1

Input
rrlll

Output
1
2
5
4
3

Input
lrlrr

Output
2
4
5
3
1

-----Note-----

In the first example, the positions of stones 1, 2, 3, 4, 5 will be $\frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{3}{16}, \frac{5}{32}$, respectively. So you should print the sequence: 3, 5, 4, 2, 1.

inp = input()
length = len(inp)
min,max,dic1,dic2 = 1,length,[],[]
for i in range(0,length):
    if inp[i] == "l":
        dic2.append(i+1)
    else:
        dic1.append(i+1)

print('\n'.join(map(str, dic1)))
print('\n'.join(map(str, dic2[::-1])))


Solve in Python:
Stacey is a big [AD&D](https://en.wikipedia.org/wiki/Dungeons_%26_Dragons) games nerd. Moreover, she's a munchkin. Not a [cat breed](https://en.wikipedia.org/wiki/Munchkin_cat), but a person who likes to get maximum efficiency of their character.

As you might know, many aspects of such games are modelled by rolling dice and checking it against a threshold value determined by various aspects.
Stacey wants to always control the situation and know whether she can beat the foe with certain special ability or not. Unfortunately she doesn't know probabilty theory well enough. Help Stacey by providing a calculating utility for her.

P.S.: Stacey says that she has tried to implement a calculator by Monte-Carlo modelling: calling rand() in a loop, but she hasn't been satisfied with precision of this method.

### Examples

`P(1d6 >= 4)` means the chance of getting 4 points or higher on a regular cubic die. Obviously the chance is `3/6` cause there're 6 possibilities in total (1, 2, 3, 4, 5, 6) and only three of them are >= 4: (4, 5, 6)

`P(2d6 >= 3)` gives us `35/36`, cause the only possibility to get < 3 is rolling exactly 1+1.
Exactly 2 as sum of two dice appears only if both have 1. While total amount of different outcomes is 6\*6 = 36. Hence resulting probability is 1-1/36, which is 35/36

### Your task

is to write a function, which will calculate the probability of that a die with `N` sides rolled `M` times (`MdN` in AD&D notation) will get at least `T` points. We don't add modifiers cause they are already incorporated into the threshold.

Input arguments will be valid integers with the following limits:

- `rolls` 1..20
- `sides` 2..100
- `threshold` 1..2000

memo={}
def roll_dice (rolls, sides, threshold):
    memo={}
    r=0
    for i in range(rolls,threshold):
        r+=_roll_dice(rolls,sides,i)
    return 1-r

def _roll_dice (rolls, sides, s):
    if s<1:
        return 0
    elif rolls==1:
        if s>sides:
            return 0
        return 1/sides
    key=(rolls,sides,s)
    if key in memo:
        return memo[key]
    r=0
    for i in range(1,sides+1):
       r+=_roll_dice(rolls-1,sides,s-i)
    memo[key]=r/sides
    return r/sides


Solve in Python:
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this in a way such that the resulting number is a power of 2.

Example 1:
Input: 1
Output: true

Example 2:
Input: 10
Output: false

Example 3:
Input: 16
Output: true

Example 4:
Input: 24
Output: false

Example 5:
Input: 46
Output: true

Note:

1 <= N <= 10^9

class Solution:
    def reorderedPowerOf2(self, N: int) -> bool:
        maxn = 10 ** 9
        twopower = 1
        twosets = set()
        while twopower <= maxn:
            twosets.add(twopower)
            twopower *= 2
        permutations = self.get_all_permutation(N)
        for p in permutations:
            if p[0] != '0' and int(p) in twosets:
                return True
        return False

    def get_all_permutation(self, num):
        perm = {''}
        for n in str(num):
            perm = {p[:i] + n + p[i:] for p in perm  for i in range(len(p) + 1)}
        return perm


Solve in Python:
Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivisions are made to some of the edges.
The graph is given as follows: edges[k] is a list of integer pairs (i, j, n) such that (i, j) is an edge of the original graph,
and n is the total number of new nodes on that edge.
Then, the edge (i, j) is deleted from the original graph, n new nodes (x_1, x_2, ..., x_n) are added to the original graph,
and n+1 new edges (i, x_1), (x_1, x_2), (x_2, x_3), ..., (x_{n-1}, x_n), (x_n, j) are added to the original graph.
Now, you start at node 0 from the original graph, and in each move, you travel along one edge.
Return how many nodes you can reach in at most M moves.

Example 1:
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3
Output: 13
Explanation:
The nodes that are reachable in the final graph after M = 6 moves are indicated below.

Example 2:
Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4
Output: 23

Note:

0 <= edges.length <= 10000
0 <= edges[i][0] < edges[i][1] < N
There does not exist any i != j for which edges[i][0] == edges[j][0] and edges[i][1] == edges[j][1].
The original graph has no parallel edges.
0 <= edges[i][2] <= 10000
0 <= M <= 10^9
1 <= N <= 3000
A reachable node is a node that can be travelled to using at most M moves starting from node 0.

import collections
class Solution:
    def reachableNodes(self, edges: List[List[int]], M: int, N: int) -> int:
        graph = collections.defaultdict(dict)
        for i, j, w in edges:
            graph[i][j] = graph[j][i] = w
        # min queue for dijastra (distance from source, vertex)
        pq = [(0,0)]
        # weight used from u to v
        used = {}
        # min distance from source
        dist = {0: 0}
        res = 0

        while pq:
            d, v = heapq.heappop(pq)
            # dist in this path greater than previous route, no need to searching
            if d > dist[v]:
                continue
            # count this vertex
            res += 1

            for nei, weight in list(graph[v].items()):
                # insert how much weight/nodes can be used in edge v->nei
                use_wei = min(weight, M - d)
                used[v, nei] = use_wei

                # get min dis to next node
                d_min = d + weight + 1
                # if next node is not visited and distance smaller than M + 1
                # or has been visited but has greater distance from source
                # we can update distance and push new vertex to heap
                if d_min < dist.get(nei, M + 1):
                    dist[nei] = d_min
                    heapq.heappush(pq,(d_min, nei))

        # insert traveled mid nodes to res
        for i, j, w in edges:
            res += min(w, used.get((i, j), 0) + used.get((j, i), 0))
        return res


Solve in Python:
Step through my `green glass door`.

You can take the `moon`, but not the `sun`.

You can take your `slippers`, but not your `sandals`.

You can go through `yelling`, but not `shouting`.

You can't run through `fast`, but you can run with `speed`.

You can take a `sheet`, but not your `blanket`.

You can wear your `glasses`, but not your `contacts`.

Have you figured it out? Good! Then write a program that can figure it out as well.

def step_through_with(s):
    return any(s[i-1] == x for i, x in enumerate(s[1:], 1))


Solve in Python:
Steve and Josh are bored and want to play something. They don't want to think too much, so they come up with a really simple game. Write a function called winner and figure out who is going to win.

They are dealt the same number of cards. They both flip the card on the top of their deck. Whoever has a card with higher value wins the round and gets one point (if the cards are of the same value, neither of them gets a point). After this, the two cards are discarded and they flip another card from the top of their deck. They do this until they have no cards left.

`deckSteve` and `deckJosh` are arrays representing their decks. They are filled with *cards*, represented by a single character. The card rank is as follows (from lowest to highest):
```
'2','3','4','5','6','7','8','9','T','J','Q','K','A'
```

Every card may appear in the deck more than once. Figure out who is going to win and return who wins and with what score:
* `"Steve wins x to y"` if Steve wins; where `x` is Steve's score, `y` is Josh's score;
* `"Josh wins x to y"` if Josh wins; where `x` is Josh's score, `y` is Steve's score;
* `"Tie"` if the score is tied at the end of the game.

## Example

* Steve is dealt: `['A','7','8']`
* Josh is dealt: `['K','5','9']`

1. In the first round, ace beats king and Steve gets one point.
2. In the second round, 7 beats 5 and Steve gets his second point.
3. In the third round, 9 beats 8 and Josh gets one point.

So you should return: `"Steve wins 2 to 1"`

def winner(deck_steve, deck_josh):
    ls = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
    st = 0
    jo = 0
    for k, v in enumerate(deck_josh):
        if ls.index(v) > ls.index(deck_steve[k]):
            jo += 1
        elif ls.index(v) < ls.index(deck_steve[k]):
            st += 1
    return "Tie" if st == jo else "{} wins {} to {}".format('Steve' if st > jo else "Josh", max(st, jo), min(st, jo))


Solve in Python:
Storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by a grid of size m x n, where each element is a wall, floor, or a box.
Your task is move the box 'B' to the target position 'T' under the following rules:

Player is represented by character 'S' and can move up, down, left, right in the grid if it is a floor (empy cell).
Floor is represented by character '.' that means free cell to walk.
Wall is represented by character '#' that means obstacle  (impossible to walk there).
There is only one box 'B' and one target cell 'T' in the grid.
The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.
The player cannot walk through the box.

Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.

Example 1:

Input: grid = [["#","#","#","#","#","#"],
               ["#","T","#","#","#","#"],
               ["#",".",".","B",".","#"],
               ["#",".","#","#",".","#"],
               ["#",".",".",".","S","#"],
               ["#","#","#","#","#","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.
Example 2:
Input: grid = [["#","#","#","#","#","#"],
               ["#","T","#","#","#","#"],
               ["#",".",".","B",".","#"],
               ["#","#","#","#",".","#"],
               ["#",".",".",".","S","#"],
               ["#","#","#","#","#","#"]]
Output: -1

Example 3:
Input: grid = [["#","#","#","#","#","#"],
               ["#","T",".",".","#","#"],
               ["#",".","#","B",".","#"],
               ["#",".",".",".",".","#"],
               ["#",".",".",".","S","#"],
               ["#","#","#","#","#","#"]]
Output: 5
Explanation:  push the box down, left, left, up and up.

Example 4:
Input: grid = [["#","#","#","#","#","#","#"],
               ["#","S","#",".","B","T","#"],
               ["#","#","#","#","#","#","#"]]
Output:...

class Solution:
    def minPushBox(self, grid: List[List[str]]) -> int:
        m, n = len(grid), len(grid[0])
        moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]

        def check(p1, p2, t1, t2, b1, b2):#g is new grid
            visited = visited = [[False for _ in range(n)] for _ in range(m)]
            queue = collections.deque()
            queue.append((p1, p2))
            visited[p1][p2] = True

            while queue:
                x, y = queue.popleft()
                if (x, y) == (t1, t2):
                    return True
                for dx, dy in moves:
                    nx, ny = x + dx, y + dy
                    if 0 <= nx < m  and 0 <= ny < n:
                        if visited[nx][ny]: continue
                        if (nx, ny) == (t1, t2): return True
                        if (nx, ny) != (b1, b2) and grid[nx][ny] != '#':
                            queue.append((nx, ny))
                            visited[nx][ny] = True
            return False

        def inbound(x, y):
            return 0 <= x < m and 0 <= y < n

        for i in range(m):
            for j in range(n):
                if grid[i][j] != '#':
                    if grid[i][j] == 'S':
                        player = (i, j)
                    elif grid[i][j] == 'B':
                        box = (i, j)
                    elif grid[i][j] == 'T':
                        end = (i, j)
        #player box end
        p1, p2 = player
        b1, b2 = box
        e1, e1 = end

        visited = set()
        step = -1

        queue = collections.deque()
        queue.append((b1, b2, p1, p2))

        while queue:
            step += 1
            for _ in range(len(queue)):#别忘了是层序遍历！！！
                x, y, p1, p2 = queue.popleft()
                #up
                if inbound(x - 1, y) and inbound(x + 1, y) and grid[x + 1][y] != '#' and check(p1, p2, x + 1, y, x, y):
                    if (x - 1, y, x, y) not in visited:
                 ...


Solve in Python:
Story
Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra special fruits cost $9 per each. There is no limit on how many fruits she/he picks.The price of a cup of juice is the mean of price of chosen fruits. In case of decimal number (ex. $5.99), output should be the nearest integer (use the standard rounding function of your language of choice).

Input
The function will receive an array of strings, each with the name of a fruit. The recognition of names should be case insensitive. There is no case of an enmpty array input.

Example

```
['Mango', 'Banana', 'Avocado'] //the price of this juice bottle is (7+5+7)/3 = $6($6.333333...)
```

PRICES = dict(banana=5, orange=5, apple=5, lemon=5, grapes=5, avocado=7, strawberry=7, mango=7)

def mix_fruit(fruits):
    return round(sum(PRICES.get(fruit.lower(), 9) for fruit in fruits) / len(fruits))


Solve in Python:
Story:
In the realm of numbers, the apocalypse has arrived. Hordes of zombie numbers have infiltrated and are ready to turn everything into undead. The properties of zombies are truly apocalyptic: they reproduce themselves unlimitedly and freely interact with each other. Anyone who equals them is doomed. Out of an infinite number of natural numbers, only a few remain. This world needs a hero who leads remaining numbers in hope for survival: The highest number to lead those who still remain.

Briefing:
There is a list of positive natural numbers. Find the largest number that cannot be represented as the sum of this numbers, given that each number can be added unlimited times. Return this number, either 0 if there are no such numbers, or -1 if there are an infinite number of them.

Example:
```
Let's say [3,4] are given numbers. Lets check each number one by one:
1 - (no solution) - good
2 - (no solution) - good
3 = 3 won't go
4 = 4 won't go
5 - (no solution) - good
6 = 3+3 won't go
7 = 3+4 won't go
8 = 4+4 won't go
9 = 3+3+3 won't go
10 = 3+3+4 won't go
11 = 3+4+4 won't go
13 = 3+3+3+4 won't go
```
...and so on. So 5 is the biggest 'good'. return 5

Test specs:
Random cases will input up to 10 numbers with up to 1000 value

Special thanks:
Thanks to Voile-sama, mathsisfun-sama, and Avanta-sama for heavy assistance. And to everyone who tried and beaten the kata ^_^

# a1, a2, a3, ... are the zombies numbers
# For a number x to be represented as a sum of those zombies, it means n-a1 or n-a2 or n-a3 or ... has to be represented
# From that, we can dynamically find if a number is representable (function "represent")
#
# an is the biggest zombie number
# If x is represented, then x + an is represented too
# Wich means we can divide numbers from 0 into groups of size an
# If the element i of a group is representable, then it will still be in the next group
#
# If the kth group is the same as the (k-1)th group, then it means no new number is representable
# In this case, there will be an infinite number of survivors
#
# If all number in the kth are representable, then it means the biggest non-representable number was in the previous group
# So we just find the biggest non-representable number of the previous group
#
# After an iterations of this, either we found there are infinites survivors
# Or we already filled the group (since they have a size of an)

from functools import lru_cache

def survivor(zombies):
    if not zombies: return -1
    nums = sorted(zombies)
    represent = lru_cache(maxsize=None)(lambda x: not x or any(represent(x-y) for y in nums[::-1] if x >= y))
    maxi = nums[-1]
    current = [0]*maxi
    for x in range(0, maxi**2, maxi):
        temp = [current[i] or represent(x+i) for i in range(maxi)]
        if temp == current: return -1
        if all(temp):
            y = next(i for i,v in enumerate(current[::-1]) if not v)
            return max(0, x-y-1)
        current = temp


Solve in Python:
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1

Example 2:
Input: A = "abc", B = "bca"
Output: 2

Example 3:
Input: A = "abac", B = "baca"
Output: 2

Example 4:
Input: A = "aabc", B = "abca"
Output: 2

Note:

1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}

class Solution:
    @lru_cache(None)
    def kSimilarity(self, A: str, B: str) -> int:
        if len(A) == 0: return 0
        if A[0]==B[0]: return self.kSimilarity(A[1:],B[1:])

        ans = math.inf
        for i in range(1,len(B)):
            if B[i]==A[0]: ans = min(ans, 1+self.kSimilarity(A[1:],B[1:i]+B[0]+B[i+1:]))
        return ans


Solve in Python:
Striver$Striver$ wants to strive hard in order to reach his goals, hence asks his mentor to give him a question for which he has to strive hard.
The mentor gives Striver$Striver$ a N$N$ X N$N$ matrix consisting of lowercase characters (′a′$'a'$ to ′z′$'z'$) and Q$Q$ queries. Every query consists of X$X$ and Y$Y$. From any position in the matrix, one can either move towards the right or towards down. He asks striver to write down all the paths from (1,1)$(1, 1)$ to (X,Y)$(X, Y)$ and find out which string has the maximum number of character ′a′$'a'$ in it and answer him the number of characters which are not 'a' in that string.
Striver wants to strive hard but also wants to impress his mentor. He asks for your help to answer Q$Q$ queries given by his mentor as fast as he can so that he can impress his mentor also. Can you help him to answer the Q queries?

-----Input:-----
- First line will contain T$T$, number of test cases. Then the test cases follow.
- First line of every test case contains a number N$N$ and Q$Q$ which denotes the dimensions of the matrix and number of queries respectively.
- N lines follow, which contains N numbers each denoting the elements of the matrix.
- Q line follow, every line contains X and Y.

-----Output:-----
For every test case, print a single integer which prints the answer to mentor's every query.

-----Constraints-----
- 1≤T≤10$1 \leq T \leq 10$
- 1≤N≤103$1 \leq N \leq 10^3$
- 1≤Q≤105$1 \leq Q \leq 10^5$
- 1≤X,Y≤N$1 \leq X, Y \leq N$

-----Sample Input:-----
1
3 2
a b a
a c d
b a b
1 3
3 3

-----Sample Output:-----
1
2

-----EXPLANATION:-----
Query-1: There is only one path from (1,1) to (1,3) i.e.,"aba" and the number of characters which are not 'a' is 1.
Query-2:  The path which has the maximum number of 'a' in it is "aabab", hence non 'a' characters are 2.


Solve in Python:
Stuart is obsessed to numbers. He like all type of numbers in fact he is having a great collection of numbers in his room. His collection includes N different large numbers. But today he is searching for a number which is having maximum frequency of digit X. Numbers are large so he can’t do the task on his own. Help him to find a number having maximum frequency of digit X.

-----Input-----
First Line contains number of test cases T. First Line of each test case contains N. Next line contains N space separated integers A1,A2,A3,....,AN. Where Ai integer indicates ith number in Stuart's room. Next Line contains digit X.

-----Output-----
Output the number which is having maximum frequency of digit X. If two or more numbers are having same maximum frequency then output the first occurred number among them in A1,A2,A3,....,AN

-----Constraints-----
- 1 ≤ T ≤ 30
- 1 ≤ N ≤ 100
- 1 ≤ Ai ≤ 10200
- 0 ≤ X ≤ 9

-----Example-----
Input:
2
5
345 1323 165 98 456
3
5
335 876 98 1323 349
3

Output:
1323
335

-----Explanation-----
Example case 1. 1323 number is having maximum occurrence of digit 3.
Example case 2. 335 & 1323 are having maximum occurrence of digit 3 so output must be first occurred number in the array i.e. 335.

#write your code in next line.
a=int(input())
while(a):
 b=int(input())
 c=str(input()).split()
 d=str(input())
 l=0
 m=0
 x=0
 while(b):
  l=c[b-1].count(d)
  if l>=x:
   x=l
   m=c[b-1]
  b-=1
 a-=1
 print(m)


Solve in Python:
Student A and student B are giving each other test answers during a test.
They don't want to be caught so they are sending each other coded messages.

Student A is sending student B the message: `Answer to Number 5 Part b`.
He starts of with a square grid (in this example the grid = 5x5).
He writes the message down (with spaces):

```
Answe
r to
Numbe
r 5 P
art b
```

He then starts writing the message down one column at a time (from the top to the bottom).
The new message is now: `ArNran u rstm5twob  e ePb`

You are the teacher of this class.
Your job is to decipher this message and bust the students.

# Task

Write a function `decipher_message`.
This function will take one parameter (`message`).
This function will return the original message.
*** Note: The length of the string is always going to be a prefect square ***

Hint: You should probably decipher the example message first before you start coding

Have fun !!!

import math
def decipher_message(m):
    l = int(math.sqrt(len(m)))
    return ''.join(''.join(m[i+l*j] for j in range(l)) for i in range(l))


Solve in Python:
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

Example 1:
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array  : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.

Example 2:
Input: heights = [5,1,2,3,4]
Output: 5

Example 3:
Input: heights = [1,2,3,4,5]
Output: 0

Constraints:

1 <= heights.length <= 100
1 <= heights[i] <= 100

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        hs = heights[:]
        for e in range(len(hs) - 1, 0, -1):
            mx, ix = float('-inf'), -1
            for i, h in enumerate(hs[:e + 1]):
                if h >= mx:
                    ix, mx = i, h
            hs[e], hs[ix] = hs[ix], hs[e]
        return sum(a != b for a, b in zip(hs, heights))


Solve in Python:
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."

The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.

Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.

-----Input-----

The only line contains two integers n and m (1 ≤ n, m ≤ 10^5; n·m ≤ 10^5) — the number of rows and the number of columns in the required matrix.

-----Output-----

If there is no such matrix, output "NO" (without quotes).

Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.

-----Examples-----
Input
2 4

Output
YES
5 4 7 2
3 6 1 8

Input
2 1

Output
NO

-----Note-----

In the first test case the matrix initially looks like this:

1 2 3 4

5 6 7 8

It's easy to see that there are no two students that are adjacent in both matrices.

In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.

n,m=map(int,input().split())
if n==1and m==1:print('YES\n1')
elif n==3and m==3:
    print('YES')
    print(6, 1, 8)
    print(7,5,3)
    print(2,9,4)
elif n<4and m<4:print('NO')
elif n==1 or m==1:
    t=max(n,m)
    a=[i for i in range(2,t+1,2)]
    a+=[i for i in range(1,t+1,2)]
    print('YES')
    for i in a:print(i,end="");print([' ','\n'][m==1],end='')
else:
    a=[]
    for j in range(n):
        a.append([int(i)+int(m*j) for i in range(1,m+1)])
    if n<=m:
        for j in range(1,m,2):
            t=a[0][j]
            for i in range(1,n):
                a[i-1][j]=a[i][j]
            a[n-1][j]=t
        for i in range(1,n,2):
            r,s=a[i][0],a[i][1]
            for j in range(2,m):
                a[i][j-2]=a[i][j]
            a[i][m-2],a[i][m-1]=r,s
    else:
        for j in range(1,m,2):
            r,s=a[0][j],a[1][j]
            for i in range(2,n):
                a[i-2][j]=a[i][j]
            a[n-2][j], a[n-1][j] = r, s
        for i in range(1,n,2):
            t=a[i][0]
            for j in range(1,m):
                a[i][j-1]=a[i][j]
            a[i][m-1]=t
    print('YES')
    for i in range(n):
        print(*a[i])


Solve in Python:
Sultan, the freestyle wrestler, you all know him. He broke multiple records in the history of all wrestling leagues. Now 20 years have passed, Sultan has grown old. He has two sons, he wants them to be like him. Sultan being orthodox goes to his astrologer, where he is told that his sons shall be invincible like him.
Sultan starts to train them. After training, his son Multan & Fultan, having strengths are M and F respectively, decide to fight. They can defeat if the strength of challengers Si is a positive integer multiple of their strength else they lose. Multan fights first, then Fultan. A challenger once knocked out cannot challenge them again. Sultan's sons are still not very good wrestlers. Sultan considers them wrestlers if they both combined are able to win at least 70% of the all the fights. Also, he wants to know who is a better wrestler of the two. Your task is to help Sultan in this venture. Print "Yes" (without quotes) if they are able to win, else print "No" (without quotes). If yes, also name whether, "Multan" or "Fultan" is a better wrestler, if both win equally print “Both”.

-----Input-----
- First line contains single integer T denoting test cases.
- Second Line contains single integer N for number of challengers.
- Third Line contains space separated two integer denoting strength M & F
- Next Line contains strength space separated N integer ith of which denoting Si of N challengers respectively.

-----Output-----
- Yes or No corresponding the result.
- Also, if Yes, print, Multan, Fultan, Both accordingly.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 1000
- 1 ≤ M, F ≤ 109
- 0 ≤ Si ≤ 109

-----Example-----
Input:
2
7
2 3
4 5 7 8 9 10 14
6
5 7
1 2 8 9 10 11

Output:
Yes
Multan
No

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

Multan (M) defeats total 4 challengers with strengths 4, 8, 10, 14 and Fultan (F) defeats 1 challenger with strength 9. Their total wins are 5 out of 7 and win accuracy of 71.4%. Hence, 'Yes' and since Multan is better wrestler so 'Multan'

Example case 2.
Multan defeats...

t=eval(input())
while t:
 n=eval(input())
 m,f=list(map(int,input().split()))
 multan=0
 total=0
 fultan=0
 s=list(map(int,input().split()))
 for i in s:
  if i==0:
   continue
  if i%m==0:
   multan+=1;
   total+=1
  elif i%f==0:
   fultan+=1
   total+=1
 if total-0.7*n>=0.0:
  print("Yes")
  if multan>fultan:
   print("Multan")
  elif fultan>multan:
   print("Fultan")
  else:
   print("Both")
 else:
  print("No")
 #print total,multan,fultan
 t-=1


Solve in Python:
Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!).
(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!)
Example:
```
{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6
```

If array is empty, null or None, or if only 1 Element exists, return 0.
Note:In C++ instead null an empty vector is used. In C there is no null. ;-)

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have created other katas. Have a look if you like coding and challenges.

def sum_array(arr):
    if arr == None or arr == [] or len(arr) == 1:
        return 0
    else:
        return sum(x for x in arr) - min(arr) - max(arr)


Solve in Python:
Sumit and Dhiraj are roommates in a hostel of NIT Jamshedpur,One day after completing there boring assignments of Artificial Intelligence, they decided to play a game as it was dhiraj,s idea to play a game so he started explaining the rules of the game to sumit.
So the game was as follows-They randomly took a number N after that they find all its divisors.Suppose first sumit took a divisor then dhiraj and so on.The player who will be having the last divisor with him will win the game.Rohit their mutual friend,was observing them play. Can you help Rohit predict the outcome of game? If Sumit wins print "YES" without quotes and "NO" without quotes, if Dhiraj wins
the game.

-----Input-----
Input starts with an integer T denoting the number of test cases Each test case starts with a line containing an integer N the number.

-----Output-----
Outcome of each game in a separate line

-----Constraints-----
- 1 ≤ T ≤ 10^3
- 1 ≤ N ≤ 10^18

-----Sub tasks-----
- Subtask #1:(10 points)

- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 103
- Subtask #2:(25 points)

- 1 ≤ T ≤ 50
- 1 ≤ N ≤ 1016
- Subtask #3:(65 points)

- 1 ≤ T ≤ 103
- 1 ≤ N ≤ 1018

-----Example-----
Input:
2
4
5

Output:
YES
NO

t=int(input());
for i in range (0,t):
 c=0;
 n=int(input());
 for j in range (1,n+1):
  if(n%j==0):
   c=c+1;
 if(c%2==0):
  print("NO\n");
 else:
  print("YES\n");


Solve in Python:
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.

Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].

There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.

If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.

-----Input-----

The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 10^5).

-----Output-----

The output contains a single number — the maximum total gain possible.

-----Examples-----
Input
3 3
100 100 100
100 1 100
100 100 100

Output
800

-----Note-----

Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].

'''input
3 3
100 100 100
100 1 100
100 100 100
'''
# again a coding delight
from sys import stdin

def create_dp1(matrix, n, m):
	dp = [[0 for i in range(m)] for j in range(n)]
	for i in range(n):
		for j in range(m):
			if i - 1 >= 0:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
			if j - 1 >= 0:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
			elif i - 1 < 0 and j - 1 < 0:
				dp[i][j] = matrix[i][j]
	return dp

def create_dp2(matrix, n, m):
	dp = [[0 for i in range(m)] for j in range(n)]
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if i + 1 < n:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
			if j + 1 < m:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
			if i + 1 >= n and j + 1 >= m:
				dp[i][j] = matrix[i][j]
	return dp

def create_dp3(matrix, n, m):
	dp = [[0 for i in range(m)] for j in range(n)]
	for i in range(n - 1, -1, -1):
		for j in range(m):
			if i + 1 < n:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
			if j - 1 >= 0:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
			if i + 1 >= n and j - 1 < 0:
				dp[i][j] = matrix[i][j]
	return dp

def create_dp4(matrix, n, m):
	dp = [[0 for i in range(m)] for j in range(n)]
	for i in range(n):
		for j in range(m - 1, -1, -1):
			if i - 1 >= 0:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
			if j + 1 < m:
				dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
			if i - 1 < 0 and j + 1 >= m:
				dp[i][j] = matrix[i][j]
	return dp

# main starts
n, m = list(map(int, stdin.readline().split()))
matrix = []
for _ in range(n):
	matrix.append(list(map(int, stdin.readline().split())))

dp1 = create_dp1(matrix, n, m) # from 0, 0 to i, j
dp2 = create_dp2(matrix, n, m) # from i, j to n, m
dp3 = create_dp3(matrix, n, m) # from n, 1 to i, j
dp4 = create_dp4(matrix, n, m) # from i, j to 1, m

total = -float('inf')
for i in range(1, n - 1):
	for j in range(1, m - 1):
		first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]
		second =...


Solve in Python:
Sunita has lots of tasks pending and she has no time to complete.  She needs your help and wants you complete the task.
You are given a list of integers and two values $N$ and $K$ $-$ the size of array of integers and the numbers of partitions to be made respectively.
You have to partition the list of integers without changing the order of elements ,into exactly $K$ parts.
Calculate Greatest Common Divisor of all $K$ partition and sum up the gcd values for each partition.
Maximize the sum obtained.
Can you help Sunita ?

-----Input:-----
- First line will contain $T$, number of test cases. Then the test cases follow.
- Each test case contains of a single line of input, two integers $N, K$.
- Next line contains $N$ integers $-$ the list of integers.

-----Output:-----
For each test case, output in a single line integer $-$ the maximal result.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N, K \leq 250$
- $1 \leq K \leq N$
- $1 \leq A[i] \leq 1e5$

-----Sample Input:-----
1
4 2
5 6 3 2

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

-----EXPLANATION:-----
[5] [6 3 2] is the best partition [5 + GCD(6,3,2)] = 6

from sys import stdin,stdout
from math import gcd
for _ in range(int(stdin.readline())):
    # n=int(stdin.readline()) k-pieces
    n,k=list(map(int,stdin.readline().split()))
    a=list(map(int,stdin.readline().split()))
    gr=[[0 for _ in range(n)]for _ in range(n)];ans=0;k-=1
    for sz in range(n):
        for i in range(n-sz):
            j=i+sz
            if sz==0:gr[i][j]=a[i]
            else:
                gr[i][j]=gcd(gr[i+1][j],gr[i][j-1])
    # print(*gr,sep='\n')
    dp=[[0 for _ in range(n)]for _ in range(k+1)]
    for i in range(n):
        dp[0][i]=gr[0][i]
    for i in range(1,k+1):
        for j in range(i,n):
            for par in range(j-1,-1,-1):
                dp[i][j]=max(dp[i][j],gr[par+1][j]+dp[i-1][par])
    # print(*dp,sep='\n')
    print(dp[k][n-1])


Solve in Python:
Supermarket Dilemma
Chef is going to local supermarket but there appears a problem with chef as he is confused about which Supermarket he can choose to go as he is not able to decide whether he can park his car in that particular supermarket’s parking lot or not! There are N parking slots in each supermarket which are marked from 1,2,3,4…N.
Chef will go to that supermarket in which he gets to know that there is exactly 1 empty parking slot having number K that exactly divides the total number of slots (N) available in that supermarket.
The 1st and Nth parking slots are always occupied by the staff of every supermarket. Rest parking slots are empty as Chef is arriving early morning to the supermarket.
Now Chef needs your help in determining whether he can park his car in a supermarket or not!
Input
The first line contains the single integer N showing how many supermarkets are there for the chef to choose.
The next N lines contain a number ‘ai’ which represents the total parking slots available in ith supermarket.
Output
You need to output "YES" (without the quotes), if a supermarket can be reached by Chef, and "NO" (without the quotes), if it can't.
Constraints
1<=N<=10^5
1<=ai<=10^12
Sample Input :
2
4
5
Sample Output :
YES
NO

import math

def check(s):
    if s==2:
        return 1

    for i in range(2,math.ceil(math.sqrt(s))+1):
        if s%i == 0:
            return 0

    return 1

def Solve(slots):
  if slots<3:
    return 0

  #check
  s = math.sqrt(slots)
  if math.floor(s) == math.ceil(s):
      return check(s)

  return 0

N = int(input())

for t in range(N):

  slots = int(input())

  if (Solve(slots)):
    print("YES")

  else:
    print("NO")


Solve in Python:
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as:

```
a1*b1 + a2*b2 + a3*b3 + ... + aN*bN
```

The vectors are classified as orthogonal if the dot product equals zero.

Complete the function that accepts two sequences as inputs and returns `true` if the vectors are orthogonal, and `false` if they are not. The sequences will always be correctly formatted and of the same length, so there is no need to check them first.

## Examples
```
[1, 1, 1], [2, 5, 7]        --> false
[1, 0, 0, 1], [0, 1, 1, 0]  --> true
```

from operator import mul
def is_orthogonal(u, v):
    return not sum(map(mul, u, v))


Solve in Python:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

       This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
       Would this affect the run-time complexity? How and why?

class Solution:
     def search(self, nums, target):
         """
         :type nums: List[int]
         :type target: int
         :rtype: bool
         """
         return target in nums


Solve in Python:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

class Solution:
     def search(self, nums, target):
         """
         :type nums: List[int]
         :type target: int
         :rtype: int
         """
         for i in range(0,len(nums)):
             if nums[i] == target:
                 return i
         return -1


Solve in Python:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

       This is a follow up problem to Find Minimum in Rotated Sorted Array.
       Would allow duplicates affect the run-time complexity? How and why?

class Solution:
     def findMin(self, nums):
         l = 0
         r = len(nums) - 1
         res = nums[r]
         while l < r:
             if nums[l] < nums[r]:
                 return min(nums[l],res)
             res = min(res,nums[r])
             m = int((l+r)/2)
             if nums[l] == nums[r]:
                 temp = nums[r]
                 while nums[l] == temp and l < r:
                     l = l + 1
                 while nums[r] == temp and l < r:
                     r = r - 1
             elif nums[m] >= nums[l]:
                 l = m + 1
             elif nums[m] <= nums[r]:
                 res = min(nums[m],res)
                 r = m - 1
         return min(nums[l],res)
         """
         :type nums: List[int]
         :rtype: int
         """


Solve in Python:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2]
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

class Solution:
     def findMin(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         # m = nums[0]
         # for num in nums:
         #     if num < m:
         #         m = num
         # return m
         if len(nums) == 1:
             return nums[0]

         for i in range(1,len(nums)):
             if nums[i - 1] > nums[i]:
                 return nums[i]

         return nums[0]


Solve in Python:
Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagonally opposite vertices. In other word (i, j, k) in B is the sum of numbers of A having coordinates (a, b, c) such that 0 ≤ a ≤ i, 0 ≤ b ≤ j, 0 ≤ c ≤ k. The problem is that given B, you have to find out A.

-----Input-----
The first line of input will contain the number of test cases ( ≤ 10). That many test cases will follow in subsequent lines. The first line of each test case will contain the numbers X Y Z (0 ≤ X, Y, Z ≤ 100). After that there will be X x Y lines each containing Z numbers of B. The first line contains the numbers (0, 0, 0), (0, 0, 1)..., (0, 0, Z-1). The second line has the numbers (0, 1, 0), (0, 1, 1)..., (0, 1, Z-1) and so on. The (Y+1)th line will have the numbers (1, 0, 0), (1, 0, 1)..., (1, 0, Z-1) and so on.

-----Output-----
For each test case print the numbers of A in exactly the same fashion as the input.

-----Example-----
Input:
2
3 1 1
1
8
22
1 2 3
0 9 13
18 45 51

Output:
1
7
14
0 9 4
18 18 2

# Problem: http://www.codechef.com/JULY09/submit/CUBESUM/
# Author: Susam Pal

def computeA():
 X, Y, Z = [int(x) for x in input().split()]
 B = []
 for x in range(X):
  B.append([])
  for y in range(Y):
   B[-1].append([int(t) for t in input().split()])
   for z in range(Z):
    result = B[x][y][z]
    if x:
     result -= B[x - 1][y][z]
     if y:
      result += B[x - 1][y - 1][z]
      if z:
       result -= B[x - 1][y - 1][z - 1]

    if y:
     result -= B[x][y - 1][z]
     if z:
      result += B[x][y - 1][z - 1]
    if z:
     result -= B[x][y][z - 1]
     if x:
      result += B[x - 1][y][z - 1]
    print(result, end=' ')
   print()

test_cases = int(input())
for i in range(test_cases):
 computeA()


Solve in Python:
Suppose we abstract our file system by a string in the following manner:

The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:

dir
    subdir1
    subdir2
        file.ext

The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.

The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:

dir
    subdir1
        file1.ext
        subsubdir1
    subdir2
        subsubdir2
            file2.ext

The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.

We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).

Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.

Note:

The name of a file contains at least a . and an extension.
The name of a directory or sub-directory will not contain a ..

Time complexity required: O(n) where n is the size of the input string.

Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.

class Solution:
     def lengthLongestPath(self, input):
         """
         :type input: str
         :rtype: int
         """
         res, l=0, 0
         path=[]
         for line in input.splitlines():
             name=line.lstrip('\t')
             n=len(line)-len(name)
             while len(path)>n:
                 l-=path[-1]
                 path.pop()
             l+=len(name)
             path.append(len(name))
             if '.' in name:
                 res=max(res, l+len(path)-1)
         return res


Solve in Python:
Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1
The number at the ith position is divisible by i.
i is divisible by the number at the ith position.

Now given N, how many beautiful arrangements can you construct?

Example 1:

Input: 2
Output: 2
Explanation:
The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.

Note:

N is a positive integer and will not exceed 15.


Solve in Python:
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False

Note:

The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.

class Solution:
     def canPlaceFlowers(self, flowerbed, n):
         """
         :type flowerbed: List[int]
         :type n: int
         :rtype: bool
         """
         cnt = 0
         for i, f in enumerate(flowerbed):
             if f == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerbed)-1 or flowerbed[i+1] == 0):
                 cnt += 1
                 flowerbed[i] = 1
         return cnt >= n


Solve in Python:
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

class Solution:
     def reconstructQueue(self, people):
         """
         :type people: List[List[int]]
         :rtype: List[List[int]]
         """

         if not people:
             return []
         ordered_line = []
         people = sorted(people, key=lambda x: x[1])
         people = sorted(people, key=lambda x: -x[0])
         for person in people:
             ordered_line.insert(person[1], person)

         return ordered_line