I found an interesting problem on https://codeforces.com/problemset/problem/377/B:
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get c_{i} 'passes' in his subjects (regardless of the volume of his work).

Bugs, like students, are not the same: every bug is characterized by complexity a_{j}, and every student has the level of his abilities b_{i}. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: b_{i} ≥ a_{j}, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.

The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.

-----Input-----

The first line contains three space-separated integers: n, m and s (1 ≤ n, m ≤ 10^5, 0 ≤ s ≤ 10^9) — the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students.

The next line contains m space-separated integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — the bugs' complexities.

The next line contains n space-separated integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^9) — the levels of the students' abilities.

The next line contains n space-separated integers c_1, c_2, ..., c_{n} (0 ≤ c_{i} ≤ 10^9) — the numbers of the passes the students want to get for their help.

-----Output-----

If the university can't correct all bugs print "NO".

Otherwise, on the first line...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin
import heapq

n,m,s = [int(x) for x in stdin.readline().split()]

bugs = [int(x) for x in stdin.readline().split()]
bugs = sorted([(bugs[x],x) for x in range(m)])

order = [x[1] for x in bugs]
bugs = [x[0] for x in bugs]

students = [int(x) for x in stdin.readline().split()]
rate = [int(x) for x in stdin.readline().split()]

valid = False
for x in range(n):
  if students[x] >= bugs[-1] and rate[x] <= s:
    valid = True
if not valid:
  print('NO')
else:
  print('YES')
  #print(students)
  for i,x in enumerate(students):
    low = 0
    high = m-1
    while high >= low:
      mid = (high+low)//2
      if bugs[mid] > x:
        high = mid-1
      else:
        low = mid+1
    #print(x,high)
    students[i] = high

  students = sorted([(students[x]+1,rate[x], x+1) for x in range(n)],reverse=True)
  #print(students)
  l1 = 1
  high = m

  lastValid = []
  lastD = 100000

  while l1 <= high:
    mid = (l1+high)//2
    shift = (mid-(m%mid))%mid
    segs = m//mid
    if shift > 0:
      segs += 1
    ind = 0
    q = []

    total = 0

    group = []

    for x in range(segs,0,-1):
      while ind<n:
        if (students[ind][0]+shift)//mid >= x:
          heapq.heappush(q,(students[ind][1],students[ind][2]))
          ind += 1
        else:
          break
      if q:
        r,i = heapq.heappop(q)
        group.append((x,i))
        total += r
      else:
        break
    if len(group) == segs and total <= s:
      #print(mid,total)
      high = mid-1
      lastValid = group
      lastD = mid
    else:
      l1 = mid+1
  complete = [0 for x in range(m)]
  lastValid.sort()
  mid = lastD
  shift = (mid-(m%mid))%mid
  skill = 1
  for bruh,i in lastValid:
    end = skill*mid-shift
    start = max(0,end-mid)
    for x in range(start,end):
      complete[x] = i
    skill += 1
  c2 = [0 for x in range(m)]
  for i,x in enumerate(complete):
    c2[order[i]] = x
  print(' '.join([str(x) for x in c2]))


I found an interesting problem on https://codeforces.com/problemset/problem/378/A:
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.

The first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?

-----Input-----

The single line contains two integers a and b (1 ≤ a, b ≤ 6) — the numbers written on the paper by the first and second player, correspondingly.

-----Output-----

Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly.

-----Examples-----
Input
2 5

Output
3 0 3

Input
2 4

Output
2 1 3

-----Note-----

The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.

You can assume that number a is closer to number x than number b, if |a - x| < |b - x|.

I tried it in Python, but could not do it. Can you solve it?

line = input()

integers = [int(i) for i in line.split()]
a = integers[0]
b = integers[1]

x = 0
y = 0
z = 0

for i in range(1, 7):
    if abs(a - i) < abs(b - i):
        x += 1
    elif abs(a - i) == abs(b - i):
        y += 1
    else:
        z += 1

print(str(x) + ' ' + str(y) + ' ' + str(z))


I found an interesting problem on https://codeforces.com/problemset/problem/378/B:
Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others.

The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of participants in each semifinal.

Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 10^9) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n} are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal.

-----Output-----

Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0".

-----Examples-----
Input
4
9840 9920
9860 9980
9930 10020
10040 10090

Output
1110
1100

Input
4
9900 9850
9940 9930
10000 10020
10060 10110

Output
1100
1100

-----Note-----

Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090.  If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and...

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/379/A:
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.

Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like any other new candle.

Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.

-----Input-----

The single line contains two integers, a and b (1 ≤ a ≤ 1000; 2 ≤ b ≤ 1000).

-----Output-----

Print a single integer — the number of hours Vasily can light up the room for.

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

Output
7

Input
6 3

Output
8

-----Note-----

Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours.

I tried it in Python, but could not do it. Can you solve it?

a, b = list(map(int, input().split()))
ans = a
while a >= b:
    f = a // b
    ans += f
    a = a % b + f
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/379/C:
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.

There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least a_{i} rating units as a present.

The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.

Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 3·10^5) — the number of users on the site. The next line contains integer sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a sequence of integers b_1, b_2, ..., b_{n}. Number b_{i} means that user i gets b_{i} of rating as a present. The printed sequence must meet the problem conditions.

If there are multiple optimal solutions, print any of them.

-----Examples-----
Input
3
5 1 1

Output
5 1 2

Input
1
1000000000

Output
1000000000

I tried it in Python, but could not do it. Can you solve it?

n=int(input())
lst=[*map(int,input().split())]
ind=sorted(range(n),key=lst.__getitem__)
elem=0
for i,x in enumerate(ind):
    elem=max(elem+1,lst[x])
    lst[x]=elem
print(*lst)


I found an interesting problem on https://codeforces.com/problemset/problem/381/A:
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.

Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.

Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.

-----Output-----

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.

-----Examples-----
Input
4
4 1 2 10

Output
12 5

Input
7
1 2 3 4 5 6 7

Output
16 12

-----Note-----

In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
cards = list(map(int, input().split()))
s = True
d = False
ps = 0
pd = 0
while len(cards) > 0:
    if s:
        if cards[0] > cards[-1]:
            ps += cards[0]
            t = 0
        else:
            ps += cards[-1]
            t = -1
        s = False
        d = True
        cards.pop(t)
    elif d:
        if cards[0] > cards[-1]:
            pd += cards[0]
            t = 0
        else:
            pd += cards[-1]
            t = -1
        s = True
        d = False
        cards.pop(t)

print(ps, pd)


I found an interesting problem on https://codeforces.com/problemset/problem/381/B:
Sereja loves integer sequences very much. He especially likes stairs.

Sequence a_1, a_2, ..., a_{|}a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a_1 < a_2 < ... < a_{i} - 1 < a_{i} > a_{i} + 1 > ... > a_{|}a| - 1 > a_{|}a|.

For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.

Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?

-----Input-----

The first line contains integer m (1 ≤ m ≤ 10^5) — the number of Sereja's cards. The second line contains m integers b_{i} (1 ≤ b_{i} ≤ 5000) — the numbers on the Sereja's cards.

-----Output-----

In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.

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

Output
5
5 4 3 2 1

Input
6
1 1 2 2 3 3

Output
5
1 2 3 2 1

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = list(map(int, input().split()))
a.sort()
b=[]
for i in range(n-2):
    if not (a[i] == a[i+1] and a[i] == a[i+2]):
        b.append(a[i])
b.append(a[n-2])
b.append(a[n-1])
if b[-1] == b[-2]:
    b = b[:len(b)-1]
print(len(b))
b1=[]
b2=[]
for i in range(len(b)):
    if i % 2 == 0:
        b2.append(b[i])
    else:
        b1.append(b[i])
for i in b1:
    print(i, end=' ')
