from math import factorial
from collections import Counter

def prime(n):
    a = [0] * (n + 1)
    a[0] = 1
    a[1] = 1
    i = 2
    while n // i >= i:
        if a[i] != 0:
            i += 1
            continue
        j = 2 * i
        while j <= n:
            a[j] = 1
            j += i
        i += 1
    return [i for i, ai in enumerate(a) if ai == 0]

n = int(input())
f = factorial(n)
primes = prime(n)
counter = Counter()

while f > 1:
    for p in primes:
        if f % p == 0:
            counter[p] += 1
            f = f // p

ans = 1
for val in counter.values():
    ans *= (val + 1)

print(ans % (10**9 + 7))

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

The input is given from Standard Input in the following format:

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


n,a,b = map(int,input().split())
x = list(map(int,input().split()))
ans = 0
for i in range(n-1):
    if (x[i+1]-x[i]) * a <= b:
        ans += (x[i+1]-x[i]) * a
    else:
        ans += b
print(ans)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

The input is given from Standard Input in the following format:

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

The input is given from Standard Input in the following format:

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print 0.

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


A, op, B = input().split()
if op == '-':
  print(int(A) - int(B))
else:
  print(int(A) + (B))

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys

def read_data():
    lines = [line.rstrip() for line in sys.stdin]
    ns = [int(n) for n in lines[1].split()]
    ms = []
    for line in lines[3:]:
        num, sec = line.split()
        ms.append((int(num)-1, int(sec)))
    return ns, ms

def main():
    ns, ms = read_data()
    for (drink_num, drink_sec) in ms:
        result = sum(ns) - ns[drink_num] + drink_sec
        print result

if __name__ == "__main__":
    main()


