local n,k=io.read("n","n")
local R,S,P=io.read("n","n","n","l")
local t=io.read()
local a={}
local point=0

for i=1,n do
    if t:sub(i,i)=="r" then
        a[i]="p"
        point=point+P
    end
    if t:sub(i,i)=="s" then
        a[i]="r"
        point=point+R
    end
    if t:sub(i,i)=="p" then
        a[i]="s"
        point=point+S
    end
end

for i=1,n do
    if a[i]==a[i+k] and i+k<=n then
        if a[i]=="p" then
            point=point-P
            a[i+k]="r"
        end
        if a[i]=="r" then
            point=point-R
            a[i+k]="s"
        end
        if a[i]=="s" then
            point=point-S
            a[i+k]="p"
        end
    end
end

print(point)

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


a, b = io.read"*n", io.read"*n"
print(6-a-b)

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

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3

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.


local n = io.read("*n")
local cur = 1
for i = 1, n do
  local a = io.read("*n")
  if a == cur then
    cur = cur + 1
  end
end
local used = cur - 1
if used == 0 then
  print(-1)
else
  print(n - used)
end

Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.


N=io.read"*n"
if(N%2==1)then print(0)return end
s=0
i=10
while(i<=N)do
	s=s+math.floor(N/i)
	i=i*5
end
print(s)

Score : 500 points

Problem Statement

For an integer n not less than 0, let us define f(n) as follows:

f(n) = 1 (if n < 2)

f(n) = n f(n-2) (if n \geq 2)

Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).

Constraints

0 \leq N \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of trailing zeros in the decimal notation of f(N).

Sample Input 1

12

Sample Output 1

1

f(12) = 12 × 10 × 8 × 6 × 4 × 2 = 46080, which has one trailing zero.

Sample Input 2

5

Sample Output 2

0

f(5) = 5 × 3 × 1 = 15, which has no trailing zeros.

Sample Input 3

1000000000000000000

Sample Output 3

124999999999999995


local n=io.read("*n")
if n%2==1 then
  print(0)
else
  local f,ans=1,0
  n=n//2
  while n>1 do
    ans=ans+n//5
    n=n//5
  end
  print(ans)
end


a,b,c=io.read("*n","*n","*n")
if 21<a+b+c then
  print("bust")
else
  print("win")
end

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


local A = tostring(io.read())

local counter = 0
for i=1 , #A/2 do
    if string.sub(A, i, i) ~= string.sub(string.reverse(A), i, i) then
        counter = counter + 1
    end
end
print(string.format("%d", counter))

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2


local A = tostring(io.read())

local counter = 0
for i=1 , #A do
    if string.sub(A, i, i) ~= string.sub(string.reverse(A), i, i) then
        counter = counter + 1
    end
end
print(counter/2)


local n=io.read("n")
local a={}
for i=1,n do
    a[i]=io.read("n")
end

local mod=1000000007
local total=0
local two=1
for i=0,59 do
    local odd,even=0,0
    for j=1,n do
        if a[j]&(1<<i)>0 then
            odd=odd+1
        else
            even=even+1
        end
    end
    local add=(odd*even)%mod*two%mod
    total=(total+add)%mod
    two=(two*2)%mod
end
print(total)

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

2 \leq N \leq 3 \times 10^5

0 \leq A_i < 2^{60}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo (10^9+7).


local mod = 1000000007
local mfl = math.floor
local function bmul(x, y)
  local x0, y0 = x % 31623, y % 31623
  local x1, y1 = mfl(x / 31623), mfl(y / 31623)
  return (x1 * y1 * 14122 + (x1 * y0 + x0 * y1) * 31623 + x0 * y0) % mod
end
local function badd(x, y) return (x + y) % mod end
local function lltonumber(str)
  local ret = 0LL
  local sign = str:sub(1, 1) ~= "-"
  local begin = sign and 1 or 2
  for i = begin, #str do
    ret = ret * 10LL
    ret = ret + tonumber(str:sub(i, i))
  end
  if not sign then ret = ret * -1LL end
  return ret
end

local n = io.read("*n", "*l")
local box = {0}
local mul = {1}
for i = 2, 61 do
  box[i] = 0
  mul[i] = bmul(mul[i - 1], 2)
end
local ret = 0
local s = io.read()
local str = {}
for z in s:gmatch("%d+") do
  table.insert(str, z)
end
for i = 1, n do
  local a = lltonumber(str[i])
  for j = 1, 61 do
    local p = a % 2
    if p == 1LL then
      ret = badd(ret, bmul(mul[j], i - 1 - box[j]))
      box[j] = box[j] + 1
    else
      ret = badd(ret, bmul(mul[j], box[j]))
    end
    a = a / 2
  end
end
print(ret)


Score: 100 points

Problem Statement

In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019.

Integers M_1, D_1, M_2, and D_2 will be given as input.

It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1.

Determine whether the date 2019-M_1-D_1 is the last day of a month.

Constraints

Both 2019-M_1-D_1 and 2019-M_2-D_2 are valid dates in the Gregorian calendar.

The date 2019-M_2-D_2 follows 2019-M_1-D_1.

Input

Input is given from Standard Input in the following format:

M_1 D_1
M_2 D_2

Output

If the date 2019-M_1-D_1 is the last day of a month, print 1; otherwise, print 0.

Sample Input 1

11 16
11 17

Sample Output 1

0

November 16 is not the last day of a month.

Sample Input 2

11 30
12 1

Sample Output 2

1

November 30 is the last day of November.


local function comp(a, b)
  return a < b
end

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if not comp(ary[1], x) then return 1 end
  if comp(ary[num], x) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = (min + max) // 2
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local n = io.read("*n", "*l")
local s = io.read()
local t = {}
for i = 1, 10 do
  t[i] = {}
end
for i = 1, n do
  local v = s:sub(i, i):byte() - 48
  if v == 0 then v = 10 end
  table.insert(t[v], i)
end
local ret = 0
for i = 1, 10 do
  local lb1 = lower_bound(t[i], 1)
  if lb1 <= #t[i] then
    local p1 = t[i][lb1]
    for j = 1, 10 do
      local lb2 = lower_bound(t[j], p1 + 1)
      if lb2 <= #t[j] then
        local p2 = t[j][lb2]
        for k = 1, 10 do
          local lb3 = lower_bound(t[k], p2 + 1)
          if lb3 <= #t[k] then
            ret = ret + 1
          end
        end
      end
    end
  end
end
print(ret)

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