b2.reverse()
for i in b2:
    print(i, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/382/A:
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.

The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.

-----Input-----

The first line has a non-empty sequence of characters describing the scales. In this sequence, an uppercase English letter indicates a weight, and the symbol "|" indicates the delimiter (the character occurs in the sequence exactly once). All weights that are recorded in the sequence before the delimiter are initially on the left pan of the scale. All weights that are recorded in the sequence after the delimiter are initially on the right pan of the scale.

The second line contains a non-empty sequence containing uppercase English letters. Each letter indicates a weight which is not used yet.

It is guaranteed that all the English letters in the input data are different. It is guaranteed that the input does not contain any extra characters.

-----Output-----

If you cannot put all the weights on the scales so that the scales were in equilibrium, print string "Impossible". Otherwise, print the description of the resulting scales, copy the format of the input.

If there are multiple answers, print any of them.

-----Examples-----
Input
AC|T
L

Output
AC|TL

Input
|ABC
XYZ

Output
XYZ|ABC

Input
W|T
F

Output
Impossible

Input
ABC|
D

Output
Impossible

I tried it in Python, but could not do it. Can you solve it?

scales  = input().split('|')
weights = list(input())

balance = len(scales[0]) - len(scales[1])

while weights:
    if len(scales[0]) < len(scales[1]):
        scales[0] += weights[0]
        weights.pop(0)
    else:
        scales[1] += weights[0]
        weights.pop(0)
    balance = len(scales[0]) - len(scales[1])

if balance == 0:
    print('|'.join(scales))
else:
    print('Impossible')


I found an interesting problem on https://codeforces.com/problemset/problem/382/B:
Arthur and Alexander are number busters. Today they've got a competition.

Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: c = c - 1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if b ≥ x, perform the assignment b = b - x, if b < x, then perform two consecutive assignments a = a - 1; b = w - (x - b).

You've got numbers a, b, w, x, c. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if c ≤ a.

-----Input-----

The first line contains integers a, b, w, x, c (1 ≤ a ≤ 2·10^9, 1 ≤ w ≤ 1000, 0 ≤ b < w, 0 < x < w, 1 ≤ c ≤ 2·10^9).

-----Output-----

Print a single integer — the minimum time in seconds Alexander needs to get ahead of Arthur. You can prove that the described situation always occurs within the problem's limits.

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

Output
2

Input
4 2 3 1 7

Output
4

Input
1 2 3 2 6

Output
13

Input
1 1 2 1 1

Output
0

I tried it in Python, but could not do it. Can you solve it?

import sys

def solve():
    a, b, w, x, c = map(int, input().split())
    w -= x
    small, large = 0, int(1e20)
    while small < large:
        avg = (small + large) // 2
        if works(avg, a, b, c, w, x): large = avg
        else: small = avg + 1
    return small

def works(val, a, b, c, w, x):
    cres = c - val
    amin = cres
    maxsubtract = a - amin
    if maxsubtract < 0: return False
    bsubtract = val - maxsubtract
    bres = b + maxsubtract * w - x * bsubtract
    return bres >= 0

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/382/C:
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a_1, a_2, ..., a_{n} of length n, that the following condition fulfills: a_2 - a_1 = a_3 - a_2 = a_4 - a_3 = ... = a_{i} + 1 - a_{i} = ... = a_{n} - a_{n} - 1.

For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.

Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).

Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 10^8.

-----Output-----

If Arthur can write infinitely many distinct integers on the card, print on a single line -1.

Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 10^8 or even be negative (see test samples).

-----Examples-----
Input
3
4 1 7

Output
2
-2 10

Input
1
10

Output
-1

Input
4
1 3 5 9

Output
1
7

Input
4
4 3 4 5

Output
0

Input
2
2 4

Output
3
0 3 6

I tried it in Python, but could not do it. Can you solve it?

n=int(input())
li=list(map(int,input().split()))
if n==1:
    print(-1)
elif n==2:
    li.sort()
    d=li[1]-li[0]
    if d==0:
        print(1)
        print(li[0])
    elif d%2==0:
        print(3)
        print(li[0]-d,li[0]+d//2,li[1]+d)
    else:
        print(2)
        print(li[0]-d,li[1]+d)
else:
    flag=0
    li.sort()
    d=li[1]-li[0]
    for i in range(2,n):
        if li[i]-li[i-1]<d:
            d=li[i]-li[i-1]
    for i in range(1,n):
        if (li[i]-li[i-1])!=d:
            if li[i]-li[i-1]==2*d:
                flag+=1
                ind=i
            else:
                flag=-1
                break
    if d==0 and flag==0:
        print(1)
        print(li[0])
    elif flag==-1 or flag>1:
        print(0)
    elif flag==1:
        print(1)
        print(li[ind]-d)
    else:
        print(2)
        print(li[0]-d,li[-1]+d)


I found an interesting problem on https://codeforces.com/problemset/problem/383/B:
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≤ i, j ≤ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1).

Also, there are m cells that are occupied by volcanoes, which Iahub cannot enter.

Iahub is initially at cell (1, 1) and he needs to travel to cell (n, n). Knowing that Iahub needs 1 second to travel from one cell to another, find the minimum time in which he can arrive in cell (n, n).

-----Input-----

The first line contains two integers n (1 ≤ n ≤ 10^9) and m (1 ≤ m ≤ 10^5). Each of the next m lines contains a pair of integers, x and y (1 ≤ x, y ≤ n), representing the coordinates of the volcanoes.

Consider matrix rows are numbered from 1 to n from top to bottom, and matrix columns are numbered from 1 to n from left to right. There is no volcano in cell (1, 1). No two volcanoes occupy the same location.

-----Output-----

Print one integer, the minimum time in which Iahub can arrive at cell (n, n). If no solution exists (there is no path to the final cell), print -1.

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

Output
6

Input
7 8
1 6
2 6
3 5
3 6
4 3
5 1
5 2
5 3

Output
12

Input
2 2
1 2
2 1

Output
-1

-----Note-----

Consider the first sample. A possible road is: (1, 1)  →  (1, 2)  →  (2, 2)  →  (2, 3)  →  (3, 3)  →  (3, 4)  →  (4, 4).

I tried it in Python, but could not do it. Can you solve it?

from collections import defaultdict

def f(u, v):
    s, l = [], len(v)
    i = j = 0
    for i in range(len(u)):
        while v[j][1] <= u[i][0]:
            j += 1
            if j == l: return s
        if u[i][1] <= v[j][0]: continue
        if u[i][0] >= v[j][0]: s.append(u[i])
        else: s.append((v[j][0], u[i][1]))
    return s

n, m = map(int, input().split())
p = defaultdict(list)

for i in range(m):
    x, y = map(int, input().split())
    p[x].append(y)

for x in p:
    if len(p[x]) > 1: p[x].sort()
    t, i = [], 1
    for j in p[x]:
        if i != j: t.append((i, j))
        i = j + 1
    if i != n + 1: t.append((i, n + 1))
    p[x] = t

k, s = 1, [(1, 2)]
for x in sorted(p.keys()):
    if x == k: s = f(p[x], s)
    else: s = f(p[x], [(s[0][0], n + 1)])
    if not s: break
    k = x + 1

if s and k == n + 1 and s[-1][1] != k: s = []
print(2 * (n - 1) if s else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/384/A:
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).

Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 1000).

-----Output-----

On the first line print an integer, the maximum number of Coders that can be placed on the chessboard.

On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'.

If there are multiple correct answers, you can print any.

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

Output
2
C.
.C

I tried it in Python, but could not do it. Can you solve it?

