--url : https://devforum.roblox.com/t/commonly-used-tree-data-structures-in-lua/265673/2

----------

--[[
	Pairing Min Heap

	Binary Heap is faster for increasing and random pushes but this is faster for joining (merging) and decreasing pushes
	It is very optimized

	Use Kill to GC after finished using

--]]

--[[
	Node: {
	Key,
	LeftChild,
	NextSibling,
	}

--]]

-- Constants

-- cached variables

-- local variables

local tables={}
local tSize=0

local function merge(a,b)
	if not a then
		return b
	elseif not b then
		return a
	elseif a[1]<b[1]then
		-- inlined add child
		b[3]=a[2]
		a[2]=b

		return a
	else
		-- inlined add child
		a[3]=b[2]
		b[2]=a

		return b
	end
end

local function twopassmerge(a)
	local b=a and a[3]
	if b then
		local newnode=b[3]

		a[3]=false
		b[3]=false

		return merge(merge(a,b),twopassmerge(newnode))
	else
		return a
	end
end

local function empty(heap)
	return not heap.root
end

local function top(heap)
	return heap.root[1]
end

local function push(heap,key)
	local root=heap.Size+1
	heap.Size=root
	local t=heap.maxSize
	heap.maxSize=(root>t and root)or t

	-- inlined merge (optimized for insert)
	root=heap.root
	if not root then
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			heap.root=t
		else
			heap.root={
				key,
				false,
				false,
			}
		end
	elseif root[1]<key then
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			t[3]=root[2]
			root[2]=t
		else
			root[2]={
				key,
				false,
				root[2],
			}
		end
	else
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			t[2]=root
			heap.root=t
		else
			heap.root={
				key,
				root,
				false,
			}
		end
	end
end

local function pop(heap)
	heap.Size=heap.Size-1
	local root=heap.root
	heap.root=twopassmerge(root[2])
	root[1]=false
	root[2]=false
	root[3]=false
	tSize=tSize+1
	tables[tSize]=root
end

local function join(heap1,heap2)
	-- assumes non empty heaps
	-- don't kill heap2 after merging

	local a=heap1.Size+heap2.Size
	heap1.Size=a
	local b=heap1.maxSize
	heap1.maxSize=(a>b and a)or b

	a=heap1.root
	b=heap2.root

	-- inlined merge
	if a[1]<b[1]then
		-- inlined add child
		b[3]=a[2]
		a[2]=b
	else
		-- inlined add child
		a[3]=b[2]
		b[2]=a

		heap1.root=b
	end

	return heap1
end

local function kill(heap)
	local nt=tSize-heap.maxSize+heap.Size
	for i=nt+1,tSize do
		tables[i]=nil
	end
	tSize=nt
end

local heap={
	empty=empty,
	top=top,
	push=push,
	pop=pop,
	join=join,
	kill=kill,
}

function heap.new(expectedspace)
	expectedspace=expectedspace or 0
	local nt=tSize+expectedspace
	for i=tSize+1,nt do
		tables[i]={false,false,false,}
	end
	tSize=nt

	return{
		empty=empty,
		top=top,
		push=push,
		pop=pop,
		join=join,
		kill=kill,

		Size=0,
		maxSize=expectedspace,
    }
end

----------

local n,m=io.read("n","n")
local a=heap.new(n)
for i=1,n do
    a:push(-io.read("n"))
end