local n = io.read("*n")
local v1, v2, v3 = 0, 0, 0
local ret = 1
for i = 1, n do
  local a = io.read("*n")
  local c = 0
  if v1 == a then
    c = c + 1
  end
  if v2 == a then
    c = c + 1
  end
  if v3 == a then
    c = c + 1
  end
  ret = (ret * c) % 1000000007
  if v3 == a then
    v3 = v3 + 1
  elseif v2 == a then
    v2 = v2 + 1
  elseif v1 == a then
    v1 = v1 + 1
  end
end
print(ret)

Score: 500 points

Problem Statement

N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered i says:

"In front of me, exactly A_i people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the N people's hats.

Since the count can be enormous, compute it modulo 1000000007.

Constraints

1 \leq N \leq 100000

0 \leq A_i \leq N-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print the number of possible combinations of colors of the N people's hats, modulo 1000000007.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190


t={SUN=7
,MON=6
,TUE=5
,WED=4
,THU=3
,FRI=2
,SAT=1
}
S=io.read()
print(t[S])

Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


local n = io.read("*n", "*l")
local s = io.read()
for i = 1, #s do
  io.write(string.char((s:sub(i, i):byte() - 65 + n) % 26 + 65))
end
io.write("\n")

Score : 200 points

Problem Statement

We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.

Shift each character of S by N in alphabetical order (see below), and print the resulting string.

We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).

Constraints

0 \leq N \leq 26

1 \leq |S| \leq 10^4

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the string resulting from shifting each character of S by N in alphabetical order.

Sample Input 1

2
ABCXYZ

Sample Output 1

CDEZAB

Note that A follows Z.

Sample Input 2

0
ABCXYZ

Sample Output 2

ABCXYZ

Sample Input 3

13
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Sample Output 3

NOPQRSTUVWXYZABCDEFGHIJKLM


local n = io.read("*n")
local nodecol = {}
local edgecol = {}
local edge = {}
for i = 1, n do
  nodecol[i] = 0
  edge[i] = {}
end
for i = 1, n - 1 do
  edgecol[i] = 0
  local a, b = io.read("*n", "*n")
  edge[a][b] = i
  edge[b][a] = i
end
local snode = 0
for i = 1, n do
  local edgecnt = 0
  for k, v in pairs(edge[i]) do
    edgecnt = edgecnt + 1
  end
  if edgecnt == 1 then
    snode = i
    break
  end
end
nodecol[snode] = 1
local tasknode = {}
for dstnode, edgeid in pairs(edge[snode]) do
  nodecol[dstnode] = 1
  edgecol[edgeid] = 1
  table.insert(tasknode, dstnode)
end
local maxcol = 1
local mma = math.max
for i = 1, n - 1 do
  local srcnode = tasknode[i]
  local srccol = nodecol[srcnode]
  local curcol = 1
  for dstnode, edgeid in pairs(edge[srcnode]) do
    if nodecol[dstnode] == 0 then
      if curcol == srccol then curcol = curcol + 1 end
      nodecol[dstnode] = curcol
      edgecol[edgeid] = curcol
      maxcol = mma(maxcol, curcol)
      table.insert(tasknode, dstnode)
      curcol = curcol + 1
    end
  end
end
print(maxcol)
for i = 1, n - 1 do
  print(edgecol[i])
end

Score : 400 points

Problem Statement

Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.

Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.

Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints

2 \le N \le 10^5

1 \le a_i \lt b_i \le N

All values in input are integers.

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

Print N lines.

The first line should contain K, the number of colors used.

The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

Sample Input 1

3
1 2
2 3

Sample Output 1

2
1
2

Sample Input 2

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

Sample Output 2

4
1
2
3
4
1
1
2

Sample Input 3

6
1 2
1 3
1 4
1 5
1 6

Sample Output 3

5
1
2
3
4
5


local n, k = io.read("*n", "*n")
local function modsub(a, b)
  if a < b then return a + k - b
  else return a - b
  end
end

local a = {}
for i = 1, n do
  a[i] = io.read("*n") % k
end
local sum = {a[1]}
for i = 2, n do
  sum[i] = (sum[i - 1] + a[i]) % k
end
for i = 1, n do
  sum[i] = modsub(sum[i], i)
end
local remlist, remlist_uniq = {0}, {}
remlist_uniq[0] = true
for i = 1, n do
  if not remlist_uniq[sum[i]] then
    remlist_uniq[sum[i]] = true
    table.insert(remlist, sum[i])
  end
end
local remlist_inv = {}
local remcnt = {}
for i = 1, #remlist do
  remlist_inv[remlist[i]] = i
  remcnt[i] = 0
end
remcnt[remlist_inv[0]] = 1
local ret = 0
for i = 1, n do
  local reminv = remlist_inv[sum[i]]
  ret = ret + remcnt[reminv]
  remcnt[reminv] = remcnt[reminv] + 1
  if i == k then
    remcnt[remlist_inv[0]] = remcnt[remlist_inv[0]] - 1
  elseif k < i then
     remcnt[remlist_inv[sum[i - k]]] = remcnt[remlist_inv[sum[i - k]]] - 1
  end
end
print(ret)

Score : 500 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.

Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

Constraints

All values in input are integers.

1 \leq N \leq 2\times 10^5

1 \leq K \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print the number of subsequences that satisfy the condition.

Sample Input 1

5 4
1 4 2 3 5

Sample Output 1

4

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

Sample Input 2

8 4
4 2 4 2 4 2 4 2

Sample Output 2

7

(4,2) is counted four times, and (2,4) is counted three times.

Sample Input 3

10 7
14 15 92 65 35 89 79 32 38 46

Sample Output 3

8


n=io.read("*n","*l")
a={0}
for i=1,n do
    a[i]=io.read("*n")
end

b={a[1]}
for i=2,n do
    b[i]=b[i-1]+a[i]
end
c={b[n]}
for i=2,n do
    c[i]=c[i-1]-a[i-1]
end

minyen=2020202020
for i=1,n-1 do
    minyen=math.min(minyen,math.abs(b[i]-c[i+1]))
end
print(minyen)

Score: 200 points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).

Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 2020202020

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:

Shrink the second section from the left. The lengths of the sections are now [2, 3, 3].

Shrink the first section from the left. The lengths of the sections are now [1, 3, 3].

Shrink the second section from the left. The lengths of the sections are now [1, 2, 3], and we can cut the bar at the second notch from the left into two parts of length 3 each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0


Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
----
-- A
local A = read.nn()
local ans = A*A
print(ans)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
----
-- B
local N = read.nl()
local S = read.l()
local h = S:sub(1, N//2)
if S == h..h then
    print("Yes")
else
    print("No")
end

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


local msq = math.sqrt
local n = io.read("*n")
local x, y = {}, {}
for i = 1, n do
  x[i], y[i] = io.read("*n", "*n")
end
local function getlen(i, j)
  return msq((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]))