def CreateBoard(n):
    mat = []
    for i in range(n):
        if i % 2 == 0:
            if n % 2 == 0:
                mat.append('C.'*(n//2))
            else:
                mat.append('C.'*(n//2+1))
        else:
            if n % 2 == 0:
                mat.append('.C'*(n//2))
            else:
                mat.append('.C'*(n//2+1))
    return mat

n = int(input())

if n % 2 == 0:
    print(n * n//2)
    for row in CreateBoard(n):
        print(row)
else:
    print((n//2 + 1)**2 + (n//2)**2)
    for row in CreateBoard(n):
        print(row[:-1])


I found an interesting problem on https://codeforces.com/problemset/problem/384/B:
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.

Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position i is strictly greater than the value at position j.

Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the n arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most $\frac{m(m - 1)}{2}$ (at most $\frac{m(m - 1)}{2}$ pairs). Help Iahub, find any suitable array.

-----Input-----

The first line contains three integers n (1 ≤  n ≤ 1000), m (1 ≤ m ≤  100) and k. Integer k is 0 if the arrays must be sorted in ascending order, and 1 if the arrays must be sorted in descending order. Each line i of the next n lines contains m integers separated by a space, representing the i-th array. For each element x of the array i, 1 ≤ x ≤ 10^6 holds.

-----Output-----

On the first line of the output print an integer p, the size of the array (p can be at most $\frac{m(m - 1)}{2}$). Each of the next p lines must contain two distinct integers i and j (1 ≤ i, j ≤ m, i ≠ j), representing the chosen indices.

If there are multiple correct answers, you can print any.

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

Output
3
2 4
2 3
4 5

Input
3 2 1
1 2
2 3
3 4

Output
1
2 1

-----Note-----

Consider the first sample. After the first operation, the arrays become [1, 3, 2, 5, 4] and [1, 2, 3, 4, 5]. After the second operation, the arrays become [1, 2, 3, 5, 4] and [1, 2, 3, 4, 5]. After the third operation they become [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5].

I tried it in Python, but could not do it. Can you solve it?

n,m,k=map(int,input().split())
print(m*(m-1)//2)
for i in range(n):
    a=list(map(int,input().split()))
if k==0:
    for i in range(m):
        for j in range(i+1,m):
            print(i+1,j+1)
else:
    for i in range(m):
        for j in range(i+1,m):
            print(j+1,i+1)


I found an interesting problem on https://codeforces.com/problemset/problem/385/A:
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is x_{i} kilos of raspberry.

Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 ≤ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.

The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.

-----Input-----

The first line contains two space-separated integers, n and c (2 ≤ n ≤ 100, 0 ≤ c ≤ 100), — the number of days and the number of kilos of raspberry that the bear should give for borrowing the barrel.

The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 100), the price of a honey barrel on day i.

-----Output-----

Print a single integer — the answer to the problem.

-----Examples-----
Input
5 1
5 10 7 3 20

Output
3

Input
6 2
100 1 10 40 10 40

Output
97

Input
3 0
1 2 3

Output
0

-----Note-----

In the first sample the bear will lend a honey barrel at day 3 and then sell it for 7. Then the bear will buy a barrel for 3 and return it to the friend. So, the profit is (7 - 3 - 1) = 3.

In the second sample bear will lend a honey barrel at day 1...

I tried it in Python, but could not do it. Can you solve it?

n, c = map(int, input().split())
a = list(map(int, input().split()))
m = 0
for i in range(n - 1):
    if a[i] - a[i + 1] - c > m:
        m = a[i] - a[i + 1] - c
print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/385/B:
The bear has a string s = s_1s_2... s_{|}s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = s_{i}s_{i} + 1... s_{j} contains at least one string "bear" as a substring.

String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that s_{k} = b, s_{k} + 1 = e, s_{k} + 2 = a, s_{k} + 3 = r.

Help the bear cope with the given problem.

-----Input-----

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

-----Output-----

Print a single number — the answer to the problem.

-----Examples-----
Input
bearbtear

Output
6

Input
bearaabearc

Output
20

-----Note-----

In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).

In the second sample, the following pairs (i, j) match: (1,  4), (1,  5), (1,  6), (1,  7), (1,  8), (1,  9), (1,  10), (1,  11), (2,  10), (2,  11), (3,  10), (3,  11), (4,  10), (4,  11), (5,  10), (5,  11), (6,  10), (6,  11), (7,  10), (7,  11).

I tried it in Python, but could not do it. Can you solve it?

s=input().strip()
n=len(s)
x=[]
for i in range(n-3):
    if s[i:i+4]=='bear':
        x.append(i)
i=0
j=0
ans=0
m=len(x)
while i<m:
    ans+=max(0,n-x[i]-3)
    j+=1
    if j>x[i]:
        i+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/385/E:
Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes.

The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place:  Let's suppose that at the current moment the bear is in cell (x, y).  First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k).  Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1).  Then one additional raspberry bush grows in each cell of the field.

You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it.

-----Input-----

The first line of the input contains six space-separated integers: n, sx, sy, dx, dy, t (1 ≤ n ≤ 10^9; 1 ≤ sx, sy ≤ n;  - 100 ≤ dx, dy ≤ 100; 0 ≤ t ≤ 10^18).

-----Output-----

Print two integers — the coordinates of the cell the bear will end up in after t seconds.

-----Examples-----
Input
5 1 2 0 1 2

Output
3 1
Input
1 1 1 -1 -1 2

Output
1 1

-----Note-----

Operation a mod b means taking the remainder after dividing a by b. Note that the result of the operation is always non-negative. For example, ( - 1) mod 3 = 2.

In the first sample before the first move...

I tried it in Python, but could not do it. Can you solve it?

mod, sx, sy, dx, dy, t = list(map(int, input().split()))
class Matrix():
    def __init__(self, n):
        self.n = n
        self.a = [[0] * n for _ in range(n)]

    def __mul__(self, b):
        res = Matrix(self.n)
        for i in range(self.n):
            for j in range(self.n):
                for k in range(self.n):
                    res.a[i][j] += self.a[i][k] * b.a[k][j] % mod
                    res.a[i][j] %= mod
        return res

    def __pow__(self, e):
        res = Matrix(self.n)
        for i in range(self.n):
            res.a[i][i] = 1
        tmp = self
        while e:
            if e & 1:
                res = res * tmp
            e >>= 1
            tmp = tmp * tmp
        return res
M = Matrix(6)
M.a = [[2, 1, 1, 0, 1, 2],
       [1, 2, 0, 1, 1, 2],
       [1, 1, 1, 0, 1, 2],
       [1, 1, 0, 1, 1, 2],
       [0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1]]
sx -= 1
sy -= 1
r = M ** t
f = lambda i: (r.a[i][0] * sx + r.a[i][1] * sy + r.a[i][2] * dx + r.a[i][3] * dy + r.a[i][5]) % mod + 1
print(f(0), f(1))


I found an interesting problem on https://codeforces.com/problemset/problem/386/A:
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).

Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.

-----Input-----

The first line of the input contains n (2 ≤ n ≤ 1000) — number of bidders. The second line contains n distinct integer numbers p_1, p_2, ... p_{n}, separated by single spaces (1 ≤ p_{i} ≤ 10000), where p_{i} stands for the price offered by the i-th bidder.

-----Output-----

The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.

-----Examples-----
Input
2
5 7

Output
2 5

Input
3
10 2 8

Output
1 8

Input
6
3 8 2 9 4 14

Output
6 9

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = list(map(int, input().split()))
p = a.index(max(a))
a.pop(p)
print(p+1, max(a))


I found an interesting problem on https://codeforces.com/problemset/problem/386/B:
Everyone loves a freebie. Especially students.

It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam.

In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time t_{i}, where t_{i} is the number of seconds elapsed since the beginning of the night.

It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.

Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 100), where n — the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers t_{i} (1 ≤ t_{i} ≤ 1000).

The last line contains integer T (1 ≤ T ≤ 1000) — the time interval during which the freebie was near the dormitory.

-----Output-----

Print a single integer — the largest number of people who will pass exam tomorrow because of the freebie visit.

-----Examples-----
Input
6
4 1 7 8 3 8
1

Output
3

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
p = list(map(int,input().split()))
t = int(input())
p.sort()
ans = 0
i = 0
for j in range(n):
    while p[j]-p[i]>t:
        i=i+1
    ans=max(ans,j-i+1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/386/D:
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are three stones positioned on three distinct vertices. All stones are the same. With one move you can move the stone to another free vertex along some diagonal. The color of this diagonal must be the same as the color of the diagonal, connecting another two stones.

Your goal is to move stones in such way that the only vertices occupied by stones are 1, 2 and 3. You must achieve such position using minimal number of moves. Write a program which plays this game in an optimal way.

-----Input-----

In the first line there is one integer n (3 ≤ n ≤ 70) — the number of points. In the second line there are three space-separated integer from 1 to n — numbers of vertices, where stones are initially located.

Each of the following n lines contains n symbols — the matrix denoting the colors of the diagonals. Colors are denoted by lowercase English letters. The symbol j of line i denotes the color of diagonal between points i and j. Matrix is symmetric, so j-th symbol of i-th line is equal to i-th symbol of j-th line. Main diagonal is filled with '*' symbols because there is no diagonal, connecting point to itself.

-----Output-----

If there is no way to put stones on vertices 1, 2 and 3, print -1 on a single line. Otherwise, on the first line print minimal required number of moves and in the next lines print the description of each move, one move per line. To describe a move print two integers. The point from which to remove the stone, and the point to which move the stone. If there are several optimal solutions, print any of them.

-----Examples-----
Input
4
2 3 4
*aba
a*ab
ba*b
abb*

Output
1
4 1

Input
4
2 3 4
*abc
a*ab
ba*b
cbb*

Output
-1

-----Note-----

In the first example we can move stone...

I tried it in Python, but could not do it. Can you solve it?

from collections import deque

__author__ = 'asmn'

n = int(input())
end = tuple(sorted([int(x) - 1 for x in input().split()]))
st = (0, 1, 2)
mat = [input() for i in range(n)]
v = set([st])
path = {}
dist = {st: 0}
queue = deque([st])

while end not in v and len(queue) > 0:
    p = queue.popleft()

    for x in range(-2, 1):
        p1, p2, p3 = p[x], p[x + 1], p[x + 2]
        for i in range(n):
            if i not in (p1, p2, p3) and mat[i][p3] == mat[p1][p2]:
                np = tuple(sorted((p1, p2, i)))
                if np not in v:
                    v.add(np)
                    queue.append(np)
                    path[np] = p
                    dist[np] = dist[p] + 1

def pathinfo(fr, to):
    return str((set(fr) - set(to)).pop() + 1) + ' ' + str((set(to) - set(fr)).pop() + 1)

if end not in dist:
    print(-1)
    return

print(dist[end])
while end in path:
    print(pathinfo(end, path[end]))
    end = path[end]


I found an interesting problem on https://codeforces.com/problemset/problem/387/A:
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t.

Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second test sample).

-----Input-----

The first line contains current time s as a string in the format "hh:mm". The second line contains time t in the format "hh:mm" — the duration of George's sleep. It is guaranteed that the input contains the correct time in the 24-hour format, that is, 00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59.

-----Output-----

In the single line print time p — the time George went to bed in the format similar to the format of the time in the input.

-----Examples-----
Input
05:50
05:44

Output
00:06

Input
00:00
01:00

Output
23:00

Input
00:01
00:00

Output
00:01

-----Note-----

In the first sample George went to bed at "00:06". Note that you should print the time only in the format "00:06". That's why answers "0:06", "00:6" and others will be considered incorrect.

In the second sample, George went to bed yesterday.

In the third sample, George didn't do to bed at all.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/387/B:
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer b_{i}.

To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a_1, at least one with complexity exactly a_2, ..., and at least one with complexity exactly a_{n}. Of course, the round can also have problems with other complexities.

George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.

However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_1 < a_2 < ... < a_{n} ≤ 10^6) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b_1, b_2, ..., b_{m} (1 ≤ b_1 ≤ b_2... ≤ b_{m} ≤ 10^6) — the complexities of the problems prepared by George.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
0

Input
3 5
1 2 3
1 1 1 1 1

Output
2

Input
3 1
2 3 4
1

Output
3

-----Note-----

In the first sample the set of the prepared problems meets the requirements for a good round.

In...

I tried it in Python, but could not do it. Can you solve it?

import re

temp=input()
temp=re.split(' ',temp)
n=eval(temp[0])
m=eval(temp[1])
temp=input()
temp=re.split(' ',temp)
a=[]
for i in range(n):
  a.append(eval(temp[i]))
i=0
temp=input()
temp=re.split(' ',temp)
for j in range(m):
  x=eval(temp[j])
  if i>=n: continue
  if x>=a[i]: i+=1
ans=n-i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/387/C:
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b_1, b_2, ..., b_{|}b| (record |b| denotes the current length of the array). Then one change is a sequence of actions:   Choose two distinct indexes i and j (1 ≤ i, j ≤ |b|; i ≠ j), such that b_{i} ≥ b_{j}.  Get number v = concat(b_{i}, b_{j}), where concat(x, y) is a number obtained by adding number y to the end of the decimal record of number x. For example, concat(500, 10) = 50010, concat(2, 2) = 22.  Add number v to the end of the array. The length of the array will increase by one.  Remove from the array numbers with indexes i and j. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array.

George played for a long time with his array b and received from array b an array consisting of exactly one number p. Now George wants to know: what is the maximum number of elements array b could contain originally? Help him find this number. Note that originally the array could contain only positive integers.

-----Input-----

The first line of the input contains a single integer p (1 ≤ p < 10^100000). It is guaranteed that number p doesn't contain any leading zeroes.

-----Output-----

Print an integer — the maximum number of elements array b could contain originally.

-----Examples-----
Input
9555

Output
4
Input
10000000005

Output
2
Input
800101

Output
3
Input
45

Output
1
Input
1000000000000001223300003342220044555

Output
17
Input
19992000

Output
1
Input
310200

Output
2

-----Note-----

Let's consider the test examples:   Originally array b can be equal to {5, 9, 5, 5}. The sequence of George's changes could have been: {5, 9, 5, 5} → {5, 5, 95} → {95, 55} → {9555}.  Originally array b could be equal to {1000000000, 5}. Please note that the array b cannot contain zeros.  Originally array b could be equal to...

I tried it in Python, but could not do it. Can you solve it?

p = input().strip()

n = len(p)
j = n - 1
ans = 0

while(j >= 0):
    k = j
    while p[k] == '0':
        k -= 1

    ln = j - k + 1

    if ln > k:
        ans += 1
        j = -1

    elif ln == k:
        if (p[0] >= p[k]):
            j = k - 1
        else:
            j = -1
        ans += 1

    else:
        ans += 1
        j = k - 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/388/A:
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most x_{i} boxes on its top (we'll call x_{i} the strength of the box).

Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.[Image]

Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than x_{i} boxes on the top of i-th box. What is the minimal number of piles she needs to construct?

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 100).

-----Output-----

Output a single integer — the minimal possible number of piles.

-----Examples-----
Input
3
0 0 10

Output
2

Input
5
0 1 2 3 4

Output
1

Input
4
0 0 0 0

Output
4

Input
9
0 1 0 2 0 1 1 2 10

Output
3

-----Note-----

In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2.[Image]

In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).[Image]

I tried it in Python, but could not do it. Can you solve it?

import sys
import math

n = int(sys.stdin.readline())
xn = [int(x) for x in (sys.stdin.readline()).split()]

xn.sort()

k = [1]
res = 1
for i in xn[1:]:
    flag = False
    for t in range(res):
        if(i >= k[t]):
            k[t] += 1
            flag = True
            break

    if(flag == False):
        res += 1
        k.append(1)

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/388/D:
Fox Ciel studies number theory.

She thinks a non-empty set S contains non-negative integers is perfect if and only if for any $a, b \in S$ (a can be equal to b), $(a \text{xor} b) \in S$. Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).

Please calculate the number of perfect sets consisting of integers not greater than k. The answer can be very large, so print it modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains an integer k (0 ≤ k ≤ 10^9).

-----Output-----

Print a single integer — the number of required sets modulo 1000000007 (10^9 + 7).

-----Examples-----
Input
1

Output
2

Input
2

Output
3

Input
3

Output
5

Input
4

Output
6

-----Note-----

In example 1, there are 2 such sets: {0} and {0, 1}. Note that {1} is not a perfect set since 1 xor 1 = 0 and {1} doesn't contain zero.

In example 4, there are 6 such sets: {0}, {0, 1}, {0, 2}, {0, 3}, {0, 4} and {0, 1, 2, 3}.

I tried it in Python, but could not do it. Can you solve it?

from math import factorial
MOD = 10**9+7

k = int(input())
bink = list(map(int, bin(k)[2:]))
N = len(bink)

# dp[i][j][k] = first i bits, j bases,
#   k = 1 if maxor matches k, 0 else
dp = [[[0,0] for j in range(i+2)] for i in range(N+1)]
dp[0][0][1] = 1
for i in range(1, N+1):
    for j in range(i+1):
        # k = 0 -> 0
        dp[i][j][0]+= 2**j * dp[i-1][j][0] # distribute
        if j: dp[i][j][0]+= dp[i-1][j-1][0] # new base
        # k = 1 -> 0
        odd = 2**(j-1) if j else 0
        even = 2**j - odd
        if bink[i-1] == 1:
            dp[i][j][0]+= even * dp[i-1][j][1] # distribute even
        # k = 1 -> 1
        if bink[i-1] == 0:
            dp[i][j][1]+= even * dp[i-1][j][1] # distribute even
        else:
            dp[i][j][1]+= odd * dp[i-1][j][1] # distribute odd
            if j: dp[i][j][1]+= dp[i-1][j-1][1] # new base
ans = sum(map(sum, dp[-1]))
print(ans % MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/389/A:
Fox Ciel is playing a game with numbers now.

Ciel has n positive integers: x_1, x_2, ..., x_{n}. She can do the following operation as many times as needed: select two different indexes i and j such that x_{i} > x_{j} hold, and then apply assignment x_{i} = x_{i} - x_{j}. The goal is to make the sum of all numbers as small as possible.

Please help Ciel to find this minimal sum.

-----Input-----

The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 100).

-----Output-----

Output a single integer — the required minimal sum.

-----Examples-----
Input
2
1 2

Output
2

Input
3
2 4 6

Output
6

Input
2
12 18

Output
12

Input
5
45 12 27 30 18

Output
15

-----Note-----

In the first example the optimal way is to do the assignment: x_2 = x_2 - x_1.

In the second example the optimal sequence of operations is: x_3 = x_3 - x_2, x_2 = x_2 - x_1.

I tried it in Python, but could not do it. Can you solve it?

def gcd(a, b):
    c = a % b
    return gcd(b, c) if c else b
n, t = int(input()), list(map(int, input().split()))
j = t[0]
for i in t[1: ]: j = gcd(i, j)
print(n * j)


I found an interesting problem on https://codeforces.com/problemset/problem/389/B:
Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.

A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.[Image]

Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.

Please, tell Ciel if she can draw the crosses in the described way.

-----Input-----

The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board.

Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.

-----Output-----

Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".

-----Examples-----
Input
5
.#...
####.
.####
...#.
.....

Output
YES

Input
4
####
####
####
####

Output
NO

Input
6
.#....
####..
.####.
.#.##.
######
.#..#.

Output
YES

Input
6
.#..#.
######
.####.
.####.
######
.#..#.

Output
NO

Input
3
...
...
...

Output
YES

-----Note-----

In example 1, you can draw two crosses. The picture below shows what they look like.[Image]

In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/390/A:
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.

The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off.

Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers x_{i}, y_{i} — the coordinates of the i-th alarm clock (0 ≤ x_{i}, y_{i} ≤ 100).

Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.

-----Output-----

In a single line print a single integer — the minimum number of segments Inna will have to draw if she acts optimally.

-----Examples-----
Input
4
0 0
0 1
0 2
1 0

Output
2

Input
4
0 0
0 1
1 0
1 1

Output
2

Input
4
1 1
1 2
2 3
3 3

Output
3

-----Note-----

In the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.

In the third sample it...

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
x = [0] * 101
y = [0] * 101
for _ in range(n):
  i, j = map(int, input().split())
  x[i] = 1
  y[j] = 1
print(min(sum(x), sum(y)))


I found an interesting problem on https://codeforces.com/problemset/problem/390/B:
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.

A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 ≤ v ≤ a_{i}; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal b_{i}. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes x_{i} and y_{i} (x_{i} + y_{i} = b_{i}) correspondingly, Sereja's joy rises by x_{i}·y_{i}.

Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the number of notes in the song. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6). The third line contains n integers b_{i} (1 ≤ b_{i} ≤ 10^6).

-----Output-----

In a single line print an integer — the maximum possible joy Sereja feels after he listens to a song.

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

Output
4

Input
1
2
5

Output
-1

-----Note-----

In the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1·1 + 1·1 + 1·2 = 4.

In the second sample, there is no such pair (x, y), that 1 ≤ x, y ≤ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -1.

I tried it in Python, but could not do it. Can you solve it?

import math
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=int(0)
for i in range(n):
    if b[i]== 1:
        c-=1
    elif a[i]*2 < b[i]:
        c-=1
    else:
        if b[i]%2 == 0:
            c+=int((b[i]/2)**2)
        else:
            c+=int((int(math.ceil(b[i]/2)))*(int(math.floor(b[i]/2))))
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/390/D:
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".

Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.

Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.

Help Inna to minimize the penalty in the game.

-----Input-----

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).

-----Output-----

In the first line print an integer — Inna's minimum penalty in the game.

In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.

Please follow the output format strictly! If your program passes the first pretest, then the output format is...

I tried it in Python, but could not do it. Can you solve it?

string = input()
l = string.split(" ")
n, m, k = int(l[0]),int(l[1]),int(l[2])
l = [{(1,1),}]
count = 1
In = 0
while count < k:
	s = set()
	for i in l[In]:
		x = i[0]+1
		y = i[1]
		if x<=n and y<=m:
			t = [0,0]
			t[0],t[1] = x, y
			s.add(tuple(t))
		x = i[0]
		y = i[1]+1
		if x<=n and y<=m:
			t = [0,0]
			t[0],t[1] = x, y
			s.add(tuple(t))
	l.append(s)
	In+=1
	count+=len(l[In])
l2 = []
Count = 0
flag = 0
for i in l:
	for h in i:
		if Count==k:
			flag = 1
			break
		l3 = [h]
		x,y = h[0],h[1]
		while x!=1 or y!=1:
			if x>y:
				x-=1
				l3.append((x,y))
			else:
				y-=1
				l3.append((x,y))
		l2.append(l3)
		Count+=1
	if flag==1:
		break

cost = 0
string = ""
for i in range(k):
	length = len(l2[k-i-1])
	cost+=length
	for j in range(length):
		t = l2[k-i-1][length - j - 1]
		x,y = t[0],t[1]
		string += "("+str(x)+","+str(y)+") "
	string += "\n"

print(cost)
print(string)


I found an interesting problem on https://codeforces.com/problemset/problem/391/A:
You will receive 3 points for solving this problem.

Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'.

Manao has determined that if the stretch of DNA contains a maximal sequence of consecutive identical nucleotides that is of even length, then the protein will be nonfunctional. For example, consider a protein described by DNA string "GTTAAAG". It contains four maximal sequences of consecutive identical nucleotides: "G", "TT", "AAA", and "G". The protein is nonfunctional because sequence "TT" has even length.

Manao is trying to obtain a functional protein from the protein he currently has. Manao can insert additional nucleotides into the DNA stretch. Each additional nucleotide is a character from the set {'A', 'T', 'G', 'C'}. Manao wants to determine the minimum number of insertions necessary to make the DNA encode a functional protein.

-----Input-----

The input consists of a single line, containing a string s of length n (1 ≤ n ≤ 100). Each character of s will be from the set {'A', 'T', 'G', 'C'}.

This problem doesn't have subproblems. You will get 3 points for the correct submission.

-----Output-----

The program should print on one line a single integer representing the minimum number of 'A', 'T', 'G', 'C' characters that are required to be inserted into the input string in order to make all runs of identical characters have odd length.

-----Examples-----
Input
GTTAAAG

Output
1

Input
AACCAACCAAAAC

Output
5

-----Note-----

In the first example, it is sufficient to insert a single nucleotide of any type between the two 'T's in the sequence to restore the functionality of the protein.

I tried it in Python, but could not do it. Can you solve it?

import sys

sys_in = input()

def counter(dna):
	count = 1
	even_count = 0
	previous = dna[0]
	dna = dna[1:]
	while(dna != ""):
		if dna[0] == previous:
			count += 1
		else:
			previous  = dna[0]
			if count % 2 == 0:
				even_count += 1
			count = 1
		dna = dna[1:]
	if count%2 == 0 and count != 0:
		even_count+=1
	return even_count

print(str(counter(sys_in))+"\n")


I found an interesting problem on https://codeforces.com/problemset/problem/391/B:
You will receive 5 points for solving this problem.

Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity.

We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings:

"ABCDEF|GHIJK" |  "A|BCDEFGHIJK" |  "AB|RACA|DAB|RA" |  "X|XXXXX|X|X|XXXXXX"

               |                 |                   |       XXXXXX

    KJIHG      |   KJIHGFEDCB    |      AR           |       X

   ABCDEF      |            A    |     DAB           |       X

               |                 |     ACAR          |       XXXXX

               |                 |       AB          |           X

One last example for "ABCD|EFGH|IJ|K":

 K

IJ

HGFE

ABCD

Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both.

-----Input-----

The input will consist of one line containing a single string of n characters with 1 ≤ n ≤ 1000 and no spaces. All...

I tried it in Python, but could not do it. Can you solve it?

t = {}
for i, c in enumerate(input()):
    if c not in t: t[c] = (i, 1)
    elif (t[c][0] - i) & 1: t[c] = (i, t[c][1] + 1)
print(max(b for a, b in list(t.values())))


I found an interesting problem on https://codeforces.com/problemset/problem/391/C1:
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.

Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had p_{i} points.

Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort e_{i} he needs to invest to win against the i-th contestant. Losing a fight costs no effort.

After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.

Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.

-----Input-----

The first line contains a pair of integers n and k (1 ≤ k ≤ n + 1). The i-th of the following n lines contains two integers separated by a single space — p_{i} and e_{i} (0 ≤ p_{i}, e_{i} ≤ 200000).

The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.

  In subproblem C1 (4 points), the constraint 1 ≤ n ≤ 15 will hold.  In subproblem C2 (4 points), the constraint 1 ≤ n ≤ 100 will hold.  In subproblem C3 (8 points), the constraint 1...

I tried it in Python, but could not do it. Can you solve it?

m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0

def add(b, k):
    k = t[k]
    while k:
        e = es[k]
        if b[-1] > e: b[-1] = e
        b[e] += 1
        k = ns[k]

def delete(b):
   for i in range(b[m - 1], m + 1):
       if b[i]:
           b[i] -= 1
           b[-1] = i
           return i

def calc(k):
    nonlocal b
    q = 0
    b = [0] * m
    b[-1] = m
    take = rank - dn
    if take < 0: take = 0
    add(b, k)
    add(b, k - 1)
    for i in range(1, take + 1): q += delete(b)
    for i in range(k - 1): add(b, i)
    for i in range(k + 1, P + 1): add(b, i)
    for i in range(1, k - take + 1): q += delete(b)
    return q

n, k = list(map(int, input().split()))
rank = n - k + 1

if rank == 0:
    print('0')
    return

for i in range(1, n + 1):
    p, e = list(map(int, input().split()))
    if p > P: P = p
    c[p] += 1
    es[i], ns[i] = e, t[p]
    t[p] = i

dn = 0
for i in range(1, n + 1):
    if i > 1: dn += c[i - 2]
    if c[i] + c[i - 1] + dn >= rank and rank <= i + dn:
        u = calc(i)
        if i < n:
            dn += c[i - 1]
            v = calc(i + 1)
            if u > v: u = v
        if i < n - 1:
            dn += c[i]
            v = calc(i + 2)
            if u > v: u = v
        print(u)
        return

print('-1')


I found an interesting problem on https://codeforces.com/problemset/problem/392/A:
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:  the Euclidean distance between A and B is one unit and neither A nor B is blocked;  or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.

Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?

-----Input-----

The first line contains an integer n (0 ≤ n ≤ 4·10^7).

-----Output-----

Print a single integer — the minimum number of points that should be blocked.

-----Examples-----
Input
1

Output
4

Input
2

Output
8

Input
3

Output
16

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/392/B:
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:   Only one disk can be moved at a time.  Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.  No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2^{n} - 1, where n is the number of disks. (c) Wikipedia.

SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all n disks are on the first rod. Moving a disk from rod i to rod j (1 ≤ i, j ≤ 3) costs t_{ij} units of money. The goal of the puzzle is to move all the disks to the third rod.

In the problem you are given matrix t and an integer n. You need to count the minimal cost of solving SmallY's puzzle, consisting of n disks.

-----Input-----

Each of the first three lines contains three integers — matrix t. The j-th integer in the i-th line is t_{ij} (1 ≤ t_{ij} ≤ 10000; i ≠ j). The following line contains a single integer n (1 ≤ n ≤ 40) — the number of disks.

It is guaranteed that for all i (1 ≤ i ≤ 3), t_{ii} = 0.

-----Output-----

Print a single integer — the minimum cost of solving SmallY's puzzle.

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

Output
7

Input
0 2 2
1 0 100
1 2 0
3

Output
19

Input
0 2 1
1 0 100
1 2 0
5

Output
87

I tried it in Python, but could not do it. Can you solve it?

#	!/bin/env python3
#	coding: UTF-8

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology and Management,Gwalior

#	Question Link
#	https://codeforces.com/problemset/problem/392/B
#

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return list(map(int, sys.stdin.readline().split()))

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def main():
    dp = [[[0 for _ in range(3)] for _ in range(3)] for _ in range(43)]
    matrix = [[0 for _ in range(3)] for _ in range(3)]
    for i in range(3):
        matrix[i] = get_array()
    n = int(input())
    for i in range(1, n+1):
        for frm in range(3):
            for to in range(3):
                other = 3-frm-to
                if frm == to:
                    continue
                dp[i][frm][to] = dp[i-1][frm][other]+matrix[frm][to]+dp[i-1][other][to]
                c = dp[i-1][frm][to]+matrix[frm][other] + \
                    dp[i-1][to][frm]+matrix[other][to]+dp[i-1][frm][to]
                dp[i][frm][to] = min(c, dp[i][frm][to])
    print(dp[n][0][2])

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/393/A:
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.

For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.

Help her to find the maximum number of "nineteen"s that she can get in her string.

-----Input-----

The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.

-----Output-----

Print a single integer — the maximum number of "nineteen"s that she can get in her string.

-----Examples-----
Input
nniinneetteeeenn

Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii

Output
2
Input
nineteenineteen

Output
2

I tried it in Python, but could not do it. Can you solve it?

def main(s):
    from collections import Counter
    count = Counter(s)
    n = {'n': 2, 'i': 1, 'e': 3, 't': 1}
    f = True
    x = ""
    for i in range(len(s)):
        for c in n:
            if count[c] < n[c]:
                f = False
                break
        if not f:
            break
        for c in n:
            count[c] -= n[c]
        x += "ninetee"
    if count['n'] > 0:
        x += "n"
    r = 0
    for i in range(0, len(x) + 2 , 7):
        if x[i:i+8] == 'nineteen':
            r += 1
    return r

print(main(list(input())))


I found an interesting problem on https://codeforces.com/problemset/problem/393/B:
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:   A_{ij} = A_{ji}, for all i, j (1 ≤ i, j ≤ n);  B_{ij} =  - B_{ji}, for all i, j (1 ≤ i, j ≤ n);  W_{ij} = A_{ij} + B_{ij}, for all i, j (1 ≤ i, j ≤ n).

Can you solve the problem?

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is W_{ij} (0 ≤ |W_{ij}| < 1717).

-----Output-----

The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them.

The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 4}.

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

Output
1.00000000 3.50000000
3.50000000 2.00000000
0.00000000 0.50000000
-0.50000000 0.00000000

Input
3
1 2 3
4 5 6
7 8 9

Output
1.00000000 3.00000000 5.00000000
3.00000000 5.00000000 7.00000000
5.00000000 7.00000000 9.00000000
0.00000000 -1.00000000 -2.00000000
1.00000000 0.00000000 -1.00000000
2.00000000 1.00000000 0.00000000

I tried it in Python, but could not do it. Can you solve it?

import sys
n = int(sys.stdin.readline())
A = [[0]*n for i in range(n)]
for i in range(n):
    I = sys.stdin.readline().split()
    for j in range(n):
        A[i][j] = int(I[j])
B = [[0]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        B[i][j] = (A[i][j]+A[j][i])/2
        print(B[i][j], end=" ")
    print()
for i in range(n):
    for j in range(n):
        print(A[i][j]-B[i][j], end=" ")
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/394/A:
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:

An expression of counting sticks is an expression of type:[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≤ A, B, C).

Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C.

We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.

We really aren't fabulous at arithmetics. Can you help us?

-----Input-----

The single line contains the initial expression. It is guaranteed that the expression looks like A + B = C, where 1 ≤ A, B, C ≤ 100.

-----Output-----

If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters.

If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test...

I tried it in Python, but could not do it. Can you solve it?

a,b=input().split("=")
if abs(len(a)-1-len(b)) not in [0,2]:
  print("Impossible")
elif len(a)-1==len(b):
  print(a+'='+b)
elif len(a)-1<len(b):
  print('|'+a+"="+b[:-1])
elif a.find('+')>1:
  print(a[1:]+'='+b+'|')
else:
  print(a[:-1]+'='+b+'|')


I found an interesting problem on https://codeforces.com/problemset/problem/394/B:
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.

The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.

The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!

-----Input-----

The single line contains integers p, x (1 ≤ p ≤ 10^6, 1 ≤ x ≤ 9).

-----Output-----

If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.

-----Examples-----
Input
6 5

Output
142857
Input
1 2

Output
Impossible

Input
6 4

Output
102564

-----Note-----

Sample 1: 142857·5 = 714285.

Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".

I tried it in Python, but could not do it. Can you solve it?

p,k = input().split()

p = int (p)
k = int (k)

y = 10*k -1
x = ((10 ** (p-1)) - k) % y

b = True

for i in range(k,10):
	if( (x*i % y) == 0):
		#z = (x*i) // y
		#print(z*10 + i)

		z = i*10

		while( (z-i)%y ):
			z *= 10

		part = str ((z-i)//y)
		print(part * (p//len(part)))
		b= False
		break

if(b):
	print("Impossible")


I found an interesting problem on https://codeforces.com/problemset/problem/394/D:
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.

To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum.

Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression.

-----Input-----

The single line contains integer n (2 ≤ n ≤ 10^3) — the number of students. The second line contains n space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 10^4.

-----Output-----

In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative.

If there are multiple possible answers, you can print any of them.

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

Output
2
-3 1

Input
5
2 -3 -1 -4 3

Output
1
-4 2

-----Note-----

Lets look at the first sample. We can proceed in the following manner:

  don't feed the 1-st student, his height will stay equal to -3;  give two buns of the first type to the 2-nd student, his height become equal to -2;  give two buns of the first type...

I tried it in Python, but could not do it. Can you solve it?

q = 10001
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(40000 // (n - 1) + 1):
    b = [a[j] - j * i for j in range(n)]
    u, v = max(b), min(b)
    p = (u - v + 1) // 2
    if p < q: q, s, d = p, v + p, i
print(q)
print(s, d)


I found an interesting problem on https://codeforces.com/problemset/problem/396/A:
You are given an integer m as a product of integers a_1, a_2, ... a_{n} $(m = \prod_{i = 1}^{n} a_{i})$. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.

Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains positive integer n (1 ≤ n ≤ 500). The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

In a single line print a single number k — the number of distinct decompositions of number m into n ordered multipliers modulo 1000000007 (10^9 + 7).

-----Examples-----
Input
1
15

Output
1

Input
3
1 1 2

Output
3

Input
2
5 7

Output
4

-----Note-----

In the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1.

In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1].

A decomposition of positive integer m into n ordered multipliers is a cortege of positive integers b = {b_1, b_2, ... b_{n}} such that $m = \prod_{i = 1}^{n} b_{i}$. Two decompositions b and c are considered different, if there exists index i such that b_{i} ≠ c_{i}.

I tried it in Python, but could not do it. Can you solve it?

from math import sqrt, factorial as f
from collections import Counter
from operator import mul
from functools import reduce

def comb(n, m):
    o = n - m
    if m and o:
        if m < o:
            m, o = o, m
        return reduce(mul, list(range(m + 1, n)), n) // f(o)
    return 1

def main():
    n = int(input())
    aa = list(map(int, input().split()))
    if n == 1:
        print(1)
        return
    lim = int(sqrt(max(aa)) // 6) + 12
    sieve = [False, True, True] * lim
    lim = lim * 3 - 1
    for i, s in enumerate(sieve):
        if s:
            p, pp = i * 2 + 3, (i + 3) * i * 2 + 3
            le = (lim - pp) // p + 1
            if le > 0:
                sieve[pp::p] = [False] * le
            else:
                break
    sieve[0] = sieve[3] = True
    primes = [i * 2 + 3 for i, f in enumerate(sieve) if f]
    for i, p in enumerate((2, 3, 5, 7)):
        primes[i] = p
    del sieve
    c = Counter()
    for x in aa:
        for p in primes:
            cnt = 0
            while not x % p:
                x //= p
                cnt += 1
            if cnt:
                c[p] += cnt
                if x == 1:
                    break
        if x > 1:
            c[x] += 1
    x, inf = 1, 1000000007
    for p, cnt in list(c.items()):
        x = x * comb(cnt + n - 1, n - 1) % inf
    print(x)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/397/A:
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.

The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (l_{i}, r_{i}) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!

Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.

-----Input-----

The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers l_{i} and r_{i} (0 ≤ l_{i} < r_{i} ≤ 100) — the endpoints of the corresponding segment for the i-th student.

-----Output-----

On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.

-----Examples-----
Input
3
0 5
2 8
1 6

Output
1

Input
3
0 10
1 5
7 15

Output
3

-----Note-----

Note that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.

In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.

In the second test sample Alexey may dry his clothes on segments...

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a1 = list()
for i in range(0,101):
	a1.insert(i,0)
#	print(a1[i])
for i in range(0,n):
	a,b = list(map(int,input().split()))
	#print(i)
	if i!=0:
		for j in range(a, b):
			#print(j)
			a1[j] = 1
			#print(a1[j])
	else:
		l = a
		r = b
ans = 0
for i in range(l, r):
	#print(i)
	if a1[i]==0:
		ans = ans+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/397/B:
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.

The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — n_{i} berubleys. He cannot pay more than n_{i}, because then the difference between the paid amount and n_{i} can be regarded as a bribe!

Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than r_{i}. The rector also does not carry coins of denomination less than l_{i} in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where l_{i} ≤ x ≤ r_{i} (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.

Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.

In other words, you are given t requests, each of them contains numbers n_{i}, l_{i}, r_{i}. For each query you need to answer, whether it is...

I tried it in Python, but could not do it. Can you solve it?

def possible(numbers):
        if int(numbers[0])//int(numbers[1])!=0 and int(numbers[0])%int(numbers[1])//(int(numbers[0])//int(numbers[1]))<=int(numbers[2])-int(numbers[1]) and (int(numbers[0])%int(numbers[1])%(int(numbers[0])//int(numbers[1])) == 0 or int(numbers[0])%int(numbers[1])%int(numbers[0])//int(numbers[1])+int(numbers[0])%int(numbers[1])%(int(numbers[0])//int(numbers[1]))<=(int(numbers[2])-int(numbers[1]))*(int(numbers[0])//int(numbers[1])-int(numbers[0])//int(numbers[2]))):
            return 'Yes'
        return 'No'
for i in range(0,int(input())):
    numbers=input().split(' ')
    if i == -1 and int(numbers[0])!=2 and int(numbers[0])!=912247143:
        print(numbers)
    print(possible(numbers))


I found an interesting problem on https://codeforces.com/problemset/problem/398/A:
User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below.  At first, the score is 0.  For each block of contiguous "o"s with length x the score increases by x^2.  For each block of contiguous "x"s with length y the score decreases by y^2.

For example, if a = 6, b = 3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 2^2 - 1^2 + 3^2 - 2^2 + 1^2 = 9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o".

User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.

-----Input-----

The first line contains two space-separated integers a and b (0 ≤ a, b ≤ 10^5; a + b ≥ 1) — the number of "o" cards and the number of "x" cards.

-----Output-----

In the first line print a single integer v — the maximum score that ainta can obtain.

In the second line print a + b characters describing the deck. If the k-th card of the deck contains "o", the k-th character must be "o". If the k-th card of the deck contains "x", the k-th character must be "x". The number of "o" characters must be equal to a, and the number of "x " characters must be equal to b. If there are many ways to maximize v, print any.

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

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

Output
-1
xoxox

Input
4 0

Output
16
oooo
Input
0 4

Output
-16
xxxx

I tried it in Python, but could not do it. Can you solve it?

a,b=[int(i) for i in input().split()]
if(a==0):
    print(-b**2)
    print('x'*b)
elif(b==0):
    print(a**2)
    print('o'*a)
elif(b==1):
    print(a**2-1)
    print('x'+'o'*a)
else:
    ans=-float('inf')
    gr_no=None
    for i in range(2,min(a+2,b+1)):
        v1=(a+2-i)**2 + i-2
        quo=b//i
        rem=b%i
        v2=rem*((quo+1)**2) + (i-rem)*((quo**2))
        if(v1-v2>ans):
            gr_no=i
            ans=v1-v2
    quo=b//gr_no
    rem=b%gr_no
    if(rem>0):
        s='x'*(quo+1)+'o'*(a+2-gr_no)
        rem-=1
    else:
        s='x'*(quo)+'o'*(a+2-gr_no)
    gr_no-=1
    s1='x'*(quo+1)+'o'
    s2='x'*quo + 'o'
    for i in range(rem):
        s+=s1
    for i in range(gr_no-rem-1):
        s+=s2
    s+='x'*(quo)
    print(ans)
    print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/399/A:
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are n pages numbered by integers from 1 to n. Assume that somebody is on the p-th page now. The navigation will look like this: << p - k p - k + 1 ... p - 1 (p) p + 1 ... p + k - 1 p + k >>

When someone clicks the button "<<" he is redirected to page 1, and when someone clicks the button ">>" he is redirected to page n. Of course if someone clicks on a number, he is redirected to the corresponding page.

There are some conditions in the navigation:  If page 1 is in the navigation, the button "<<" must not be printed.  If page n is in the navigation, the button ">>" must not be printed.  If the page number is smaller than 1 or greater than n, it must not be printed.

You can see some examples of the navigations. Make a program that prints the navigation.

-----Input-----

The first and the only line contains three integers n, p, k (3 ≤ n ≤ 100; 1 ≤ p ≤ n; 1 ≤ k ≤ n)

-----Output-----

Print the proper navigation. Follow the format of the output from the test samples.

-----Examples-----
Input
17 5 2

Output
<< 3 4 (5) 6 7 >>
Input
6 5 2

Output
<< 3 4 (5) 6
Input
6 1 2

Output
(1) 2 3 >>
Input
6 2 2

Output
1 (2) 3 4 >>
Input
9 6 3

Output
<< 3 4 5 (6) 7 8 9
Input
10 6 3

Output
<< 3 4 5 (6) 7 8 9 >>
Input
8 5 4

Output
1 2 3 4 (5) 6 7 8

I tried it in Python, but could not do it. Can you solve it?

# @Author: Justin Hershberger
# @Date:   23-03-2017
# @Filename: 399A.py
# @Last modified by:   Justin Hershberger
# @Last modified time: 23-03-2017

#Justin Hershberger
#Py3.5

import fileinput

def test():
	pass
def __starting_point():
	n,p,k = list(map(int, input().split()))

	output = ""

	if p - k > 1:
		output = "<< "

	for i in range(p-k,p+k+1):
		if i == p:
			output += "(" + str(i) + ") "
		elif i > n:
			break
		elif i > 0:
			output += str(i) + " "

	if p + k < n:
		output += ">>"

	print(output)

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/399/B:
User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.

  While the top ball inside the stack is red, pop the ball from the top of the stack.  Then replace the blue ball on the top with a red ball.  And finally push some blue balls to the stack until the stack has total of n balls inside.

If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 50) — the number of balls inside the stack.

The second line contains a string s (|s| = n) describing the initial state of the stack. The i-th character of the string s denotes the color of the i-th ball (we'll number the balls from top to bottom of the stack). If the character is "R", the color is red. If the character is "B", the color is blue.

-----Output-----

Print the maximum number of operations ainta can repeatedly apply.

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

-----Examples-----
Input
3
RBR

Output
2

Input
4
RBBR

Output
6

Input
5
RBBRR

Output
6

-----Note-----

The first example is depicted below.

The explanation how user ainta applies the first operation. He pops out one red ball, changes the color of the ball in the middle from blue to red, and pushes one blue ball.

 [Image]

The explanation how user ainta applies the second operation. He will not pop out red balls, he simply changes the color of the ball on the top from blue to red.

 [Image]

From now on, ainta can't apply any operation because there are no blue balls inside the stack. ainta applied two operations, so the answer is 2.

The second example is depicted below. The blue arrow denotes a single operation.

 [Image]

I tried it in Python, but could not do it. Can you solve it?

n=int(input())
B=input()
ans=0
for i in range(n-1,-1,-1):
    ans=ans*2+int(B[i]=='B')
print(ans)