N = int(input())
A = list(map(int, input().rstrip().split()))
A.sort()
ANS = 2**(N//2)

if N%2 == 0:
    if A[0] and A[1] != 1:
        print(0)
        exit()
    elif N == 2:
        if A[0] != A[1]:
            print(0)
            exit()
    else:
        for i in range(2,N,2):
            if A[i] != A[i+1] or A[i] - A[i-2] != 2:
                print(0)
                exit()
else:
    if A[0] != 0:
        print(0)
        exit()
    elif N == 3:
        if A[1] != A[2]:
            print(0)
            exit()
    else:
        for i in range(3,N,2):
            if A[i] != A[i+1] or A[i] - A[i-2] != 2:
                print(0)
                exit()

print(ANS%(10**9+7))

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


h, w = map(int, input().split())

for i in range(h):
    c = input()
    for k in range(2):
        print(c)


# coding: utf-8

a, b, x = map(int, input().split(" "))

n = b - a - 1

if a % x == 0 or b % x == 0:
    print(n // x + 1)
else:
    print(n // x)

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


a,b,x = map(int, input().split())

if a == 0:
    print(b//x+1)
else:
    print(b//x-(a-1)//x)


a,b,c = input().split()
if a + b == c or a + c == b or b + c == a:
    print("Yes")
else:
    print("No")

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

The input is given from Standard Input in the following format:

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


N,_=map(int,input().split())
A=list(map(int,input().split()))
if N<=2: print(1)
else:
  ans=1
  mm=A[0]
  mx=A[1]-A[0]
  for i in range(2,N):
    mm=min(mm,A[i-1])
    xx=A[i]-mm
    if mx==xx:
      ans+=1
    elif mx<xx:
      ans=1
      mx=xx
      mm=A[i]
  print(ans)

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

10 100
7 10 4 5 9 3 6 8 2 1

Sample Output 3

2


from collections import deque

N,x = list(map(int,input().split()))

if x==2*N-1 or x==1:
    print("No")
else:
    Q=deque()
    if x<=N:
        Q.append(x)
        Q.append(x-1)
        for i in range(2*N-1,0,-1):
            if i!=x and i!=x-1:
                if i%2==0:
                    Q.append(i)
                else:
                    Q.appendleft(i)
    else:
        Q.append(x)
        Q.append(x+1)
        for i in range(1,2*N):
            if i!=x and i!=x-1:
                if i%2==0:
                    Q.append(i)
                else:
                    Q.appendleft(i)

    print("Yes")

    while len(Q)>0:
        print(Q.pop())

Score : 400 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the integer written into the block of step 1 was x.

Construct a permutation of (1, 2, ..., 2N-1) that could have been written into the blocks of step N, or declare that Snuke's memory is incorrect and such a permutation does not exist.

Constraints

2≤N≤10^5

1≤x≤2N-1

Input

The input is given from Standard Input in the following format:

N x

Output

If no permutation of (1, 2, ..., 2N-1) could have been written into the blocks of step N, print No.

Otherwise, print Yes in the first line, then print 2N-1 lines in addition.

The i-th of these 2N-1 lines should contain the i-th element of a possible permutation.

Sample Input 1

4 4

Sample Output 1

Yes
1
6
3
7
4
5
2

This case corresponds to the figure in the problem statement.

Sample Input 2

2 1

Sample Output 2

No

No matter what permutation was written into the blocks of step N, the integer written into the block of step 1 would be 2.


n,a,b = map(int,input().split())
s = input()
na = 0
nb = 0
for i in range(len(s)):
  if na + nb >= a+b:
    print("No")
  elif s[i]=="a":
    na += 1
    print("Yes")
  elif s[i]=="b":
    if nb < b:
      nb += 1
      print("Yes")
    else:
      print("No")
  else:
    print("No")

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


N, A, B = map(int,input().split())
S = input()
S = "a"*10000
yosen = 0
yosen_b = 1
for i in range(N):
    if S[i] == "a" and yosen < (A + B):
            print("Yes")
            yosen += 1
    elif S[i] == "b" and yosen < (A + B) and yosen_b <= B:
            print("Yes")
            yosen += 1
            yosen_b += 1
    else:
        print("No")


def myAnswer(A: int, B: int, S: list) -> None:
    counter = 0
    foreignStu = 1
    for i, s in enumerate(S):
        if(s == 'a' and counter < (A + B)): #国内の学生で、カウンタの値が(A+B)未満なら通過
            print("Yes")
            counter += 1#カウンタの値を更新
        elif(s == 'b' and counter < (A + B) and foreignStu <= B): #海外の学生で、カウンタの値が(A+B)未満かつ海外学生の順位がB以下なら通過
            print("Yes")
            counter += 1
            foreignStu += 1
        else:
            print("No")

def main():
    N, A, B = map(int, input().split())
    S = list(input())
    myAnswer(A, B, S)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N=int(input())
a=list(map(int1,input().split()))
ans=0
for i,x in enumerate(a):
    if i==a[x]:
        ans+=1
ans//=2
print(ans)

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

def foo(a,b,ans):
    z = d[a][b]
    for p in range(3):
        for q in range(3):
            if a-2+p<0 or a+p>=h or b-2+q<0 or b+q>=w:
                continue
            ok = True
            reachorig = False
            v = 0
            for i in range(3):
                for j in range(3):
                    if p+i==q+j==2:
                        reachorig = True
                    if z[p+i][q+j]==1:
                        if reachorig:
                            v += 1
                        else:
                            ok = False
                            break
            if ok:
                ans[v] += 1

h,w,n = inm()
d = {}
ab = []
for i in range(n):
    a,b = inm()
    a -= 1
    b -= 1
    ab.append((a,b))
    if a not in d:
        d[a] = {}
    d[a][b] = [[0]*5 for j in range(5)]
    d[a][b][2][2] = 1
for a,b in ab:
    for dx in range(-2,3):
        for dy in range(-2,3):
            if a+dx in d and b+dy in d[a+dx] and not (dx==dy==0):
                d[a+dx][b+dy][2-dx][2-dy] = 1

if False and DBG:
    for i in range(h):
        for j in range(w):
            if i in d and j in d[i]:
                #print(f"{i=} {j=}")
                for k in range(5):
                    print(d[i][j][k])
ans = [0]*10
for a,b in ab:
    foo(a,b,ans)
print((h-2)*(w-2)-sum(ans))
for i in range(1,10):
    print(ans[i])

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

The input is given from Standard Input in the following format:

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

4 5 8
1 1
1 4
1 5
2 3
3 1
3 2
3 4
4 4

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

10 10 20
1 1
1 4
1 9
2 5
3 10
4 2
4 7
5 9
6 4
6 6
6 7
7 1
7 3
7 7
8 1
8 5
8 10
9 2
10 4
10 9

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


F=lambda:tuple(int(X)for X in input().split());H,W,N=F();S={F()for _ in[0]*N};T=set();Z=[0]*10
for Y,X in S:
	for A in range(9):
		A,B=X+A%3-1,Y+A//3-1
		if 0<A<W-1 and 0<B<H-1 and(A,B)not in T:
			T.add((A,B));Q=0
			for C in range(9):Q+=(B+C//3,A+C%3)in S
			Z[Q]+=1
print(*Z,sep='\n')


a=[int(i) for i in input().split()]
b=[]
for i in range(a[2]):
  b.append([int(j) for j in input().split()])
import collections
import time
c=[]
d=[0 for i in range(10)]
for i in range(len(b)):
  for jj in [-2,-1,0]:
    for kk in [-2,-1,0]:
      if 0<b[i][0]+jj<a[0]-1 and 0<b[i][1]+kk<a[1]-1:
       c.append((b[i][0]+jj,b[i][1]+kk))
count_dict = collections.Counter(c)
n=count_dict.values()
for i in n:
  d[i]+=1
d[0]=(a[0]-2)*(a[1]-2)-len(n)
for j in range(10):
 print(d[j])


A, B, C = map(int, input().split())
if A%2 == 0 or B%2 == 0 or C%2 == 0:
  print(0)
else:
  dice = [A, B, C]
  dice.sort(reverse=True)
  print(A*B*C-dice[1]*dice[2])

Score : 200 points

Problem Statement

We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:

There is at least one red block and at least one blue block.

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.

Constraints

2≤A,B,C≤10^9

Input

The input is given from Standard Input in the following format:

A B C

Output

Print the minimum possible difference between the number of red blocks and the number of blue blocks.

Sample Input 1

3 3 3

Sample Output 1

9

For example, Snuke can paint the blocks as shown in the diagram below.
There are 9 red blocks and 18 blue blocks, thus the difference is 9.

Sample Input 2

2 2 4

Sample Output 2

0

For example, Snuke can paint the blocks as shown in the diagram below.
There are 8 red blocks and 8 blue blocks, thus the difference is 0.

Sample Input 3

5 3 5

Sample Output 3

15

For example, Snuke can paint the blocks as shown in the diagram below.
There are 45 red blocks and 30 blue blocks, thus the difference is 9.


a=int(input())
b=int(input())
c=int(input())
d=int(input())
ans=0
if a<=b:
    ans=a*c
else:
    ans=b*c+(a-b)*d
print(ans)

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


n, k, x, y = [int(input()) for i in range(4)]

print(k*x + (n-k)*y)


a=[N,K,X,Y]
for i in range(0,4):
    a=a.append(input())
if N>K:
    print(K*X+(N-K)*Y)
else:
    print(N*X)


w = raw_input()

for c in w :
  if w.count(c) % 2 != 0 :
    print "No"
    break
else :
  print "Yes"

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

The input is given from Standard Input in the following format:

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


N=int(input())
A=[int(input()) for _ in range(N)]

ans=0
for i in range(0,N-1,2):
  a,b=A[i],A[i+1]
  if b%2==1 and a%2==1:
    ans+=a%2
    A[i]-=1
    A[i+1]-=1

for a in A:
  ans+= a//2
print(ans)

Score : 400 points

Problem Statement

Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it.
He has A_i cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum number of pairs that Snuke can create.

Sample Input 1

4
4
0
3
2

Sample Output 1

4

For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

Sample Input 2

8
2
0
1
6
0
8
2
1

Sample Output 2

9


def examA():
    S = SI()
    if "W" in S and not "E" in S:
        print("No")
    elif "E" in S and not "W" in S:
        print("No")
    elif "N" in S and not "S" in S:
        print("No")
    elif "S" in S and not "N" in S:
        print("No")
    else:
        print("Yes")
    return

def examB():
    N = I()
    A = [I()for _ in range(N)]
    ans = 0
    for i in range(N-1):
        ans += A[i]//2
        if A[i]%2 and A[i+1]>=1:
            ans += 1
            A[i+1] -= 1
    ans += A[N-1]//2
    print(ans)
    return

def examC():
    N = I()
    A = [I()for _ in range(N)]
    if N==1:
        print(0)
        return
    odd = set()
    for i in range(N):
        if i&1==0:
            odd.add(A[i])
    A.sort()
    ans = 0
    for i in range((N+1)//2):
        if A[i*2] in odd:
            continue
        ans += 1
    print(ans)
    return

def examD():
    def factorization_(a):
        rep = [[]for _ in range(2)]
        pair = []
        for i in range(2,int(10**(10*1/3))+2):
            cur = 0
            while a%i==0:
                cur += 1
                a //= i
            if cur>0:
                cur %= 3
                if cur==0:
                    continue
                rep[0].append((i,cur))
                pair.append((i,3-cur))
        if not rep[0]:
            rep[0].append((0,0))
        rep[1] = a
        rep[0] = tuple(rep[0])

        rep = tuple(rep)
        pair = tuple(pair)
        return rep, pair

    N = I()
    S = [I()for _ in range(N)]
    group = defaultdict(int)
    P = defaultdict(tuple)
    for s in S:
        g,p = factorization_(s)
        group[g] += 1
        P[g[0]] = p
    #print(group)
    G2 = deepcopy(group)
    #print(P)
    used = set()
    ans = 0
    for key,c in group.items():
        rep, rest = key
        if (rep,rest) in used:
            continue
        pair = rest**2
        if rep==((0,0),) and rest==1:
            ans += 1
        else:
            ans += max(c,G2[(P[rep],pair)])
            used.add((rep,rest))
            used.add((P[rep], pair))
        #print(ans)
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examD()

"""

"""

Score : 1100 points

Problem Statement

Snuke got positive integers s_1,...,s_N from his mother, as a birthday present. There may be duplicate elements.

He will circle some of these N integers. Since he dislikes cubic numbers, he wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product s_is_j is not cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not possible to circle both s_1 and s_2 at the same time. It is not possible to circle both s_3 and s_4 at the same time, either.

Find the maximum number of integers that Snuke can circle.

Constraints

1 ≦ N ≦ 10^5

1 ≦ s_i ≦ 10^{10}

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
s_1
:
s_N

Output

Print the maximum number of integers that Snuke can circle.

Sample Input 1

8
1
2
3
4
5
6
7
8

Sample Output 1

6

Snuke can circle 1,2,3,5,6,7.

Sample Input 2

6
2
4
8
16
32
64

Sample Output 2

3

Sample Input 3

10
1
10
100
1000000007
10000000000
1000000009
999999999
999
999
999

Sample Output 3

9


n = int(input())

li = list(map(int,input().split()))

ans = 10**10

for i in range(-100,101):
    temp = 0
    for x in li:
        temp += (x - i) ** 2
    if ans > temp:
        ans = temp

print(ans)

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10000000)
INF = 1<<32

def solve(N: int, M: int, x: "List[int]", y: "List[int]"):
    c = [1] * (N+1)
    p = [False] * (N+1)
    p[1] = True

    for i in range(M):
        if p[x[i]] is True:
            p[y[i]] = True
            c[y[i]] += 1
            c[x[i]] -= 1

        if c[x[i]] == 0:
            p[x[i]] = False

    print([i for i in p if i is True].count(True))
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    x = [int()] * (M)  # type: "List[int]"
    y = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        x[i] = int(next(tokens))
        y[i] = int(next(tokens))
    solve(N, M, x, y)

if __name__ == '__main__':
    main()

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

The input is given from Standard Input in the following format:

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, X, Y, Z = MAP()
M = X + Y + Z

# XYZとの一致をチェックするビット列
check = 1<<(X+Y+Z-1) | 1<<(Y+Z-1) | 1<<(Z-1)
dp = list2d(N+1, 1<<(M-1), 0)
# dp[i][S] := i個目まで見て、前の値M-1以下までの集合がSの時の、XYZを含まないものの通り数
dp[0][0] = 1
msk1 = (1<<M) - 1
msk2 = (1<<(M-1)) - 1
for i in range(N):
    for S in range(1<<(M-1)):
        if not dp[i][S]:
            continue
        for j in range(10):
            # 1ビットずらして1を足してjビットずらしてマスクする
            S2 = (S<<1|1)<<j & msk1
            # 直前Mビットで使った値がXYZと一致していないか確認する
            if (S2 & check) != check:
                dp[i+1][S2&msk2] += dp[i][S]
                dp[i+1][S2&msk2] %= MOD
total = pow(10, N, MOD)
print((total-sum(dp[N])%MOD)%MOD)

Score : 700 points

Problem Statement

Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences.

Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many contain an X,Y,Z-Haiku?

Here, an integer sequence a_0, a_1, ..., a_{N-1} is said to contain an X,Y,Z-Haiku if and only if there exist four indices x, y, z, w (0 ≦ x < y < z < w ≦ N) such that all of the following are satisfied:

a_x + a_{x+1} + ... + a_{y-1} = X

a_y + a_{y+1} + ... + a_{z-1} = Y

a_z + a_{z+1} + ... + a_{w-1} = Z

Since the answer can be extremely large, print the number modulo 10^9+7.

Constraints

3 ≦ N ≦ 40

1 ≦ X ≦ 5

1 ≦ Y ≦ 7

1 ≦ Z ≦ 5

Input

The input is given from Standard Input in the following format:

N X Y Z

Output

Print the number of the sequences that contain an X,Y,Z-Haiku, modulo 10^9+7.

Sample Input 1

3 5 7 5

Sample Output 1

1

Here, the only sequence that contains a 5,7,5-Haiku is [5, 7, 5].

Sample Input 2

4 5 7 5

Sample Output 2

34

Sample Input 3

37 4 2 3

Sample Output 3

863912418

Sample Input 4

40 5 7 5

Sample Output 4

562805100


# -*- coding: utf-8 -*-
def forgive(num):
    for i in range(10):
        if ((num + i) % 10) in unforgiven:
            continue
        else:
            return num + i

N, K = map(int, input().split())
unforgiven = list(map(int, input().split()))
unforgiven.sort()

price = [int(x) for x in str(N)]
purchase = 0
dig = 0
forgiven = 0
for num in reversed(price):
    forgiven = forgive(num + forgiven // 10)
    purchase += (forgiven % 10) * (10 ** dig)
    dig += 1
else:
    if forgiven >= 10:
        purchase += forgive(1) * (10 ** dig)

print(purchase)

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

H, W, A, B = list(map(int, sys.stdin.readline().split()))

# dp = np.ones(W, dtype=int)
# for h in range(1, H - A):
#     dp = dp.cumsum() % MOD
# for h in range(H - A, H):
#     dp[B:] = dp[B:].cumsum() % MOD
# print(dp[-1])

def get_factorials(max, mod=None):
    """
    階乗 0!, 1!, 2!, ..., max!
    :param int max:
    :param int mod:
    :return:
    """
    ret = [1]
    n = 1
    if mod:
        for i in range(1, max + 1):
            n *= i
            n %= mod
            ret.append(n)
    else:
        for i in range(1, max + 1):
            n *= i
            ret.append(n)
    return ret

def mod_inv(a, mod):
    """
    a の逆元
    :param int a:
    :param int mod:
    :return:
    """
    return pow(a, mod - 2, mod)

factorials = get_factorials(H + W, MOD)

def ncr(n, r, mod=None):
    """
    scipy.misc.comb または scipy.special.comb と同じ
    組み合わせの数 nCr
    :param int n:
    :param int r:
    :param int mod: 3 以上の素数であること
    :rtype: int
    """
    if n < r:
        return 0

    return factorials[n] * mod_inv(factorials[r], mod) * mod_inv(factorials[n - r], mod) % mod

ans = 0
for i in range(W - B):
    ans += ncr((H - A - 1) + (W - i - 1), W - i - 1, MOD) * ncr((A - 1) + i, i, MOD)
    ans %= MOD
print(ans)

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

The input is given from Standard Input in the following format:

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


import sys
def input():
	return sys.stdin.readline()[:-1]
n, k = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(n-1):
	a, b = map(int, input().split())
	adj[a-1].append(b-1)
	adj[b-1].append(a-1)

def bfs(start, nxt):
	vis = [-1 for _ in range(n)]
	vis[start] = 0
	vis[nxt] = 1
	s = [nxt]
	cnt = 1
	while s:
		l = s.pop()
		cnt += 1
		if vis[l] < k:
			for c in adj[l]:
				if vis[c] < 0:
					s.append(c)
					vis[c] = vis[l] + 1
	return n - cnt

ans = n-2
for i in range(n):
	for j in adj[i]:
		ans = min(ans, bfs(i, j))
print(ans)

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

The input is given from Standard Input in the following format:

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

6 2
1 2
3 2
4 2
1 6
5 6

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

6 5
1 2
3 2
4 2
1 6
5 6

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.