end
local tot = 1
for i = 2, n do
  tot = tot * i
end
local function getpattern(n, patall, idx)
  local used = {}
  local retary = {}
  local div = patall
  for i = 1, n do used[i] = false end
  for i = n, 1, -1 do
    div = div // i
    local v_idx = idx // div
    idx = idx % div
    local tmp_idx = 0
    for j = 1, n do
      if not used[j] then
        if tmp_idx == v_idx then
          table.insert(retary, j)
          used[j] = true
          break
        else
          tmp_idx = tmp_idx + 1
        end
      end
    end
  end
  return retary
end
local ans = 0
for i = 0, tot - 1 do
  local ary = getpattern(n, tot, i)
  for j = 1, n - 1 do
    ans = ans + getlen(ary[j], ary[j + 1])
  end
end
print(ans / tot)

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


local function reada(n,m)m=m or 1 r={}for i=1,m do r[i]={}end for i=1,n do for j=1,m do r[j][i]=io.read"*n"end end return unpack(r)end
N=io.read"*n"
x,y=reada(N,2)
function d(x1,y1,x2,y2)return math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))end

s=0
for i=1,N do
for j=1,i-1 do
s=s+d(x[i],y[i],x[j],y[j])
end
end
print(s/N*2)


local mfl = math.floor

local function get_ary_from_idx(idx, n)
  idx = idx - 1
  local box = {}
  for i = 1, n do box[i] = true end
  local rettbl = {}
  for i = n, 1, -1 do
    local pos = idx % i + 1
    idx = mfl(idx / i)
    local cnt = 0
    for j = 1, n do
      if box[j] then
        cnt = cnt + 1
        if cnt == pos then
          box[j] = false
          table.insert(rettbl, j)
          break
        end
      end
    end
  end
  return rettbl
end

local function get_idx_from_ary(ary)
  local retidx = 0
  local n = #ary
  local cpy = {}
  for i = 1, n do cpy[i] = ary[i] end
  for i = 1, n - 1 do
    for j = i + 1, n do
      if cpy[i] < cpy[j] then cpy[j] = cpy[j] - 1 end
    end
  end
  for i = n, 1, -1 do
    retidx = retidx * (n + 1 - i) + cpy[i] - 1
  end
  return retidx + 1
end

local n = io.read("*n")
local x, y = {}, {}
for i = 1, n do
  x[i], y[i] = io.read("*n", "*n")
end

local allpat = 1
for i = 1, n do
  allpat = allpat * i
end

local msq = math.sqrt
local function getlen(p, q)
  return msq((x[p] - x[q]) * (x[p] - x[q]) + (y[p] - y[q]) * (y[p] - y[q]))
end
local len = 0
for i = 1, allpat do
  local a = get_ary_from_idx(i, n)
  for j = 1, #a - 1 do
    len = len + getlen(a[j], a[j + 1])
  end
end
print(string.format("%.10f", len / allpat))


local mfl = math.floor
local mod = 1000000007
local function bmul(x, y)
  local x0, y0 = x % 31623, y % 31623
  local x1, y1 = mfl(x / 31623), mfl(y / 31623)
  return (x1 * y1 * 14122 + (x1 * y0 + x0 * y1) * 31623 + x0 * y0) % mod
end

local function modpow(src, pow)
  local res = 1
  while 0 < pow do
    if pow % 2 == 1 then
      res = bmul(res, src)
      pow = pow - 1
    end
    src = bmul(src, src)
    pow = mfl(pow / 2)
  end
  return res
end

local function modinv(src)
  return modpow(src, mod - 2)
end

local function getComb(n, k)
  local ret = 1
  for i = 1, k do
    ret = bmul(ret, n + 1 - i)
    ret = bmul(ret, modinv(i))
  end
  return ret
end

local x, y = io.read("*n", "*n")
if (x + y) % 3 ~= 0 then
  print(0)
else
  local n = mfl((x + y) / 3)
  if x < n or y < n then
    print(0)
  else
    x = x - n
    y = y - n
    print(getComb(n, y))
  end
end

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


local mma = math.max
local n, t = io.read("*n", "*n")
local a, b = {}, {}
for i = 1, n do
  a[i], b[i] = io.read("*n", "*n")
end

local function solve()
  if t == 1 then
    local t1ret = b[1]
    for i = 2, n do
      t1ret = mma(t1ret, b[i])
    end
    return t1ret
  end
  local totret = 0
  local tail = {}
  for i = 1, n do
    tail[i] = {}
    for j = 1, t - 1 do
      tail[i][j] = 0
    end
  end
  local curmax = 0
  for i = n, 1, -1 do
    for j = 1, curmax do
      tail[i][j] = mma(tail[i][j], tail[i + 1][j])
      if j + a[i] < t then
        tail[i][j + a[i]] = mma(tail[i][j + a[i]], tail[i + 1][j] + b[i])
        curmax = mma(curmax, j + a[i])
      end
    end
    if a[i] < t then
      tail[i][a[i]] = mma(tail[i][a[i]], b[i])
      curmax = mma(curmax, a[i])
    end
  end
  local head = {}
  for i = 1, t - 1 do
    head[i] = 0
  end
  curmax = 0
  for i = 1, n - 1 do
    local headmax = {}
    headmax[1] = head[1]
    for j = 2, t - 1 do
      headmax[j] = mma(head[j], headmax[j - 1])
    end
    local tailmax = {}
    tailmax[1] = tail[i + 1][1]
    for j = 2, t - 1 do
      tailmax[j] = mma(tail[i + 1][j], tailmax[j - 1])
    end
    local iret = 0
    if 1 < t then iret = mma(headmax[t - 1], tailmax[t - 1]) end
    for j = 1, t - 2 do
      iret = mma(iret, headmax[j] + tailmax[t - 1 - j])
    end
    iret = iret + b[i]
    totret = mma(totret, iret)
    for j = t - 1 - a[i], 1, -1 do
      head[j + a[i]] = mma(head[j + a[i]], head[j] + b[i])
    end
  end
  do -- i == n
    local headmax = {}
    headmax[1] = head[1]
    for j = 2, t - 1 do
      headmax[j] = mma(head[j], headmax[j - 1])
    end
    local iret = 1 < t and headmax[t - 1] or 0
    iret = iret + b[n]
    totret = mma(totret, iret)
  end
  return totret