for i=1,m do
    local x=-a:top()
    a:pop()
    a:push(-(x//2))
end

local total=0
for i=1,n do
    total=total-a:top()
    a:pop()
end
print(total)


--url : https://devforum.roblox.com/t/commonly-used-tree-data-structures-in-lua/265673/2

----------

--[[
	Pairing Min Heap

	Binary Heap is faster for increasing and random pushes but this is faster for joining (merging) and decreasing pushes
	It is very optimized

	Use Kill to GC after finished using

--]]

--[[
	Node: {
	Key,
	LeftChild,
	NextSibling,
	}

--]]

-- Constants

-- cached variables

-- local variables

local tables={}
local tSize=0

local function merge(a,b)
	if not a then
		return b
	elseif not b then
		return a
	elseif a[1]<b[1]then
		-- inlined add child
		b[3]=a[2]
		a[2]=b

		return a
	else
		-- inlined add child
		a[3]=b[2]
		b[2]=a

		return b
	end
end

local function twopassmerge(a)
	local b=a and a[3]
	if b then
		local newnode=b[3]

		a[3]=false
		b[3]=false

		return merge(merge(a,b),twopassmerge(newnode))
	else
		return a
	end
end

local function empty(heap)
	return not heap.root
end

local function top(heap)
	return heap.root[1]
end

local function push(heap,key)
	local root=heap.Size+1
	heap.Size=root
	local t=heap.maxSize
	heap.maxSize=(root>t and root)or t

	-- inlined merge (optimized for insert)
	root=heap.root
	if not root then
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			heap.root=t
		else
			heap.root={
				key,
				false,
				false,
			}
		end
	elseif root[1]<key then
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			t[3]=root[2]
			root[2]=t
		else
			root[2]={
				key,
				false,
				root[2],
			}
		end
	else
		if tSize>0 then
			t=tables[tSize]
			tables[tSize]=nil
			tSize=tSize-1
			t[1]=key
			t[2]=root
			heap.root=t
		else
			heap.root={
				key,
				root,
				false,
			}
		end
	end
end

local function pop(heap)
	heap.Size=heap.Size-1
	local root=heap.root
	heap.root=twopassmerge(root[2])
	root[1]=false
	root[2]=false
	root[3]=false
	tSize=tSize+1
	tables[tSize]=root
end

local function join(heap1,heap2)
	-- assumes non empty heaps
	-- don't kill heap2 after merging

	local a=heap1.Size+heap2.Size
	heap1.Size=a
	local b=heap1.maxSize
	heap1.maxSize=(a>b and a)or b

	a=heap1.root
	b=heap2.root

	-- inlined merge
	if a[1]<b[1]then
		-- inlined add child
		b[3]=a[2]
		a[2]=b
	else
		-- inlined add child
		a[3]=b[2]
		b[2]=a

		heap1.root=b
	end

	return heap1
end

local function kill(heap)
	local nt=tSize-heap.maxSize+heap.Size
	for i=nt+1,tSize do
		tables[i]=nil
	end
	tSize=nt
end

local heap={
	empty=empty,
	top=top,
	push=push,
	pop=pop,
	join=join,
	kill=kill,
}

function heap.new(expectedspace)
	expectedspace=expectedspace or 0
	local nt=tSize+expectedspace
	for i=tSize+1,nt do
		tables[i]={false,false,false,}
	end
	tSize=nt

	return{
		empty=empty,
		top=top,
		push=push,
		pop=pop,
		join=join,
		kill=kill,

		Size=0,
		maxSize=expectedspace,
    }
end

----------

local n,m=io.read("n","n")
local a=heap.new(n)
for i=1,n do
    a:push(io.read("n"))
end

for i=1,m do
    local x=a:top()
    a:pop()
    a:push(x//2)
end

local total=0
for i=1,n do
    total=total+a:top()
    a:pop()
end
print(total)

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

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000

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.


--url : https://devforum.roblox.com/t/commonly-used-tree-data-structures-in-lua/265673/5

--[[
	vEB (van Emde Boas Trees)

	This is slow because it recurses and calls functions. Because of this, it is recommended to use a Red-Black Binary Search Tree instead.

    u defines the desired upper bound, each node has u^0.5 children.
    You want u to be as close as possible to the maximum Value.

    You can insert negative numbers as well but it is a bit inefficient so it is better to offset all of the numbers by a constant beforehand.

	Sources:
		https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-design-and-analysis-of-algorithms-spring-2015/lecture-notes/MIT6_046JS15_lec04.pdf
		https://www.youtube.com/watch?v=hmReJCupbNU
		https://github.com/erikwaing/VEBTree

	Complexity:
		Min: O(1)
		Max: O(1)
		Member: O(lglg(u))
		Upper Bound: O(lglg(u))
		Lower Bound: O(lglg(u))
		Insertion: O(lglg(u))
		Deletion: O(lglg(u))

	Example Usage:
		local v = require(this).New(15)

		v:Insert(1)
		v:Insert(3)
		v:Insert(4)
		v:Insert(5)
		v:Insert(7)
		v:Insert(8)
		v:Insert(10)
		v:Insert(0)
		v:Insert(12)
		v:Insert(14)

		print(v:UpperBound(13))

		-- iterating
		local i = v.Min
		while i do
			print(i)
			i = v:Successor(i)
		end

--]]

-- Constants

-- efficiency variables
local error=error
local floor=math.floor

-- local variables

local function newveb(u)
	local self={
		u,-- u
		false,-- min
		false,-- max
		false,
		false,
		floor(u^.5),
	}

	if u>2 then
		local clusters={}
		for i=1,self[6]+1 do
			clusters[i]=false
		end

		self[4]=clusters-- clusters
		--self[5] = nil -- summary
	end

	return self
end

local function high(self,x)
	return floor(x/self[6])+1
end

local function low(self,x)
	return x%self[6]+1
end

local function index(self,h,l)
	return(h-1)*self[6]+l-1
end

local function member(self,x)
	-- returns whether x is a member of the vEB
	if x==self[2]or x==self[3]then
		-- found x as the min or max
		return true
	elseif self[1]<=2 then
		-- has not found x in the "leaf"
		return
	else
		local cluster=self[4][high(self,x)]
		if cluster then
			-- look for x in the cluster
			return member(cluster,low(self,x))
		end
	end
end

local function successor(self,x)
	local m=self[2]
	if self[1]<=2 then
		if x==0 and self[3]==1 then
			return 1
		end
	elseif m and x<m then
		-- x is less than everything in the tree, return the minimum
		return m
	else
		local h=high(self,x)
		local l=low(self,x)
		m=self[4]
		local cluster=m[h]
		local n=cluster and cluster[3]

		if n and l<n then
			return index(self,h,successor(cluster,l))
		else
			n=self[5]
			if n then
				n=successor(n,h)
				if n then
					local cluster2=m[n]
					if cluster2 then
						return index(self,n,cluster2[2])
					end
				end
			end
		end
	end
end

local function predecessor(self,x)
	local n=self[2]
	local m=self[3]
	if self[1]<=2 then
		if x==1 and n==0 then
			return 0
		end
	elseif m and x>m then
		return m
	else
		local h=high(self,x)
		local l=low(self,x)
		m=self[4]
		local cluster=m[h]
		local minlow=cluster and cluster[2]

		if minlow and l>minlow then
			return index(self,h,predecessor(cluster,l)or 0)
		else
			local predcluster=self[5]
			if predcluster then
				predcluster=predecessor(predcluster,h)
			end
			if predcluster then
				m=m[predcluster]
				return index(self,predcluster,(m and m[3])or 0)
			elseif n and x>n then
				return n
			end
		end
	end
end

local function insert(self,x)
	local m=self[2]
	if m then
		if x<m then
			-- swap x and min if x is less than min to *actually* insert min instead of x
			self[2]=x
			x=m
		end

		m=self[1]
		if m>2 then
			m=high(self,m)
			local h=high(self,x)
			local cluster=self[4][h]
			local summary=self[5]

			if not cluster then
				-- if the cluster doesn't exist then create it (save space by not having it exist) and set its bound to sqrt of u
				cluster=newveb(m)
				self[4][h]=cluster
			end
			if not summary then
				summary=newveb(m)
				self[5]=summary
			end
			if cluster[2]then
				insert(cluster,low(self,x))
			else
				insert(summary,h)
				local x=low(self,x)
				cluster[2]=x
				cluster[3]=x
			end
		end
		if x>self[3]then
			self[3]=x
		end
	else
		self[2]=x
		self[3]=x
	end
end

local function delete(self,x)
	local h
	local m=self[4]
	local p=self[5]

	if x==self[2]then
		h=p
		h=h and h[2]
		if not h then
			self[2]=nil
			self[3]=nil
			return
		end

		x=index(self,h,m[h][2])
		self[2]=x
	end

	local o=high(self,x)
	local n=m[o]
	delete(n,low(self,x))
	if not n[2]then
		delete(p,o)
		m[o]=false--nil -- delete it if its not being used
	end
	if x==self[3]then
		local h=p[3]
		self[3]=h and index(self,h,m[h][3])or self[2]
	end
end

local function vinsert(self,x)
	insert(self,x)
	self.min=self[2]
	self.max=self[3]
	self.Size=self.Size+1

	return self
end

local function vdelete(self,x)
	delete(self,x)
	self.min=self[2]
	self.max=self[3]
	self.Size=self.Size-1

	return self
end

local function vupperbound(self,x)
	return predecessor(self,x+1)
end

local function vlowerbound(self,x)
	return successor(self,x-1)
end

local function vclear(self)
	self[2]=false
	self[3]=false
	local a=self[4]
	if a then
		for i=1,#a do
			a[i]=false
		end
	end
	self[5]=false

	return self
end

local function vempty(self)
	return not self[1]
end

local veb={
	insert=vinsert,
	delete=vdelete,
	member=member,
	upperbound=vupperbound,
	lowerbound=vlowerbound,
	successor=successor,
	predecessor=predecessor,
	clear=vclear,
	empty=vempty,
}

function veb.new(u)
	if u<0 then
		error('Upper bound cannot be less than 0',2)
	end

	local self=newveb(u)

	self.Size=0
	self.max=false
	self.min=false
	self.u=u

	self.insert=vinsert
	self.delete=vdelete
	self.member=member
	self.upperbound=vupperbound
	self.lowerbound=vlowerbound
	self.clear=vclear
	self.empty=vempty
	self.successor=successor
	self.predecessor=predecessor

	return self
end

---------

local n,m=io.read("n","n")
local a=veb.new(n)
for i=1,n do
    local input=io.read("n")
    a:insert(input)
end

for i=1,m do
    x=a.max
    a:delete(x)
    x=x//2
    a:insert(x)
end

local total=0
for i=1,n do
    local x=a.max
    a:delete(x)
    total=total+x
end
print(total)


--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("*n","*n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("*n")
    a:put(-x,-x)
end
for i=1,m do
    x=a:pop()
    x=-x
    x=floor(x/2)
    a:put(-x,-x)
end

local total=0
for i=1,n do
    total=total-a:pop()
end
print(total)


--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("n","n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("n")
    a:put(-x,-x)
end
for i=1,m do
    x=a:pop()
    x=-x
    x=floor(x/2)
    a:put(-x,-x)
end

local total=0
for i=1,n do
    total=total-a:pop()
end
print(total)


--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("*n","*n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("*n")
    a:put(-x,-x)
end
for i=1,m do
    x=a:pop()
    x=-x
    x=floor(x/2)
    a:put(-x,-x)
end

local total=0
for i=1,n do
    total=total+a:pop()
end
print(-total)


--[[問題文
高橋くんは N個の品物を 1個ずつ順番に買う予定です。i番目に買う品物の値段は Ai円です。高橋くんは M枚の割引券を持っています。品物を買う際に割引券を好きな枚数使うことができます。X円の品物を買う際に Y 枚の割引券を使った場合、その品物を X/2^Y円(小数点以下切り捨て)で買うことができます。最小で何円あれば全ての品物を買うことができるでしょうか。

制約
入力は全て整数である。
1≤N,M≤10^5, 1≤Ai≤10^9]]

--M枚の商品券をいかに効率良く振り分けるか。つまり商品券1枚あたりの割引価格をどれだけ大きくできるか。
--当然のことだけど全部使い切ったほうがいい。
--最初の1枚は、自明に1番値段の高いものに使うべき。
--次は、1枚割引券を使った状態でもっとも高いものに使うべき。
--以下M枚使い切るまで行う。
--素直に実装するなら、一番大きな要素を割るたびにソートを行ってループするという感じ。
--これを以前c++で実装したけどtleになった。ソートの計算量いくらなんだろうね。
--一応同じような実装で出してみる。tlew

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

for i=1,m do
    table.sort(a)
    a[n]=a[n]//2
end

total=0
for i=1,n do
    total=total+a[i]
end
print(total)
]]

--2分探索使えないかな。
--1番大きいのを割ったらa[i]<=a[n]<=a[j]となる位置に移動させる
--うーん。移動ってのはどう実装したらいいだろう。結局ソートと変わらないってことにはならないかな
--一番大きいのを割っていく過程で、キーを記録しておいて、割ったあとに最大だった項とその次に大きな項で比較して、大小関係に応じてキーの記録を更新するというやりかたをさっきやったけどそれだと最大値でなくなった項が再び最大値になるパターンを取りこぼすから、記録の仕方を工夫しないといけない。
--キーじゃなくて値を配列に保存して、配列の最大値と比較するってのはどうだろう。
--実装がややこしくなりそうだし計算量も改善できるだろうか。。。
--あっ、無理かも。格納される項の最大値M=10^5だから計算量はM(M-1)/2に比例するはず。
--実装してみよう。

--[[
n,m=io.read("*n","*n","*l")
a={}
for i=1,n do
    a[i]=io.read("*n")
end
table.sort(a)
if n==1 then
    return print(string.format("%d",a[1]//(2^m)))
end

t={}
key=n
for i=1,m do
    a[key]=a[key]//2
    table.insert(t,{a[key],key})
    if #t>1 then
        table.sort(t,function(a,b)
            return a[1]<b[1]
        end)
    end
    if t[#t][1]<=a[key] then
        key=t[#t][2]
    else
        if key-1==0 then
            break
        else
            key=key-1
        end
    end
end

total=0
for i=1,n do
    total=total+a[i]
end
print(total)
]]

--TLEかつWAだった。テーブルをキーの取得にしか使ってなかったせいだと思う。値を消さないと。

--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("n","n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("n")
    a:put(-x,-x)
end
for i=1,m do
    x=a:pop()
    x=-x
    x=floor(x/2)
    a:put(-x,-x)
end

local total=0
for i=1,n do
    total=total+a:pop()
end
print(-total)


--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("n","n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("n")
    a:put(-x,-x)
end
for i=1,m do
    x=a:pop()
    x=-x
    x=x//2
    a:put(-x,-x)
end

local total=0
for i=1,n do
    total=total+a:pop()
end
print(-total)


n,m=io.read("*n","*n","*l")
a={}
for i=1,n do
    a[i]=io.read("*n")
end
table.sort(a)
if n==1 then
    return print(string.format("%d",a[1]//(2^m)))
end

t={}
key=n
for i=1,m do
    a[key]=a[key]//2
    table.insert(t,{a[key],key})
    if #t>1 then
        table.sort(t,function(a,b)
            return a[1]<b[1]
        end)
    end
    if t[#t][1]<=a[key] then
        key=t[#t][2]
    else
        if key-1==0 then
            break
        else
            key=key-1
        end
    end
end

total=0
for i=1,n do
    total=total+a[i]
end
print(total)


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

for i=1,m do
    table.sort(a)
    a[n]=a[n]//2
end
total=0
for i=1,n do
    total=total+a[i]
end
print(total)


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"
M=io.read"*n"
A=reada(N)

for j=1,M do
	maxv=A[1]
	maxi=1
	for i=2,N do
		if(maxv<A[i])then
			maxv=A[i]
			maxi=i
		end
	end
	A[maxi]=A[maxi]*.5
end

s=0
for i=1,N do s=s+math.floor(A[i])end
print(s)


local mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegForAvl = {}
SegForAvl.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.stage[i + 1][j * 2]
    end
  end
end
SegForAvl.create = function(self, n)
  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
  self.stage[stagenum][1] = false
  for i = 2, mul do self.stage[stagenum][i] = i end
  self:updateAll()
end
SegForAvl.hold = function(self)
  local idx = self.stage[1][1]
  local ridx = idx
  self.stage[self.stagenum][idx] = false
  for i = self.stagenum - 1, 1, -1 do
    local dst = mce(idx / 2)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.stage[i + 1][idx] or self.stage[i + 1][rem]
    idx = dst
  end
  return ridx
end
SegForAvl.release = function(self, idx)
  self.stage[self.stagenum][idx] = idx
  for i = self.stagenum - 1, 1, -1 do
    local dst = mce(idx / 2)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.stage[i + 1][idx] or self.stage[i + 1][rem]
    idx = dst
  end
end
SegForAvl.new = function(n)
  local obj = {}
  setmetatable(obj, {__index = SegForAvl})
  obj:create(n)
  return obj
end

local SegAvlTree = {}
SegAvlTree.makenode = function(self, val, parent)
  local i = self.seg:hold()
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
SegAvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.seg = SegForAvl.new(n + 1)
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

SegAvlTree.recalcCount = function(self, i)
  if 1 < i then
    if 1 < self.l[i] then self.lc[i] = 1 + mma(self.lc[self.l[i]], self.rc[self.l[i]])
    else self.lc[i] = 0
    end
    if 1 < self.r[i] then self.rc[i] = 1 + mma(self.lc[self.r[i]], self.rc[self.r[i]])
    else self.rc[i] = 0
    end
  end
end
SegAvlTree.recalcCountAll = function(self, i)
  while 1 < i do
    self:recalcCount(i)
    i = self.p[i]
  end
end

SegAvlTree.rotR = function(self, child, parent)
  local granp = self.p[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

SegAvlTree.rotL = function(self, child, parent)
  local granp = self.p[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

SegAvlTree.add = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  local added = false
  while not added do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        added = true
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        added = true
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalcCount(parent)
    if self.l[parent] == child then
      if self.lc[parent] - 1 == self.rc[parent] then
        pos = parent
      elseif self.lc[parent] - 2 == self.rc[parent] then
        self:recalcCount(child)
        if self.lc[child] - 1 == self.rc[child] then
          self:rotR(child, parent)
        else
          local cr = self.r[child]
          self:rotL(cr, child)
          self:rotR(cr, parent)
        end
        pos = 1
      else
        self:recalcCountAll(child)
        pos = 1
      end
    else -- parent.r == child
      if self.rc[parent] - 1 == self.lc[parent] then
        pos = parent
      elseif self.rc[parent] - 2 == self.lc[parent] then
        self:recalcCount(child)
        if self.rc[child] - 1 == self.lc[child] then
          self:rotL(child, parent)
        else
          local cl = self.l[child]
          self:rotR(cl, child)
          self:rotL(cl, parent)
        end
        pos = 1
      else
        self:recalcCountAll(child)
        pos = 1
      end
    end
  end
end

SegAvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalcCount(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcCountAll(self.p[node])
      node = 1
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(self.r[node], node)
        node = 1
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(nr, node)
        node = nr
      else
        local nrl = self.l[self.r[node]]
        self:rotR(nrl, self.r[node])
        self:rotL(nrl, node)
        node = nrl
      end
    end
  end
end

SegAvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  if 1 < self.p[node] then
    self.p[self.r[node]] = self.p[node]
    self.l[self.p[node]] = self.r[node]
    self:rmsub(self.p[node])
  else
    self.p[self.r[node]] = 1
    self.root = self.r[node]
  end
  self.seg:release(node)
  return v
end

SegAvlTree.new = function(lessthan, n)
    local obj = {}
    setmetatable(obj, {__index = SegAvlTree})
    obj:create(lessthan, n)
    return obj
end

local n, m = io.read("*n", "*n")
local avl = SegAvlTree.new(function(a, b) return a < b end, n)
for i = 1, n do
  local a = io.read("*n")
  avl:add(-a)
end
for i = 1, m do
  local v = avl:pop()
  avl:add(-mfl(-v / 2))
end
local ret = 0

local tasks = {avl.root}
local done = 0
while done < #tasks do
  done = done + 1
  local node = tasks[done]
  ret = ret - avl.v[node]
  if 1 < avl.l[node] then table.insert(tasks, avl.l[node]) end
  if 1 < avl.r[node] then table.insert(tasks, avl.r[node]) end
end
print(ret)


local floor = math.floor
-- heap
local function Heap(upper_func)
    local floor = math.floor
    local a = {}
    local upper = function(k1, k2)
        --assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(a[k1], a[k2])
        end
    end

    local lower = function(k1, k2)
        return not upper(k1, k2)
    end

    local function count()
        return #a
    end

    local function _swap(k1, k2)
        local old_k1 = a[k1]
        a[k1] = a[k2]
        a[k2] = old_k1
    end

    local function upheap(newk)
        local ku = floor(newk / 2)
        local k = newk
        while ku > 0 and lower(ku, k) do
            _swap(ku, k)
            k = floor(k/2)
            ku = floor(ku/2)
        end
    end

    local insert = table.insert
    local function insertq(e)
        insert(a, e)
        upheap(#a)
    end

    local function downheap(newk)
        local k = newk
        while k <= floor(#a/2) do
            local kdl = k*2
            local kdr = kdl + 1
            local kd
            if kdr <= #a and lower(kdl, kdr) then
                kd = kdr
            else
                kd = kdl
            end
            if upper(k, kd) then
                break
            end
            _swap(k, kd)
            k = kd
        end
    end

    local function top()
        --assert(#a >= 1)
        return a[1]
    end

    local remove = table.remove
    local function remove_top()
        --assert(#a >= 1)
        local v = a[1]
        _swap(1, #a)
        remove(a)
        downheap(1)
        return v
    end

    local self = {}
    self.count = count
    self.insertq = insertq
    self.top = top
    self.remove_top = remove_top
    return self
end

---
local N, M = io.read("*n", "*n")
local q = Heap(function (x,y) return x > y end)
local insertq = q.insertq
local remove_top = q.remove_top
for i=1,N do
    insertq(io.read("*n"))
end
for i=1,M do
    local top = remove_top()
    top = top / 2
    insertq(top)
end
local sum = 0
for i=1,N do
    local top = remove_top()
    sum = sum + floor(top)
end
print(sum)


local floor = math.floor
-- heap
local function Heap(upper_func)
    local floor = math.floor
    local a = {}
    local upper = function(k1, k2)
        --assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(a[k1], a[k2])
        end
    end

    local lower = function(k1, k2)
        return not upper(k1, k2)
    end

    local function count()
        return #a
    end

    local function _swap(k1, k2)
        local old_k1 = a[k1]
        a[k1] = a[k2]
        a[k2] = old_k1
    end

    local function upheap(newk)
        local ku = floor(newk / 2)
        local k = newk
        while ku > 0 and lower(ku, k) do
            _swap(ku, k)
            k = floor(k/2)
            ku = floor(ku/2)
        end
    end

    local insert = table.insert
    local function insertq(e)
        insert(a, e)
        upheap(#a)
    end

    local function downheap(newk)
        local k = newk
        while k <= floor(#a/2) do
            local kdl = k*2
            local kdr = kdl + 1
            local kd
            if kdr <= #a and lower(kdl, kdr) then
                kd = kdr
            else
                kd = kdl
            end
            if upper(k, kd) then
                break
            end
            _swap(k, kd)
            k = kd
        end
    end

    local function top()
        --assert(#a >= 1)
        return a[1]
    end

    local remove = table.remove
    local function remove_top()
        --assert(#a >= 1)
        local v = a[1]
        _swap(1, #a)
        remove(a)
        downheap(1)
        return v
    end

    local self = {}
    self.count = count
    self.insertq = insertq
    self.top = top
    self.remove_top = remove_top
    self.a = a
    return self
end

---
local N, M = io.read("*n", "*n")
local q = Heap(function (x,y) return x > y end)
local insertq = q.insertq
local remove_top = q.remove_top
for i=1,N do
    insertq(io.read("*n"))
end
for i=1,M do
    local top = remove_top()
    top = top / 2
    insertq(top)
end
local sum = 0
local a = q.a
for i=1,N do
    sum = sum + floor(a[i])
end
print(sum)


local floor = math.floor
-- heap
local Heap = {}
function Heap.new(upper_func)
    local self = setmetatable({}, {__index = Heap})
    self.a = {}
    self.upper_func = upper_func
    self.upper = function(k1, k2)
        assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(self.a[k1], self.a[k2])
        end
    end
    self.lower = function(k1, k2)
        return not self.upper(k1, k2)
    end
    return self
end

function Heap:count()
    return #self.a
end

function Heap:_swap(k1, k2)
    local old_k1 = self.a[k1]
    self.a[k1] = self.a[k2]
    self.a[k2] = old_k1
end

function Heap:upheap(newk)
    local ku = floor(newk / 2)
    local k = newk
    while ku > 0 and self.lower(ku, k) do
        self:_swap(ku, k)
        k = floor(k/2)
        ku = floor(ku/2)
    end
end

function Heap:insertq(e)
    table.insert(self.a, e)
    self:upheap(#self.a)
end

function Heap:downheap(newk)
    local k = newk
    while k <= floor(#self.a/2) do
        local kdl = k*2
        local kdr = kdl + 1
        local kd
        if kdr <= #self.a and self.lower(kdl, kdr) then
            kd = kdr
        else
            kd = kdl
        end
        if self.upper(k, kd) then
            break
        end
        self:_swap(k, kd)
        k = kd
    end
end

function Heap:top()
    assert(#self.a >= 1)
    return self.a[1]
end

function Heap:remove_top()
    assert(#self.a >= 1)
    local v = self.a[1]
    self:_swap(1, #self.a)
    table.remove(self.a)
    self:downheap(1)
    return v
end

---
local N, M = io.read("*n", "*n")
local q = Heap.new(function (x,y) return x > y end)
for i=1,N do
    q:insertq(io.read("*n"))
end
for i=1,M do
    local top = q:remove_top()
    top = top / 2
    q:insertq(top)
end
local sum = 0

for i=1,N do
    local top = q:remove_top()
    sum = sum + floor(top)
end
print(sum)


local floor = math.floor
-- heap
local Heap = {}
function Heap.new(upper_func)
    local self = setmetatable({}, {__index = Heap})
    self.a = {}
    self.upper_func = upper_func
    self.upper = function(k1, k2)
        assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(self.a[k1], self.a[k2])
        end
    end
    self.lower = function(k1, k2)
        return not self.upper(k1, k2)
    end
    return self
end

function Heap:count()
    return #self.a
end

function Heap:_swap(k1, k2)
    local old_k1 = self.a[k1]
    self.a[k1] = self.a[k2]
    self.a[k2] = old_k1
end

function Heap:upheap(newk)
    local ku = floor(newk / 2)
    local k = newk
    while ku > 0 and self.lower(ku, k) do
        self:_swap(ku, k)
        k = floor(k/2)
        ku = floor(ku/2)
    end
end

function Heap:insertq(e)
    table.insert(self.a, e)
    self:upheap(#self.a)
end

function Heap:downheap(newk)
    local k = newk
    while k <= floor(#self.a/2) do
        local kdl = k*2
        local kdr = kdl + 1
        local kd
        if kdr <= #self.a and self.lower(kdl, kdr) then
            kd = kdr
        else
            kd = kdl
        end
        if self.upper(k, kd) then
            break
        end
        self:_swap(k, kd)
        k = kd
    end
end

function Heap:top()
    assert(#self.a >= 1)
    return self.a[1]
end

function Heap:remove_top()
    assert(#self.a >= 1)
    local v = self.a[1]
    self:_swap(1, #self.a)
    table.remove(self.a)
    self:downheap(1)
    return v
end

---
local N, M = io.read("n", "n")
local q = Heap.new(function (x,y) return x > y end)
for i=1,N do
    q:insertq(io.read("n"))
end
for i=1,M do
    local top = q:remove_top()
    top = top / 2
    q:insertq(top)
end
local sum = 0

for i=1,N do
    local top = q:remove_top()
    sum = sum + floor(top)
end
print(sum)


-- heap
local Heap = {}
function Heap.new(upper_func)
    local self = setmetatable({}, {__index = Heap})
    self.a = {}
    self.upper_func = upper_func
    self.upper = function(k1, k2)
        assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(self.a[k1], self.a[k2])
        end
    end
    self.lower = function(k1, k2)
        return not self.upper(k1, k2)
    end
    return self
end

function Heap:count()
    return #self.a
end

function Heap:_swap(k1, k2)
    local old_k1 = self.a[k1]
    self.a[k1] = self.a[k2]
    self.a[k2] = old_k1
end

function Heap:upheap(newk)
    local ku = newk // 2
    local k = newk
    while ku > 0 and self.lower(ku, k) do
        self:_swap(ku, k)
        k = k//2
        ku = ku//2
    end
end

function Heap:insertq(e)
    table.insert(self.a, e)
    self:upheap(#self.a)
end

function Heap:downheap(newk)
    local k = newk
    while k <= #self.a//2 do
        local kdl = k*2
        local kdr = kdl + 1
        local kd
        if kdr <= #self.a and self.lower(kdl, kdr) then
            kd = kdr
        else
            kd = kdl
        end
        if self.upper(k, kd) then
            break
        end
        self:_swap(k, kd)
        k = kd
    end
end

function Heap:top()
    assert(#self.a >= 1)
    return self.a[1]
end

function Heap:remove_top()
    assert(#self.a >= 1)
    local v = self.a[1]
    self:_swap(1, #self.a)
    table.remove(self.a)
    self:downheap(1)
    return v
end
---
local N, M = io.read("n", "n")
local q = Heap.new(function (x,y) return x > y end)
for i=1,N do
    q:insertq(io.read("n"))
end
for i=1,M do
    local top = q:remove_top()
    top = top / 2
    q:insertq(top)
end
local sum = 0
for i=1,N do
    local top = q:remove_top()
    sum = sum + math.floor(top)
end
print(sum)


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, ary, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < #ary 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
  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.recalc = function(self, idx)
  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
SegTree.new = function(ary, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(ary, func, emptyvalue)
  return obj
end

local n, m = io.read("*n", "*n")
local t = {}
local c = {}
for i = 1, n do
  t[i] = io.read("*n")
  c[i] = 1
end
local tary = {}
for i = 1, n do tary[i] = i end
local st = SegTree.new(tary, function(x, y)
  if x == 0 then
    return y
  elseif y == 0 then
    return x
  else
    if t[x] * c[y] < t[y] * c[x] then
      return y
    else
      return x
    end
  end
end, 0)

for i = 1, m do
  local top = st.stage[1][1]
  c[top] = c[top] * 2
  st:recalc(top)
end
local ret = 0
for i = 1, n do
  ret = ret + mfl(t[i] / c[i])
end
print(ret)


local mmi, mma = math.min, math.max
local TranSufA = {}
TranSufA.makeSufA = function(self)
  self.sufa = {}
  local n = #self.str
  local idx, tbl1, tbl2 = self.sufa, {}, {}
  local tmp_tbl = {}
  for i = 1, n do
    idx[i] = i
    tbl1[i] = self.str:sub(i, i):byte() - 95 -- "a" = 97
    tbl2[i] = 0
    tmp_tbl[i] = 0
  end
  idx[n + 1], tbl1[n + 1], tbl2[n + 1] = n + 1, 1, 0
  n = n + 1 -- add empty to last
  table.sort(idx, function(a, b) return tbl1[a] < tbl1[b] end)
  local step, stepflag = 1, true
  while step < n do
    local v = stepflag and tbl1 or tbl2
    local vd = stepflag and tbl2 or tbl1
    stepflag = not stepflag
    local stepdst = {}
    for i = 1, n do
      local dst = i + step
      if n < dst then dst = dst - n end
      stepdst[i] = dst
    end
    local left, major = 1, v[idx[1]]
    local minor_min = v[stepdst[idx[1]]]
    local minor_max = minor_min
    local minormap = {}
    local cur = 0
    for i = 1, n do
      local minor = v[stepdst[idx[i]]]
      if minormap[minor] then minormap[minor] = minormap[minor] + 1
      else minormap[minor] = 1
      end
      minor_min, minor_max = mmi(minor_min, minor), mma(minor_max, minor)
      local isend = i == n or major ~= v[idx[i + 1]]
      if isend then
        local right = i
        if left == right then
          cur = cur + 1
          vd[idx[left]] = cur
        elseif minor_min ~= minor_max then
          local minortbl = {}
          for k, _u in pairs(minormap) do table.insert(minortbl, k) end
          table.sort(minortbl)
          local offset = 0
          for i = 1, #minortbl do
            local cnt = minormap[minortbl[i]]
            minormap[minortbl[i]] = i
            minortbl[i] = offset -- reuse
            offset = offset + cnt
          end
          -- local t = {}
          -- for j = left, right do
          --   tmp_tbl[j - left + 1] = 0
          -- end
          for j = left, right do
            local idxj = idx[j]
            local minor_idx = minormap[v[stepdst[idxj]]]
            local ofst = minortbl[minor_idx]
            ofst = ofst + 1
            minortbl[minor_idx] = ofst
            tmp_tbl[ofst] = idxj
            vd[idxj] = cur + minor_idx
          end
          cur = cur + #minortbl
          for j = left, right do
            idx[j] = tmp_tbl[j - left + 1]
          end
        else
          cur = cur + 1
          for j = left, right do
            vd[idx[j]] = cur
          end
        end
        if i < n then
          left, major = i + 1, v[idx[i + 1]]
          minor_min = v[stepdst[idx[i + 1]]]
          minor_max = minor_min
          minormap = {}
        end
      end
    end
    step = step * 2
  end
  -- remove empty from first (O(N))
  table.remove(self.sufa, 1)
  n = n - 1
  self.sufa_inv = {}
  for i = 1, n do self.sufa_inv[i] = 0 end
  for i = 1, n do
    self.sufa_inv[self.sufa[i]] = i
  end
end
TranSufA.makeLCPA = function(self)
  assert(self.sufa)
  local n = #self.sufa
  self.lcpa = {}
  local str, sufa, lcpa = self.str, self.sufa, self.lcpa
  for i = 1, n - 1 do lcpa[i] = 0 end
  local spos = 0
  for i = 1, n do
    local lcppos = self.sufa_inv[i]
    if lcppos < n then
      local len = spos
      local p1, p2 = sufa[lcppos], sufa[lcppos + 1]
      p1, p2 = p1 + spos, p2 + spos
      while p1 <= n and p2 <= n do
        if str:sub(p1, p1) == str:sub(p2, p2) then
          len = len + 1
          p1, p2 = p1 + 1, p2 + 1
        else break
        end
      end
      lcpa[lcppos] = len
      spos = mma(0, len - 1)
    end
  end
end

TranSufA.create = function(self, str)
  self.str = str
  self:makeSufA()
  self:makeLCPA()
end

TranSufA.new = function(str)
  local obj = {}
  setmetatable(obj, {__index = TranSufA})
  obj:create(str)
  return obj
end

local n = io.read("*n", "*l")
local s = io.read()
local sa = TranSufA.new(s)
sa:makeLCPA()
-- print(table.concat(sa.sufa, " "))
-- print(table.concat(sa.sufa_inv, " "))
-- print(table.concat(sa.lcpa, " "))

local sufa, sufa_inv, lcpa = sa.sufa, sa.sufa_inv, sa.lcpa
local ret = 0
for i = 1, n - 1 do
  local len = lcpa[i]
  local cand = len
  local p1, p2 = sufa[i], sufa[i + 1]
  if p1 < p2 then
    ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
  else
    ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
  end
  for j = i + 1, n - 1 do
    p2 = sufa[j + 1]
    len = mmi(len, lcpa[j])
    if p1 < p2 then
      ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
    else
      ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
    end
  end
end
print(ret)

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

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

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


local mmi, mma = math.min, math.max
local TranSufA = {}
TranSufA.makeSufA = function(self)
  self.sufa = {}
  local n = #self.str
  local idx, tbl1, tbl2 = self.sufa, {}, {}
  for i = 1, n do
    idx[i] = i
    tbl1[i] = self.str:sub(i, i):byte() - 95 -- "a" = 97
    tbl2[i] = 0
  end
  idx[n + 1], tbl1[n + 1], tbl2[n + 1] = n + 1, 1, 0
  n = n + 1 -- add empty to last
  table.sort(idx, function(a, b) return tbl1[a] < tbl1[b] end)
  local step, stepflag = 1, true
  while step < n do
    local v = stepflag and tbl1 or tbl2
    local vd = stepflag and tbl2 or tbl1
    -- print("A", table.concat(idx, " "))
    -- print("V", table.concat(v, " "))
    -- print("VD", table.concat(vd, " "))
    stepflag = not stepflag
    local stepdst = {}
    for i = 1, n do
      local dst = i + step
      if n < dst then dst = dst - n end
      stepdst[i] = dst
    end
    local left, major = 1, v[idx[1]]
    local minor_min = v[stepdst[idx[1]]]
    local minor_max = minor_min
    local minormap = {}
    local cur = 0
    for i = 1, n do
      local minor = v[stepdst[idx[i]]]
      if minormap[minor] then minormap[minor] = minormap[minor] + 1
      else minormap[minor] = 1
      end
      minor_min, minor_max = mmi(minor_min, minor), mma(minor_max, minor)
      local isend = i == n or major ~= v[idx[i + 1]]
      if isend then
        local right = i
        if left == right then
          cur = cur + 1
          vd[idx[left]] = cur
        elseif minor_min ~= minor_max then
          --
          local minortbl = {}
          for k, _u in pairs(minormap) do table.insert(minortbl, k) end
          table.sort(minortbl)
          local offset = 0
          for i = 1, #minortbl do
            local tmp = minormap[minortbl[i]]
            minormap[minortbl[i]] = i
            minortbl[i] = offset -- reuse
            offset = offset + tmp
          end
          local t = {}
          for j = left, right do
            t[j - left + 1] = 0
          end
          for j = left, right do
            local idxj = idx[j]
            local minor_idx = minormap[v[stepdst[idxj]]]
            local ofst = minortbl[minor_idx]
            ofst = ofst + 1
            minortbl[minor_idx] = ofst
            t[ofst] = idxj
            vd[idxj] = cur + minor_idx
          end
          cur = cur + #minortbl
          for j = left, right do
            idx[j] = t[j - left + 1]
          end
          -- local t = {}
          -- for j = left, right do
          --   t[j - left + 1] = idx[j]
          -- end
          -- print("Sort", #t)
          -- table.sort(t, function(x, y) return v[stepdst[x]] < v[stepdst[y]] end)
          -- local v_prv = 0
          -- for j = left, right do
          --   idx[j] = t[j - left + 1]
          --   local v_nxt = v[stepdst[idx[j]]]
          --   if j == left or v_nxt ~= v_prv then
          --     cur = cur + 1
          --   end
          --   vd[idx[j]] = cur
          --   v_prv = v_nxt
          -- end
        else
          cur = cur + 1
          for j = left, right do
            vd[idx[j]] = cur
          end
        end
        if i < n then
          left, major = i + 1, v[idx[i + 1]]
          minor_min = v[stepdst[idx[i + 1]]]
          minor_max = minor_min
          minormap = {}
        end
      end
    end
    step = step * 2
  end
  -- remove empty from first (O(N))
  table.remove(self.sufa, 1)
  n = n - 1
  self.sufa_inv = {}
  for i = 1, n do self.sufa_inv[i] = 0 end
  for i = 1, n do
    self.sufa_inv[self.sufa[i]] = i
  end
end
TranSufA.makeLCPA = function(self)
  assert(self.sufa)
  local n = #self.sufa
  self.lcpa = {}
  local str, sufa, lcpa = self.str, self.sufa, self.lcpa
  for i = 1, n - 1 do lcpa[i] = 0 end
  local spos = 0
  for i = 1, n do
    local lcppos = self.sufa_inv[i]
    if lcppos < n then
      local len = spos
      local p1, p2 = sufa[lcppos], sufa[lcppos + 1]
      p1, p2 = p1 + spos, p2 + spos
      while p1 <= n and p2 <= n do
        if str:sub(p1, p1) == str:sub(p2, p2) then
          len = len + 1
          p1, p2 = p1 + 1, p2 + 1
        else break
        end
      end
      lcpa[lcppos] = len
      spos = mma(0, len - 1)
    end
  end
end

TranSufA.create = function(self, str)
  self.str = str
  self:makeSufA()
  self:makeLCPA()
end

TranSufA.new = function(str)
  local obj = {}
  setmetatable(obj, {__index = TranSufA})
  obj:create(str)
  return obj
end

local n = io.read("*n", "*l")
local s = io.read()
local sa = TranSufA.new(s)
sa:makeLCPA()
-- print(table.concat(sa.sufa, " "))
-- print(table.concat(sa.sufa_inv, " "))
-- print(table.concat(sa.lcpa, " "))

local sufa, sufa_inv, lcpa = sa.sufa, sa.sufa_inv, sa.lcpa
local ret = 0
for i = 1, n - 1 do
  local len = lcpa[i]
  local cand = len
  local p1, p2 = sufa[i], sufa[i + 1]
  if p1 < p2 then
    ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
  else
    ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
  end
  for j = i + 1, n - 1 do
    p2 = sufa[j + 1]
    len = mmi(len, lcpa[j])
    if p1 < p2 then
      ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
    else
      ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
    end
  end
end
print(ret)


local mmi, mma = math.min, math.max
local TranSufA = {}
TranSufA.makeSufA = function(self, str)
  self.sufa = {}
  local n = #str
  local idx, tbl1, tbl2 = self.sufa, {}, {}
  for i = 1, n do
    idx[i] = i
    tbl1[i] = str:sub(i, i):byte() - 95 -- "a" = 97
    tbl2[i] = 0
  end
  idx[n + 1], tbl1[n + 1], tbl2[n + 1] = n + 1, 1, 0
  n = n + 1 -- add empty to last
  table.sort(idx, function(a, b) return tbl1[a] < tbl1[b] end)
  local step, stepflag = 1, true
  while step < n do
    local v = stepflag and tbl1 or tbl2
    local vd = stepflag and tbl2 or tbl1
    stepflag = not stepflag
    local stepdst = {}
    for i = 1, n do
      local dst = i + step
      if n < dst then dst = dst - n end
      stepdst[i] = dst
    end
    local left, major = 1, v[idx[1]]
    local minor_min = v[stepdst[idx[1]]]
    local minor_max = minor_min
    local cur = 0
    for i = 1, n do
      local minor = v[stepdst[idx[i]]]
      minor_min, minor_max = mmi(minor_min, minor), mma(minor_max, minor)
      local isend = i == n or major ~= v[idx[i + 1]]
      if isend then
        local right = i
        if left == right then
          cur = cur + 1
          vd[idx[left]] = cur
        elseif minor_min ~= minor_max then
          local t = {}
          for j = left, right do
            t[j - left + 1] = idx[j]
          end
          table.sort(t, function(x, y) return v[stepdst[x]] < v[stepdst[y]] end)
          local v_prv = 0
          for j = left, right do
            idx[j] = t[j - left + 1]
            local v_nxt = v[stepdst[idx[j]]]
            if j == left or v_nxt ~= v_prv then
              cur = cur + 1
            end
            vd[idx[j]] = cur
            v_prv = v_nxt
          end
        else
          cur = cur + 1
          for j = left, right do
            vd[idx[j]] = cur
          end
        end
        if i < n then
          left, major = i + 1, v[idx[i + 1]]
          minor_min = v[stepdst[idx[i + 1]]]
          minor_max = minor_min
        end
      end
    end
    step = step * 2
  end
  -- remove empty from first (O(N))
  table.remove(self.sufa, 1)
  n = n - 1
  self.sufa_inv = {}
  for i = 1, n do self.sufa_inv[i] = 0 end
  for i = 1, n do
    self.sufa_inv[self.sufa[i]] = i
  end
end
TranSufA.makeLCPA = function(self)
  assert(self.sufa)
  local n = #self.sufa
  self.lcpa = {}
  local str, sufa, lcpa = self.str, self.sufa, self.lcpa
  for i = 1, n - 1 do lcpa[i] = 0 end
  local spos = 0
  for i = 1, n do
    local lcppos = self.sufa_inv[i]
    if lcppos < n then
      local len = spos
      local p1, p2 = sufa[lcppos], sufa[lcppos + 1]
      p1, p2 = p1 + spos, p2 + spos
      while p1 <= n and p2 <= n do
        if str:sub(p1, p1) == str:sub(p2, p2) then
          len = len + 1
          p1, p2 = p1 + 1, p2 + 1
        else break
        end
      end
      lcpa[lcppos] = len
      spos = mma(0, len - 1)
    end
  end
end

TranSufA.create = function(self, str)
  self.str = str
  self:makeSufA(str)
end

TranSufA.new = function(str)
  local obj = {}
  setmetatable(obj, {__index = TranSufA})
  obj:create(str)
  return obj
end

-- sample
local n = io.read("*n", "*l")
local s = io.read()
local sa = TranSufA.new(s)
sa:makeLCPA()
-- print(table.concat(sa.sufa, " "))
-- print(table.concat(sa.sufa_inv, " "))
-- print(table.concat(sa.lcpa, " "))

local sufa, sufa_inv, lcpa = sa.sufa, sa.sufa_inv, sa.lcpa
local ret = 0
for i = 1, n - 1 do
  local len = lcpa[i]
  local cand = len
  local p1, p2 = sufa[i], sufa[i + 1]
  if p1 < p2 then
    ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
  else
    ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
  end
  for j = i + 1, n - 1 do
    p2 = sufa[j + 1]
    len = mmi(len, lcpa[j])
    if p1 < p2 then
      ret = mma(ret, mmi(len, p2 - p1, n + 1 - p2))
    else
      ret = mma(ret, mmi(len, p1 - p2, n + 1 - p1))
    end
  end
end
print(ret)


local mmi, mma, mab = math.min, math.max, math.abs
local n = io.read("*n", "*l")
local s = io.read()
local sa = {}
for i = 1, n do
  table.insert(sa, {i, s:sub(i, n)})
end
table.sort(sa, function(x, y) return x[2] < y[2] end)
local lcpa = {}
for i = 1, n - 1 do
  local len = mmi(#sa[i][2], #sa[i + 1][2])
  local c = 0
  for j = 1, len do
    if sa[i][2]:sub(j, j) == sa[i + 1][2]:sub(j, j) then
      c = c + 1
    else break end
  end
  lcpa[i] = c
end
local ret = 0
for i = 1, n - 1 do
  local prv = lcpa[i]
  for j = i, n - 1 do
    local nxt = lcpa[j]
    if nxt == 0 then
      break
    else
      prv = mmi(prv, nxt)
      ret = mma(ret, mmi(prv, mab(sa[j + 1][1] - sa[i][1])))
    end
  end
end
print(ret)


local mfl, mce, mmi, mma = math.floor, math.ceil, math.min, math.max
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, 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 = io.read("*n", "*l")
local s = io.read()
local sa = {}
for i = 1, n do
  table.insert(sa, {i, s:sub(i, n)})
end
table.sort(sa, function(x, y) return x[2] < y[2] end)

local sa_inv = {}
for i = 1, n do sa_inv[i] = 0 end
for i = 1, n do sa_inv[sa[i][1]] = i end

local lcpaSeg = SegTree.new(n - 1, mmi, 0)
local lcpa = {}
for i = 1, n - 1 do
  local len = mmi(#sa[i][2], #sa[i + 1][2])
  local c = 0
  for j = 1, len do
    if sa[i][2]:sub(j, j) == sa[i + 1][2]:sub(j, j) then
      c = c + 1
    else break end
  end
  lcpaSeg:setValue(i, c, true)
end
lcpaSeg:updateAll()
local function getLcpLength(pos1, pos2)
  local sapos1, sapos2 = sa_inv[pos1], sa_inv[pos2]
  if sapos1 == sapos2 then
    return #sa[sapos1][2]
  elseif sapos2 < sapos1 then
    sapos1, sapos2 = sapos2, sapos1
  end
  return lcpaSeg:getRange(sapos1, sapos2 - 1)
end
local ret = 0
for i = 1, n - 1 do
  for j = i + 1, n do
    ret = mma(ret, mmi(getLcpLength(i, j), j - i))
  end
end
print(ret)


local mmi, mma = math.min, math.max
local n = io.read("*n", "*l")
local s = io.read()
local sa = {}
for i = 1, n do
  table.insert(sa, {i, s:sub(i, n)})
end
table.sort(sa, function(x, y) return x[2] < y[2] end)
local lcpa = {}
for i = 1, n do
  lcpa[i] = {}
  for j = 1, n do
    lcpa[i][j] = 0
  end
end
for i = 1, n - 1 do
  local len = mmi(#sa[i][2], #sa[i + 1][2])
  local c = 0
  for j = 1, len do
    if sa[i][2]:sub(j, j) == sa[i + 1][2]:sub(j, j) then
      c = c + 1
    else break end
  end
  local i1, i2 = sa[i][1], sa[i + 1][1]
  lcpa[i1][i2], lcpa[i2][i1] = c, c
end
for i = 1, n - 2 do
  local prv = lcpa[sa[i][1]][sa[i + 1][1]]
  if 0 < prv then
    for j = i + 1, n - 1 do
      local nxt = lcpa[sa[j][1]][sa[j + 1][1]]
      if nxt == 0 then
        break
      else
        prv = mmi(prv, nxt)
        lcpa[sa[i][1]][sa[j + 1][1]], lcpa[sa[j + 1][1]][sa[i][1]] = prv, prv
      end
    end
  end
end
local ret = 0
for i = 1, n - 1 do
  for j = i + 1, n do
    ret = mma(ret, mmi(lcpa[i][j], j - i))
  end
end
print(ret)


local n = io.read("*n", "*l")
local s = io.read()
local sa = {}
for i = 1, n do
  table.insert(sa, {i, s:sub(i, n)})
end
table.sort(sa, function(x, y) return x[2] < y[2] end)
local lcpa = {}
for i = 1, n do
  lcpa[i] = {}
  for j = 1, n do
    lcpa[i][j] = 0
  end
end
local mmi, mma = math.min, math.max
for i = 1, n - 1 do
  local len = mmi(#sa[i][2], #sa[i + 1][2])
  local c = 0
  for j = 1, len do
    if sa[i][2]:sub(j, j) == sa[i + 1][2]:sub(j, j) then
      c = c + 1
    else break end
  end
  local i1, i2 = sa[i][1], sa[i + 1][1]
  lcpa[i1][i2], lcpa[i2][i1] = c, c
end
for i = 1, n - 2 do
  local prv = lcpa[sa[i][1]][sa[i + 1][1]]
  if 0 < prv then
    for j = i + 1, n - 1 do
      local nxt = lcpa[sa[j][1]][sa[j + 1][1]]
      if nxt == 0 then
        break
      else
        prv = mmi(prv, nxt)
        lcpa[sa[i][1]][sa[j + 1][1]], lcpa[sa[j + 1][1]][sa[i][1]] = prv, prv
      end
    end
  end
end
local ret = 0
for i = 1, n - 1 do
  for j = i + 1, n do
    ret = mma(ret, mmi(j - i, lcpa[i][j]))
  end
end
print(ret)


local n = io.read("*n", "*l")
local s = io.read()
local bt = {}
local mma, mmi = math.max, math.min
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end
local ret = 0
for i = 1, n do
  local cnt = 0
  for j = 1, n - i do
    if bt[j] == bt[j + i] then
      cnt = cnt + 1
    else
      cnt = 0
    end
    ret = mma(ret, mmi(i, cnt))
  end
end
print(ret)


local n = io.read("*n", "*l")
local s = io.read()
local bt = {}
local mma, mmi = math.max, math.min
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end
local ret = 0
for i = 1, n do
  local cnt = 0
  for j = 1, n - i do
    if bt[j] == bt[j + i] then
      cnt = cnt + 1
    else
      cnt = 0
    end
    print(i, j, ret, cnt)
    ret = mma(ret, mmi(i, cnt))
  end
end
print(ret)


local floor = math.floor
-- binary search
-- https://golang.org/src/sort/search.go?s=2246:2286#L49
local function find_min_true(n, f)
    local function loop(i, j)
        if i == j then
            return i
        end
        local h = floor((i + j) / 2)
        if f(h) then
            return loop(i, h)
        else
            return loop(h + 1, j)
        end
    end
    return loop(1, n + 1)
end

local N = io.read("*n", "*l")
local S = io.read("*l")
local sub = string.sub
local find = string.find
local function search()
    -- false if len is OK
    local function judge(len)
        for l1=1,N+1-2*len do
            local subst = sub(S, l1, l1+len-1)
            local result = find(S, subst, l1+len, true)
            --print("len", len, "l1", l1, "subst", subst, "result", result)
            if result then
                return false
            end
        end
        return true -- len is NG
    end
    return find_min_true(2500, judge)
end
local ans = search()
if ans == 0 then
    print(0)
else
    print(ans-1)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false
local bt = {}
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end

local thash = {}
if 6 <= n then
  thash[1]
    = bt[1]
    + bt[2] * 30
    + bt[3] * 900
    + bt[4] * 27000
    + bt[5] * 810000
    + bt[6] * 24300000
  for k = 2, n - 5 do
    thash[k] = mfl(thash[k - 1] / 30) + bt[k + 5] * 24300000
  end
end

local function solve(len)
  if 6 <= len then
    local hlen = mfl(len / 2)
    local map = {}
    local tmplen = len
    local hash = {}
    local tmap = {}
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    local taskpos = n - len + 1
    for pos = n - len, len, -1 do
      hash[thash[pos + len - 5]] = true
      if hash[thash[pos - 5]] then
        for tmp = pos + 1, taskpos do
          map[tmap[tmp]] = true
        end
        taskpos = pos
        if map[tmap[pos + 1 - len]] then
          return true
        end
      end
    end
  else
    local map = {}
    local tmap = {}
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      if map[tmap[pos + 1 - len]] then
        return true
      end
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  local nextnt = false
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if nextnt and 8 < lmax - lmin then
      len = mfl((lmax + 7 * lmin) / 8)
      nextnt = false
    end
    if solve(len) then
      lmin = len
    else
      lmax = len
      nextnt = true
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false
local bt = {}
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end

local thash = {}
if 6 <= n then
  thash[1]
    = bt[1]
    + bt[2] * 30
    + bt[3] * 900
    + bt[4] * 27000
    + bt[5] * 810000
    + bt[6] * 24300000
  for k = 2, n - 5 do
    thash[k] = mfl(thash[k - 1] / 30) + bt[k + 5] * 24300000
  end
end

local function solve(len)
  if 6 <= len then
    local hlen = mfl(len / 2)
    local map = {}
    local hash = {}
    local tmap = {}
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    local taskpos = n - len + 1
    for pos = n - len, len, -1 do
      hash[thash[pos + len - 5]] = true
      if hash[thash[pos - 5]] then
        for tmp = pos + 1, taskpos do
          map[tmap[tmp]] = true
        end
        taskpos = pos
        if map[tmap[pos + 1 - len]] then
          return true
        end
      end
    end
  else
    local map = {}
    local tmap = {}
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      if map[tmap[pos + 1 - len]] then
        return true
      end
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false
local bt = {}
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end

local function solve(len)
  if 6 <= len then
    local hlen = mfl(len / 2)
    local map = {}
    local hash = {}
    local tmap = {}
    local thash = {}
    thash[1]
      = bt[len - 5]
      + bt[len - 4] * 30
      + bt[len - 3] * 900
      + bt[len - 2] * 27000
      + bt[len - 1] * 810000
      + bt[len] * 24300000
    for k = 2, n - len + 1 do
      thash[k] = mfl(thash[k - 1] / 30) + bt[k + len - 1] * 24300000
    end
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    local taskpos = n - len + 1
    for pos = n - len, len, -1 do
      -- map[tmap[pos + 1]] = true
      hash[thash[pos + 1]] = true
      if hash[thash[pos + 1 - len]] then
        for tmp = pos + 1, taskpos do
          map[tmap[tmp]] = true
          taskpos = pos
        end
        if map[tmap[pos + 1 - len]] then
          return true
        end
      end
    end
  else
    local map = {}
    local tmap = {}
    for k = 1, n - len + 1 do
      tmap[k] = s:sub(k, k + len - 1)
    end
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      if map[tmap[pos + 1 - len]] then
        return true
      end
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false
local bt = {}
for i = 1, n do
  bt[i] = s:sub(i, i):byte() - 97
end

local function solve(len)
  local hlen = mfl(len / 2)
  local map = {}
  local hash = {}
  local tmap = {}
  local thash = {}
  for k = 1, n - len + 1 do
    tmap[k] = s:sub(k, k + len - 1)
    if 6 <= len then
      thash[k] = bt[k]
        + bt[k + 1] * 30
        + bt[k + hlen] * 900
        + bt[k + hlen + 1] * 27000
        + bt[k + len - 2] * 810000
        + bt[k + len - 1] * 24300000
    end
  end
  if 6 <= len then
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      hash[thash[pos + 1]] = true
      if hash[thash[pos + 1 - len]] and map[tmap[pos + 1 - len]] then
        return true
      end
    end
  else
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      if map[tmap[pos + 1 - len]] then
        return true
      end
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false

local function solve(len)
  local map = {}
  local hash = {}
  local tmap = {}
  local thash = {}
  for k = 1, n - len + 1 do
    tmap[k] = s:sub(k, k + len - 1)
    if 5 <= len then
      thash[k] =
        (tmap[k]:sub(1, 1):byte() - 97) +
        (tmap[k]:sub(2, 2):byte() - 97) * 30 +
        (tmap[k]:sub(3, 3):byte() - 97) * 900 +
        (tmap[k]:sub(len - 1, len - 1):byte() - 97) * 27000 +
        (tmap[k]:sub(len, len):byte() - 97) * 810000
    end
  end
  if 5 <= len then
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      hash[thash[pos + 1]] = true
      if hash[thash[pos + 1 - len]] and map[tmap[pos + 1 - len]] then
        return true
      end
    end
  else
    for pos = n - len, len, -1 do
      map[tmap[pos + 1]] = true
      if map[tmap[pos + 1 - len]] then
        return true
      end
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false

local function solve(len)
  local map = {}
  local tmap = {}
  for k = 1, n - len + 1 do
    tmap[k] = s:sub(k, k + len - 1)
  end
  for pos = n - len, len, -1 do
    map[tmap[pos + 1]] = true
    if map[tmap[pos + 1 - len]] then
      return true
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false

local function solve(len)
  local map = {}
  for pos = n - len, 1, -1 do
    map[s:sub(pos + 1, pos + len)] = true
    if map[s:sub(pos + 1 - len, pos)] then
      return true
    end
  end
  return false
end
if not solve(1) then
  print(0)
else
  local lmin, lmax = 1, maxlen + 1
  while 1 < lmax - lmin do
    local len = mfl((lmax + lmin) / 2)
    if solve(len) then
      lmin = len
    else
      lmax = len
    end
    -- print(len, lmin, lmax)
  end
  print(lmin)
end


local n = io.read("*n", "*l")
local s = io.read()
local mfl = math.floor
local maxlen = mfl(n / 2)
local found = false
for len = maxlen, 1, -1 do
  local map = {}
  for pos = n - len, 1, -1 do
    map[s:sub(pos + 1, pos + len)] = true
    if map[s:sub(pos + 1 - len, pos)] then
      print(len)
      found = true
      break
    end
  end
  if found then break end
end
if not found then
  print(0)
end


a=io.read("*n")
l=io.read()--改行の読み込み
s=io.read()
if a<3200 then
  print("red")
else
  print(s)
end

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


local a=io.read("*n")
local l=io.read()
local s=io.read()
if a>=3200 then
  print(s)
else
  print("red")
end


local a,s = io.read("*n","*l")
if a >= 3200 then
  print(s)
else
  print('red')
end


local a = io.stdin:read()
local s = io.stdin:read()

if a >= 3200 then
  print(s)
else
  print('red')
end


local a = io.read("*l")
if tonumber(a) >= 3200 then
  print(io.read())
else
  print('red')
end


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

if a >= 3200 then
  print(s)
else
  print('red')
end


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

if a >= 3200 then
  print(s)
else
  print("red")
end


local a = io.read("*n")
local s = io.read("*l")

if a >= 3200 then
  print(s)
else
  print('red')
end


local a = io.stdin:read();
local s = io.stdin:read();


local a = io.stdin:read();
local s = io.stdin:read();
print(3200 <= a and s or "red")


while true do
  local a =io.read()
  if a == nil then return end
  print(a)
end

while true do
  local s =io.read()
  if s == nil then return end
  print(s)
end

if a >= 3200 then
    print(s)
else
    print('red')
end


while true do
    local a = io.read()
    local s = io.read()
    if a  == nil then return end
    print(a)
    if s  == nil then return end
      print(s)
end

if a >= 3200 then
    print(s)
else
    print('red')
end


local a = io.stdin:read();
local s = io.stdin:read();

if a >= 3200 then
    print(s)
else
    print('red')
end


local a = io.read()
local s = io.read()

if a >= 3200 then
    print(s)
else
    print('red')
end


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 return function() return r(u(a)) end end})
-- A
local a, _, s = read.nll()
if a >= 3200 then print(s)
else print("red") end


local a = io.read("*n", "*l")
local s = io.read()
print(3200 <= a and s or "red")


local n, q = io.read("*n", "*n")
local cost = {}
local edge = {}
local asked = {}
for i = 1, n do
  cost[i] = 0
  edge[i] = {}
  asked[i] = false
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  table.insert(edge[a], b)
  table.insert(edge[b], a)
end
for iq = 1, q do
  local p, x = io.read("*n", "*n")
  cost[p] = cost[p] + x
end
local tasks = {1}
for i = 1, n do
  local p = tasks[i]
  asked[p] = true
  local e = edge[p]
  for j = 1, #e do
    local c = e[j]
    if not asked[c] then
      table.insert(tasks, c)
      cost[c] = cost[c] + cost[p]
    end
  end
end
print(table.concat(cost, " "))

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20


--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n,q=io.read("*n","*n")
local edge={}
local counter={}
for i=1,n do
    counter[i]=0
    edge[i]={}
end
for i=1,n-1 do
    local a,b=io.read("*n","*n")
    edge[a][b]=false
    edge[b][a]=false
end
for i=1,q do
    local p,x=io.read("*n","*n")
    counter[p]=counter[p]+x
end

local que=List.new()
List.pushright(que,1)

while true do
    local a=List.popleft(que)
    if a then
        for b,_ in pairs(edge[a]) do
            if not edge[a][b] then
                counter[b]=counter[b]+counter[a]
                edge[a][b]=true
                edge[b][a]=true
                List.pushright(que,b)
            end
        end
    else
        break
    end
end

print(table.concat(counter," "))


--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n,q=io.read("n","n")
local edge={}
local counter={}
for i=1,n do
    counter[i]=0
    edge[i]={}
end
for i=1,n-1 do
    local a,b=io.read("n","n")
    edge[a][b]=false
    edge[b][a]=false
end
for i=1,q do
    local p,x=io.read("n","n")
    counter[p]=counter[p]+x
end

local que=List.new()
List.pushright(que,1)

while true do
    local a=List.popleft(que)
    if a then
        for b,_ in pairs(edge[a]) do
            if not edge[a][b] then
                counter[b]=counter[b]+counter[a]
                edge[a][b]=true
                edge[b][a]=true
                List.pushright(que,b)
            end
        end
    else
        break
    end
end

print(table.concat(counter," "))


--https://www.lua.org/pil/11.4.html
List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n,q=io.read("*n","*n")
local edge={}
local counter={}
for i=1,n do
    counter[i]=0
    edge[i]={}
end
for i=1,n-1 do
    local a,b=io.read("*n","*n")
    edge[a][b]=false
    edge[b][a]=false
end
for i=1,q do
    local p,x=io.read("*n","*n")
    counter[p]=counter[p]+x
end

local que=List.new()
List.pushright(que,1)

while true do
    local a=List.popleft(que)
    if a then
        for b,_ in pairs(edge[a]) do
            if not edge[a][b] and not edge[b][a] then
                counter[b]=counter[b]+counter[a]
                edge[a][b]=true
                edge[b][a]=true
                List.pushright(que,b)
            end
        end
    else
        break
    end
end

print(table.concat(counter," "))


--https://www.lua.org/pil/11.4.html
List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n,q=io.read("n","n")
local edge={}
local counter={}
for i=1,n do
    counter[i]=0
    edge[i]={}
end
for i=1,n-1 do
    local a,b=io.read("n","n")
    edge[a][b]=false
    edge[b][a]=false
end
for i=1,q do
    local p,x=io.read("n","n")
    counter[p]=counter[p]+x
end

local que=List.new()
List.pushright(que,1)

while true do
    local a=List.popleft(que)
    if a then
        for b,_ in pairs(edge[a]) do
            if not edge[a][b] and not edge[b][a] then
                counter[b]=counter[b]+counter[a]
                edge[a][b]=true
                edge[b][a]=true
                List.pushright(que,b)
            end
        end
    else
        break
    end
end

print(table.concat(counter," "))


--https://www.lua.org/pil/11.4.html
List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n,q=io.read("n","n")
local edge={}
local counter={}
for i=1,n do
    counter[i]=0
    edge[i]={}
end
for i=1,n-1 do
    local a,b=io.read("n","n")
    edge[a][b]=false
end
for i=1,q do
    local p,x=io.read("n","n")
    counter[p]=counter[p]+x
end

local que=List.new()
List.pushright(que,1)

while true do
    local a=List.popleft(que)
    if a then
        for b,_ in pairs(edge[a]) do
            if not edge[a][b] then
                counter[b]=counter[b]+counter[a]
                edge[a][b]=true
                List.pushright(que,b)
            end
        end
    else
        break
    end
end

print(table.concat(counter," "))


local n,q=io.read("n","n")

local edge={}
local c={}
for i=1,n do
    c[i]=0
end

local function dfs(i,k)
    for j=1,#edge[i] do
        if j~=k then
            c[edge[j]]=(c[edge[j]] or 0)+(c[i] or 0)
            dfs(j,i)
        end
    end
end

for i=1,n-1 do
    local a,b=io.read("n","n")
    if not edge[a] then
        edge[a]={}
    end
    if not edge[b] then
        edge[b]={}
    end
    table.insert(edge[a],b)
    table.insert(edge[b],a)
end

for i=1,q do
    local p,x=io.read("n","n")
    c[p]=c[p]+x
end

dfs(1,-1)
print(table.concat(c," "))


local n,q=io.read("n","n")

local edge={}
local c={}
local function dfs(i,k)
    if #edge[i]>0 then
        for _,j in pairs(edge[i]) do
            if j~=k then
                c[j]=(c[j] or 0)+(c[i] or 0)
                dfs(j,i)
            end
        end
    end
end
for i=1,n do
    c[i]=0
end

for i=1,n-1 do
    local a,b=io.read("n","n")
    if not edge[a] then
        edge[a]={}
    end
    if not edge[b] then
        edge[b]={}
    end
    table.insert(edge[a],b)
    table.insert(edge[b],a)
end

for i=1,q do
    local p,x=io.read("n","n")
    c[p]=c[p]+x
end

dfs(1,-1)
print(table.concat(c," "))


local edge={}
local c={}
local function dfs(i,k)
    if #edge[i]>0 then
        for _,j in pairs(edge[i]) do
            if j~=k then
                c[j]=(c[j] or 0)+(c[i] or 0)
                dfs(j,i)
            end
        end
    end
end

local n,q=io.read("n","n")
for i=1,n-1 do
    local a,b=io.read("n","n")
    if not edge[a] then
        edge[a]={}
    end
    if not edge[b] then
        edge[b]={}
    end
    table.insert(edge[a],b)
    table.insert(edge[b],a)
end

for i=1,q do
    local p,x=io.read("n","n")
    c[p]=(c[p] or 0)+x
end

dfs(1,0)
print(table.concat(c," "))


local edge={}
local c={}
local function dfs(i,k)
    for _,j in pairs(edge[i]) do
        if j~=k then
            c[j]=(c[j] or 0)+(c[i] or 0)
            dfs(j,i)
        end
    end
end

local n,q=io.read("n","n")
for i=1,n-1 do
    local a,b=io.read("n","n")
    if not edge[a] then
        edge[a]={}
    end
    if not edge[b] then
        edge[b]={}
    end
    table.insert(edge[a],b)
    table.insert(edge[b],a)
end

for i=1,q do
    local p,x=io.read("n","n")
    c[p]=(c[p] or 0)+x
end

dfs(1,0)
print(table.concat(c," "))