end
print(solve())

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


local mmi, mma = math.min, math.max
local n, k = io.read("*n", "*n")
local h = {0}
for i = 1, n do
  h[i + 1] = io.read("*n")
end
h[n + 2] = 0
local t = {}
for i = 1, n + 2 do
  t[i] = {}
  for j = 1, k + 1 do
    t[i][j] = 0
  end
end
for i = 2, n + 1 do
  t[i] = {}
  for j = 1, k + 1 do
    t[i][j] = t[i - 1][j]
  end
  for j = i, n + 1 do
    local score = 0
    local tgt = mma(h[i - 1], h[j + 1])
    for z = i, j do
      score = score + mma(0, h[z] - tgt)
    end
    local len = j + 1 - i
    for z = len + 1, k + 1 do
      t[j][z] = mma(t[j][z], t[i - 1][z - len] + score)
    end
  end
end
local ret = -t[n + 1][1]
for i = 2, k + 1 do
  ret = mmi(ret, -t[n + 1][i])
end
for i = 2, n + 1 do
  ret = ret + mma(0, h[i] - h[i - 1])
end
print(ret)

Score : 600 points

Problem Statement

We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns.

The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column.

Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive).

Different values can be chosen for different columns.

Then, you will create the modified artwork by repeating the following operation:

Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)

Find the minimum number of times you need to perform this operation.

Constraints

1 \leq N \leq 300

0 \leq K \leq N

0 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 H_2 ... H_N

Output

Print the minimum number of operations required.

Sample Input 1

4 1
2 3 4 1

Sample Output 1

3

For example, by changing the value of H_3 to 2, you can create the modified artwork by the following three operations:

Paint black the 1-st through 4-th squares from the left in the 1-st row from the bottom.

Paint black the 1-st through 3-rd squares from the left in the 2-nd row from the bottom.

Paint black the 2-nd square from the left in the 3-rd row from the bottom.

Sample Input 2

6 2
8 6 9 1 2 1

Sample Output 2

7

Sample Input 3

10 0
1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000

Sample Output 3

4999999996


local n = io.read("*n")
if n % 2 == 0 then
  print(n // 2 - 1)
else
  print(n // 2)
end

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


local n=io.read("*n")
local verte={}
local flag=true
for i=1,n do
    local x=io.read("*n")
    if (i==1 and x>0) or (i>1 and x==0) then
        flag=false
    end
    verte[x]=(verte[x] or 0)+1
end

if not flag then
    print(0)
else
    local tree=1
    local mod=998244353
    for x,_ in pairs(verte) do
        if x+1<=#verte then
            if not verte[x] or not verte[x+1] then
                print(0)
                return
            end
            for i=1,verte[x+1] do
                tree=tree*verte[x]%mod
            end
        end
    end
    print(tree)
end

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


local n=io.read("n")
local verte={}
local flag=true
for i=1,n do
    local x=io.read("n")
    if (i==1 and x>0) or (i>1 and x==0) then
        flag=false
    end
    verte[x]=(verte[x] or 0)+1
end

if not flag then
    print(0)
else
    local tree=1
    local mod=998244353
    for x,_ in pairs(verte) do
        if x+1<=#verte then
            if not verte[x] or not verte[x+1] then
                print(0)
                return
            end
            for i=1,verte[x+1] do
                tree=tree*verte[x]%mod
            end
        end
    end
    print(string.format("%d",tree))
end


local n=io.read("n")
local verte={}
local flag=true
for i=1,n do
    local x=io.read("n")
    if (i==1 and x>0) or (i>1 and x==0) then
        flag=false
    end
    verte[x]=(verte[x] or 0)+1
end

if not flag then
    print(0)
else
    local tree=1
    local mod=998244353
    for x,_ in pairs(verte) do
        if x+1<=#verte then
            if not verte[x] or not verte[x+1] then
                print(0)
                return
            end
            tree=tree*(verte[x]^verte[x+1])%mod
        end
    end
    print(string.format("%d",tree))
end


local mod = 998244353
local function bmul(x, y) return (x * y) % mod end
local function modpow(src, pow)
  local res = 1
  while 0 < pow do
    if pow % 2 == 1 then
      res = bmul(res, src)
      pow = pow - 1
    end
    src = bmul(src, src)
    pow = pow // 2
  end
  return res
end

local function modinv(src)
  return modpow(src, mod - 2)
end

local n = io.read("*n")
local t = {}
for i = 1, n do
  t[i] = 0
end
local tmp = true
local maxlen = 0
for i = 1, n do
  local a = io.read("*n")
  if i == 1 then
    tmp = a == 0
  end
  maxlen = math.max(maxlen, a + 1)
  t[a + 1] = t[a + 1] + 1
end
if not tmp then print(0) os.exit() end
for i = 1, maxlen do
  if t[i] == 0 then
    print(0)
    os.exit()
  end
end
if t[1] ~= 1 then
  print(0)
  os.exit()
end
local ret = 1
for i = 2, maxlen do
  ret = bmul(ret, modpow(t[i - 1], t[i]))
end
print(ret)


local mod = 998244353
local mfl = math.floor
local function bmul(x, y)
  local x0, y0 = x % 31596, y % 31596
  local x1, y1 = mfl(x / 31596), mfl(y / 31596)
  return (x1 * y1 * 62863 + (x1 * y0 + x0 * y1) * 31596 + x0 * y0) % mod
end

local function badd(x, y)
  return (x + y) % mod
end

local function bsub(x, y)
  return x < y and x - y + mod or x - y
end

local function modpow(src, pow)
  local res = 1
  while 0 < pow do
    if pow % 2 == 1 then
      res = bmul(res, src)
      pow = pow - 1
    end
    src = bmul(src, src)
    pow = mfl(pow / 2)
  end
  return res
end

local n = io.read("*n")
local d = {}
local mlen = 0
local mma = math.max
for i = 1, n do
  d[i] = io.read("*n")
  mlen = mma(mlen, d[i])
end
local valid = true
if d[1] ~= 0 then
  valid = false
end
for i = 2, n do
  if d[i] == 0 then
    valid = false
  end
end
local t = {}
for i = 1, mlen do
  t[i] = 0
end
if valid then
  for i = 2, n do
    t[d[i]] = t[d[i]] + 1
  end
end
for i = 1, mlen do
  if t[i] == 0 then
    valid = false
  end
end
if not valid then
  print(0)
else
  local ret = 1
  for i = 2, mlen do
    local v = modpow(t[i - 1], t[i])
    ret = bmul(ret, v)
  end
  print(ret)
end


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  -- for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  -- for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  for i = 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local t1, t2, t3 = {start_stage}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if (l - 1) % sz ~= 0 then
      local newr = mmi(r, mce((l - 1) / sz) * sz)
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, newr)
      l = newr + 1
    end
    if sz <= r + 1 - l then
      ret = self.func(ret, self.stage[stage][mce(l / sz)])
      l = l + sz
    end
    if l <= r then
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end

SegTree.right_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, left - 1
  local t1, t2, t3 = {1}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    while (l - 1) % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = self.size[stage]
    end
    local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
    if tmp > val then
      ret, retpos = tmp, l + sz - 1
      if retpos == right then break end
      if l + sz <= r then table.insert(t1, 1) table.insert(t2, l + sz) table.insert(t3, r) end
    else
      if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, l + sz - 2) end
    end
  end
  return retpos + 1
end
SegTree.left_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, right + 1
  local t1, t2, t3 = {1}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    while r % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = self.size[stage]
    end
    local tmp = self.func(ret, self.stage[stage][mfl(r / sz)])
    if tmp > val then
      ret, retpos = tmp, r - sz + 1
      if l + sz <= r then table.insert(t1, 1) table.insert(t2, l) table.insert(t3, r - sz) end
    else
      if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, r - sz + 2) table.insert(t3, r) end
    end
  end
  return retpos - 1
end

SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local function comp(a, b)
  return a < b
end

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if not comp(ary[1], x) then return 1 end
  if comp(ary[num], x) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local function upper_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if comp(x, ary[1]) then return 1 end
  if not comp(x, ary[num]) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if not comp(x, ary[mid]) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local n = io.read("*n")
local ab = {}
for i = 1, n do
  ab[i] = {io.read("*n")}
end
for i = 1, n do
  ab[i][2] = io.read("*n")
end
table.sort(ab, function(x, y)
  if x[2] ~= y[2] then
    return x[2] < y[2]
  else
    return x[1] < y[1]
  end
end)
local a = {}
local b = {}

for i = 1, n do
  a[i] = ab[i][1]
  b[i] = ab[i][2]
end
local alim = {}
local st = SegTree.new(n, mmi, 1000000007)
-- print(table.concat(a, " "))
-- print(table.concat(b, " "))
for i = 1, n do
  alim[i] = lower_bound(b, a[i])
  st:setValue(i, alim[i], true)
end
st:updateAll()
local cnt = 0
for i = 1, n do
  if i < alim[i] then
    if i == n then
      cnt = n
      break
    end
    local pos = st:left_bound(i, i + 1, n)
    if pos < i then
      cnt = n
      break
    else
      cnt = cnt + 1
      st:setValue(i, alim[pos])
      st:setValue(pos, alim[i])
      alim[i], alim[pos] = alim[pos], alim[i]
    end
  end
end
print(cnt <= n - 2 and "Yes" or "No")

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  -- for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  -- for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  for i = 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local t1, t2, t3 = {start_stage}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if (l - 1) % sz ~= 0 then
      local newr = mmi(r, mce((l - 1) / sz) * sz)
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, newr)
      l = newr + 1
    end
    if sz <= r + 1 - l then
      ret = self.func(ret, self.stage[stage][mce(l / sz)])
      l = l + sz
    end
    if l <= r then
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end

SegTree.right_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, left - 1
  local t1, t2, t3 = {1}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    while (l - 1) % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = self.size[stage]
    end
    local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
    if tmp > val then
      ret, retpos = tmp, l + sz - 1
      if retpos == right then break end
      if l + sz <= r then table.insert(t1, 1) table.insert(t2, l + sz) table.insert(t3, r) end
    else
      if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, l + sz - 2) end
    end
  end
  return retpos + 1
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local function comp(a, b)
  return a < b
end

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if not comp(ary[1], x) then return 1 end
  if comp(ary[num], x) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local function upper_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if comp(x, ary[1]) then return 1 end
  if not comp(x, ary[num]) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if not comp(x, ary[mid]) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local n = io.read("*n")
local ab = {}
for i = 1, n do
  ab[i] = {io.read("*n")}
end
for i = 1, n do
  ab[i][2] = io.read("*n")
end
table.sort(ab, function(x, y)
  if x[2] ~= y[2] then
    return x[2] < y[2]
  else
    return x[1] < y[1]
  end
end)
local a = {}
local b = {}

for i = 1, n do
  a[i] = ab[i][1]
  b[i] = ab[i][2]
end
local alim = {}
local st = SegTree.new(n, mmi, 1000000007)
-- print(table.concat(a, " "))
-- print(table.concat(b, " "))
for i = 1, n do
  alim[i] = lower_bound(b, a[i])
  st:setValue(i, alim[i], true)
end
st:updateAll()
local cnt = 0
for i = 1, n do
  if i < alim[i] then
    if i == n then
      cnt = n
      break
    end
    local pos = st:right_bound(i, i + 1, n)
    if n < pos then
      cnt = n
      break
    else
      cnt = cnt + 1
      st:setValue(i, alim[pos])
      st:setValue(pos, alim[i])
      alim[i], alim[pos] = alim[pos], alim[i]
    end
  end
end
print(cnt <= n - 2 and "Yes" or "No")


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  -- for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  -- for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  for i = 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local t1, t2, t3 = {start_stage}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if (l - 1) % sz ~= 0 then
      local newr = mmi(r, mce((l - 1) / sz) * sz)
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, newr)
      l = newr + 1
    end
    if sz <= r + 1 - l then
      ret = self.func(ret, self.stage[stage][mce(l / sz)])
      l = l + sz
    end
    if l <= r then
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local mma, mmi = math.max, math.min
local n = io.read("*n")
local l, r = {}, {}
local s_idx = {}
for i = 1, n do
  l[i], r[i] = io.read("*n", "*n")
  s_idx[i] = i
end
table.sort(s_idx, function(x, y)
  if l[x] == l[y] then
    return r[x] < r[y]
  else
    return l[x] < l[y]
  end
end)
local lmin_idx = s_idx[1]
table.sort(s_idx, function(x, y)
  if r[x] == r[y] then
    return l[x] < l[y]
  else
    return r[x] < r[y]
  end
end)
local rmax_idx = s_idx[n] == lmin_idx and s_idx[n - 1] or s_idx[n]
local lpoint, rpoint = r[lmin_idx] - l[lmin_idx] + 1, r[rmax_idx] - l[rmax_idx] + 1
local lp, rp = {}, {}
for i = 1, n do
  if i ~= rmax_idx and i ~= lmin_idx then
    table.insert(lp, mma(0, mmi(r[i], r[lmin_idx]) - l[i] + 1))
    table.insert(rp, mma(0, r[i] - mma(l[i], l[rmax_idx]) + 1))
  end
end
-- table.insert(lp, lpoint)
-- table.insert(rp, 0)
table.insert(lp, -1)
table.insert(rp, rpoint)
local t_idx = {}
for i = 1, n - 1 do
  t_idx[i] = i
end
table.sort(t_idx, function(x, y)
  return lp[x] < lp[y]
end)
local inf = 1000000007
local st = SegTree.new(n - 1, function(x, y) return mmi(x, y) end, inf)
local ans = 0
for i = 1, n - 1 do
  st:setValue(i, rp[t_idx[i]])
  local lv = i == n - 1 and lpoint or lp[t_idx[i + 1]]
  local ret = mma(0, lv) + st.stage[1][1]
  -- print(mma(0, lv), st.stage[1][1])
  ans = mma(ans, ret)
end
print(ans)

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931


        n=io.read("*n")
    	cnt=0
        for i=1, 9 do
          if (n%i)==0 and (n/i)<10 then
            print("Yes")
    		os.exit(0)
        	cnt=1
          end
        end
    if cnt==0 then
      print("No")
    end

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


n=io.read("*n")

for i=1, 9 do
  if n%i==0 and n/i<10 then
    print("Yes")
  else
    print("No")
  end
end


local n = io.read("*n")
for i = math.floor(math.sqrt(n)), 1, -1 do
	local dev = n / i
	if dev % 1 == 0 then
		print(string.format("%d", dev + i - 2))
		os.exit()
	end
end

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


n=io.read("*n")

ans=n-1
for i=2, n do
  if n%i==0 then
    ans=(n/i)+i-2
  end
  if n <= i*i then
    break
  end
end

print(ans)


n=io.read("*n")

ans=n-1
for i=2, 9 do
  if n%i==0 then
    ans=(n/i)+i-2
    break
  end
end

print(ans)


n=io.read("*n")

ans=n-1

for i=2, 9 do
  if n%i==0 then
    ans=(n/i)+i-2
  end
end


n=io.read("*n")

p=n
l=1

for i=2, 9 do
  if n/i<p and n%i==0 then
    p=n/i
    l=i
  end
end

if l==1 then
  print(n-1)
else
  print(n/l*l-2)
end


local a,b,x=io.read("*n","*n","*n")
if a*a*b/2<=x then
  print(math.atan(2*(a*a*b-x)/(a*a*a))*180/math.pi)
else
  print((math.pi/2 - math.atan(2*x/(a*b*b)))*180/math.pi)
end

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
--
local function find_min_true(n, f)
    -- Define f(-1) == false, f(n) == true
    -- Invariant: f(left) == false and f(right) == true
    local left = -1
    local right = n
    while right - left > 1 do
        local m = left + math.floor((right - left) / 2)
        if f(m) then
            right = m -- keep f(right) == true
        else
            left = m -- keep f(left) == false
        end
    end
    return right
end
---
local N, K = read.nn()
local A = read.N(N)
local F = read.N(N)
table.sort(A)
table.sort(F, function(x,y)return x>y end)
local upper_lim = A[N] * F[1]

local function possible(max_time)
    local kk = K
    for i=1, N do
        local time = A[i] * F[i]
        if time > max_time then
            local train_cost = math.ceil((A[i] * F[i] - max_time) / F[i])
            kk = kk - train_cost
            if kk < 0 then
                return false
            end
        end
    end
    return true
end
print(find_min_true(upper_lim, possible))

Score: 500 points

Problem Statement

Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.

In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:

A team should assign one member to each food, and should not assign the same member to multiple foods.

It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.

The score of a team is the longest time it takes for an individual member to finish the food.

Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.

What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

0 \leq K \leq 10^{18}

1 \leq A_i \leq 10^6\ (1 \leq i \leq N)

1 \leq F_i \leq 10^6\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N
F_1 F_2 ... F_N

Output

Print the minimum possible score of the team.

Sample Input 1

3 5
4 2 1
2 3 1

Sample Output 1

2

They can achieve the score of 2, as follows:

Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.

Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.

Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.

They cannot achieve a score of less than 2, so the answer is 2.

Sample Input 2

3 8
4 2 1
2 3 1

Sample Output 2

0

They can choose not to do exactly K sets of training.

Sample Input 3

11 14
3 1 4 1 5 9 2 6 5 3 5
8 9 7 9 3 2 3 8 4 6 2

Sample Output 3

12


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
---
local N, K = read.nn()
local A = read.N(N)
local F = read.N(N)
table.sort(A)
table.sort(F, function(x,y)return x>y end)
local upper_lim = A[N] * F[1]

local time = {}
for i=1,N do
    time[i] = A[i] * F[i]
end

local function find_min_true()
    local ceil = math.ceil
    local max = math.max
    local function possible(max_time)
        local kk = K
        for i=1, N do
            kk = kk - max(ceil((time[i] - max_time) / F[i]), 0)
            if kk < 0 then
                return false
            end
        end
        return true
    end
    local left = -1
    local right = upper_lim
    while right - left > 1 do
        local m = left + (right - left) // 2
        if possible(m) then
            right = m
        else
            left = m
        end
    end
    return right
end

print(find_min_true())


local a, b = io.read("*n", "*n")
local rest = a - b * 2
if rest >= 0 then
  print(rest)
else
  print(0)
end

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


a=io.read("*n")
b=io.read("*n")

ans=a-(b*2)
if ans <= 0 then
  print(0)
else
  print(ans)
end


n=io.read("*n")
d={}
for i=1,n do
  table.insert(d,io.read("*n"))
end

v={}
for i=1,n-1 do
  l=0
  for j=i+1,n do
    l=l+d[j]
  end
  table.insert(v,l)
end

ans=0
for i=1,n-1 do
  ans=ans+(d[i]*v[i])
end

print(ans)

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
--
local N = read.n()
local D = read.N(N)
local sum = 0
for i=1,N-1 do
    for j=i+1,N do
        sum = sum + D[i] * D[j]
    end
end
print(sum)


N=io.read"*n"
io.read()
S=io.read()
a=S:sub(1,1)
s=1
for i=2,N do
	if(a~=S:sub(i,i))then s=s+1 a=S:sub(i,i)end
end
print(s)

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


N=io.read"*n"
io.read()
S=io.read()
a=S[1]
s=0
for i=2,N do
	if(a~=S:sub(i,i))then s=s+1 a=S:sub(i,i)end
end
print(s)


function char(s, n)
  return s:sub(n, n)
end

n=io.read("*n", "*l")
s=io.read(n)

ans=1
for i=1,n-1 do
  if char(s,i)~=char(s,i+1) then
    ans=ans+1
  end
end

print(ans)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
--
local N = read.nl()
local S = (read.l()):totable()
local t = {S[1]}
for i=2,N do
    local last = t[#t]
    if S[i] ~= last then
        table.insert(t, S[i])
    end
end
print(#t)


local mfl = math.floor

local function comp(a, b)
  return a < b
end

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if not comp(ary[1], x) then return 1 end
  if comp(ary[num], x) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local n = io.read("*n")
local t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
table.sort(t)
local ret = 0
for i = 1, n - 2 do
  for j = i + 1, n - 1 do
    local lb = lower_bound(t, t[i] + t[j]) - 1
    ret = ret + lb - j
  end
end
print(ret)

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

3 \leq N \leq 2 \times 10^3

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
--
-- 1 <= input to f <= n
local function find_min_true(n, f)
    local function loop(i, j)
        if i == j then
            --assert(i >= 1 and i <= n + 1)
            return i
        end
        local h = math.floor((i + j) / 2)
        --assert(h >= 1 and h <= n)
        if f(h) then
            return loop(i, h)
        else
            return loop(h + 1, j)
        end
    end
    return loop(1, n + 1)
end
--
local N = read.n()
local L = read.N(N)
table.sort(L)
local ans = 0
for i=1,N-2 do
    local a = L[i]
    for j=i+1,N-1 do
        local b = L[j]
        local function count()
            local function f(x)
                x = x + j -- [1,N-j] --> [j+1,N]
                local c = L[x]
                return c >= a + b
            end
            return find_min_true(N-j, f) - 1
        end
        ans = ans + count()
    end
end
print(ans)


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  -- for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  -- for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  for i = 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local t1, t2, t3 = {start_stage}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if (l - 1) % sz ~= 0 then
      local newr = mmi(r, mce((l - 1) / sz) * sz)
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, newr)
      l = newr + 1
    end
    if sz <= r + 1 - l then
      ret = self.func(ret, self.stage[stage][mce(l / sz)])
      l = l + sz
    end
    if l <= r then
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n, m, l = io.read("*n", "*n", "*n")
local edge = {}
for i = 1, n do
  edge[i] = {}
end
for i = 1, m do
  local a, b, c = io.read("*n", "*n", "*n")
  if c <= l then
    edge[a][b] = c
    edge[b][a] = c
  end
end
local len = {}
local inf = 301 * 1000000000
for i = 1, n do
  len[i] = inf
end
local function lessthan(x, y, cost)
  return len[x] + cost < len[y]
end
local function merge(x, y)
  if n < x then return y end
  if n < y then return x end
  return lessthan(x, y, 0) and x or y
end
local st = SegTree.new(n, merge, n + 1)
for i = 1, n do st:setValue(i, i) end
local alllen = {}

local function solve(start_pos)
  alllen[start_pos] = {}
  for i = 1, n do
    len[i] = inf
    alllen[start_pos][i] = 301
  end
  len[start_pos] = 0
  st:updateAll()
  for tankuse = 0, n - 2 do
    local asked = {}
    for i = 1, n do
      asked[i] = false
    end
    for _u = 1, n do
      local src = st.stage[1][1]
      if inf <= len[src] then break end
      asked[src] = true
      if alllen[start_pos][src] == 301 then
        alllen[start_pos][src] = tankuse
      end
      for dst, cost in pairs(edge[src]) do
        if not asked[dst] and len[src] + cost <= l and lessthan(src, dst, cost) then
          len[dst] = len[src] + cost
          st:setValue(dst, dst)
        end
      end
      len[src] = inf
      st:setValue(src, src)
    end
    for i = 1, n do
      if asked[i] then
        len[i] = 0
      end
    end
    st:updateAll()
  end
end

for i = 1, n do
  solve(i)
end

local q = io.read("*n")
for i = 1, q do
  local s, t = io.read("*n", "*n")
  print(alllen[s][t] < 301 and alllen[s][t] or -1)
end

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

3 2 5
1 2 3
2 3 3
2
3 2
1 3

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

5 4 4
1 2 2
2 3 2
3 4 3
4 5 2
20
2 1
3 1
4 1
5 1
1 2
3 2
4 2
5 2
1 3
2 3
4 3
5 3
1 4
2 4
3 4
5 4
1 5
2 5
3 5
4 5

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


n=io.read("*n")
k=io.read("*n")
h={}
for i=1,n do
  table.insert(h,io.read("*n"))
end

ans=0
for i=1,n do
  if h[i]>=k then
    ans=ans+1
  end
end

print(ans)

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


local n, k = io.read("*n", "*n")
local cnt = 0
for i = 1, n do
  local h = io.read("*n")
  if k <= h then cnt = cnt + 1 end
end
print(cnt)


local DBG = true
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end
local function factorize(n)
    local nn = n
    local lst = {}
    for i = 2, math.floor(n ^ 0.5) do
        k = 0
        while nn % i == 0 do
            k = k + 1
            nn = nn // i
            table.insert(lst, i)
        end
    end
    if nn ~= 1 then
        table.insert(lst, nn)
    end
    return lst
end

local A, B = io.read("n","n")
local f1 = factorize(A)
local f2 = factorize(B)
local s1 = {}
for _,v in ipairs(f1) do
    s1[v] = true
end
local s2 = {}
for _,v in ipairs(f2) do
    s2[v] = true
end
local smul = {1}
for k,_ in pairs(s1) do
    if s2[k] then
        table.insert(smul, k)
    end
end
print(#smul)

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


local mfl = math.floor
local function getor(x, y)
  local ret = 0
  local mul = 1
  while(0 < x or 0 < y) do
    if((x % 2) + (y % 2) ~= 0) then
      ret = ret + mul
    end
    x, y, mul = mfl(x / 2), mfl(y / 2), mul * 2
  end
  return ret
end

local n, m = io.read("*n", "*n")
local tot = 1
for i = 1, n do
  tot = tot * 2
end
local t = {}
for i = 1, tot do
  t[i] = -1
end
t[1] = 0
for i = 1, m do
  local a, b = io.read("*n", "*n")
  local c = {}
  for j = 1, b do
    c[io.read("*n")] = true
  end
  local val = 0
  local v = 1
  for j = 1, n do
    if c[j] then
      val = val + v
    end
    v = v * 2
  end
  for src = tot, 1, -1 do
    if 0 <= t[src] then
      local dst = 1 + getor(src - 1, val)
      if t[dst] == -1 or t[src] + a < t[dst] then
        t[dst] = t[src] + a
      end
    end
  end
end
print(t[tot])

Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.stage = {{}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
  end
  self.stagenum = stagenum
  for i = 1, n do self.stage[stagenum][i] = i end
  for i = n + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage, sz = 1, bls(1, stagenum - 1)
    local len = right - left + 1
    while (left - 1) % sz ~= 0 or len < sz do
      stage, sz = stage + 1, brs(sz, 1)
    end
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegTree.top = function(self) return self.stage[1][1] end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n, m = io.read("*n", "*n")
local longest_len = {}
local edge = {}
local invedge = {}
local updated = {}
local startcand = {}
local shortest_len = {}
for i = 1, n + 1 do
  longest_len[i] = -1
  shortest_len[i] = -1
  edge[i] = {}
  invedge[i] = {}
  updated[i] = false
  startcand[i] = true
end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  edge[a][b] = true
  invedge[b][a] = true
  startcand[b] = false
end
local function getmin(a, b)
  if updated[a] and updated[b] then
    return shortest_len[a] < shortest_len[b] and a or b
  elseif updated[a] then return a
  elseif updated[b] then return b
  else return n + 1
  end
end
local function getmax(a, b)
  if updated[a] and updated[b] then
    return longest_len[a] < longest_len[b] and b or a
  elseif updated[a] then return a
  elseif updated[b] then return b
  else return n + 1
  end
end
-- find shortest path
local st = SegTree.new(n, getmin, n + 1)
local looptasks = {}
for i = 1, n do
  if startcand[i] then
    shortest_len[i] = 0
    updated[i] = true
    st:update(i)
    table.insert(looptasks, i)
  end
end
if #looptasks == 0 then looptasks[1] = 1 end

while true do
  local src = st:top()
  if src == n + 1 then break end
  for dst, _u in pairs(edge[src]) do
    if shortest_len[dst] < 0 or shortest_len[src] + 1 < shortest_len[dst] then
      shortest_len[dst] = shortest_len[src] + 1
      updated[dst] = true
      st:update(dst)
    end
  end
  updated[src] = false
  st:update(src)
end

-- find loop candidate
st.func = getmax
for i = 1, #looptasks do
  longest_len[looptasks[i]] = 0
  updated[looptasks[i]] = true
end
st:updateAll()
while true do
  local src = st:top()
  if src == n + 1 then break end
  for dst, _u in pairs(edge[src]) do
    if longest_len[dst] < 0 or longest_len[dst] < longest_len[src] + 1 then
      if longest_len[dst] < n then
        longest_len[dst] = longest_len[src] + 1
        updated[dst] = true
        st:update(dst)
      end
    end
  end
  updated[src] = false
  st:update(src)
end

local loopCandidates = {}
for i = 1, n do
  if n <= longest_len[i] then
    loopCandidates[i] = true
  end
end
-- remove no-loop points from loop candidate points
while true do
  local removed = false
  for src, _u in pairs(loopCandidates) do
    local f = false
    for dst, _u2 in pairs(edge[src]) do
      if loopCandidates[dst] then
        f = true
        break
      end
    end
    if not f then loopCandidates[src], removed = nil, true break end
  end
  if not removed then break end
end

-- remove all no-loop edges
for src, _u in pairs(loopCandidates) do
  for dst, _u2 in pairs(edge[src]) do
    if not loopCandidates[dst] then edge[src][dst] = nil end
  end
  for dst, _u2 in pairs(invedge[src]) do
    if not loopCandidates[dst] then invedge[src][dst] = nil end
  end
end

-- find first length and second length from certain point
local loop_len = {}
local loop_started = {}
for src, _u in pairs(loopCandidates) do
  loop_len[src] = {-1, -1}
  loop_started[src] = false
end
if next(loopCandidates) then
  local src = next(loopCandidates)
  loop_len[src][1] = 0
  updated[src] = true
end

local function getlooptask(a, b)
  if updated[a] and updated[b] then
    if loop_len[a][2] < 0 and loop_len[b][2] < 0 then
      return loop_len[a][1] < loop_len[b][1] and a or b
    elseif loop_len[a][2] < 0 then return a
    elseif loop_len[b][2] < 0 then return b
    else
      return loop_len[a][2] < loop_len[b][2] and a or b
    end
  elseif updated[a] then return a
  elseif updated[b] then return b
  else return n + 1
  end
end

st.func = getlooptask
st:updateAll()

while true do
  local src = st:top()
  if src == n + 1 then break end
  for dst, _u in pairs(edge[src]) do
    if loop_started[dst] then
      if loop_started[src] then
        if loop_len[dst][2] < 0 or loop_len[src][2] + 1 < loop_len[dst][2] then
          loop_len[dst][2] = loop_len[src][2] + 1
          updated[dst] = true
          st:update(dst)
        end
      else
        if loop_len[dst][2] < 0 or loop_len[src][1] + 1 < loop_len[dst][2] then
          loop_len[dst][2] = loop_len[src][1] + 1
          updated[dst] = true
          st:update(dst)
        end
      end
    else
      if loop_len[dst][1] < 0 or loop_len[src][1] + 1 < loop_len[dst][1] then
        loop_len[dst][1] = loop_len[src][1] + 1
        updated[dst] = true
        st:update(dst)
      end
    end
  end
  loop_started[src] = true
  updated[src] = false
  st:update(src)
end

-- get start of shortest loop
local short_loop_start = false
local short_loop_len = false
for src, v in pairs(loop_len) do
  local len = v[2] - v[1]
  if not short_loop_len or len < short_loop_len then
    short_loop_start, short_loop_len = src, len
  end
end
if short_loop_start then
  local ans = {short_loop_start}
  while true do
    local dst = ans[#ans]
    local dstlen = #ans == 1 and loop_len[dst][2] or loop_len[dst][1]
    local f = false
    for src, _u in pairs(invedge[dst]) do
      local srclen = loop_len[src][1]
      if loop_len[src][2] - srclen == short_loop_len and srclen + 1 == dstlen then
        table.insert(ans, src)
        f = true
        break
      end
    end
    if not f then break end
  end
  table.remove(ans)
  print(#ans)
  print(table.concat(ans, "\n"))
else
  print(-1)
end

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5