Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".

The restaurant "Alice's" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$ customers will visit Alice's one after another and the $j$-th customer will order $d_j$ dishes of the $t_j$-th kind of food. The $(i + 1)$-st customer will only come after the $i$-th customer is completely served.

Suppose there are $r_i$ dishes of the $i$-th kind remaining (initially $r_i = a_i$). When a customer orders $1$ dish of the $i$-th kind, the following principles will be processed. If $r_i > 0$, the customer will be served exactly $1$ dish of the $i$-th kind. The cost for the dish is $c_i$. Meanwhile, $r_i$ will be reduced by $1$. Otherwise, the customer will be served $1$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $1$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $0$.

If the customer doesn't leave after the $d_j$ dishes are served, the cost for the customer will be the sum of the cost for these $d_j$ dishes.

Please determine the total cost for each of the $m$ customers.


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 10^5$), representing the number of different kinds of food and the number of customers, respectively.

The second line contains $n$ positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^7$), where $a_i$ denotes the initial remain of the $i$-th kind of dishes.

The third line contains $n$ positive integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^6$), where $c_i$ denotes the cost of one dish of the $i$-th kind.

The following $m$ lines describe the orders of the $m$ customers respectively. The $j$-th line contains two positive integers $t_j$ and $d_j$ ($1 \leq t_j \leq n$, $1 \leq d_j \leq 10^7$), representing the kind of food and the number of dishes the $j$-th customer orders, respectively.


-----Output-----

Print $m$ lines. In the $j$-th line print the cost for the $j$-th customer.


-----Examples-----
Input
8 5
8 6 2 1 4 5 7 5
6 3 3 2 6 2 3 2
2 8
1 4
4 7
3 4
6 10

Output
22
24
14
10
39

Input
6 6
6 6 6 6 6 6
6 66 666 6666 66666 666666
1 6
2 6
3 6
4 6
5 6
6 66

Output
36
396
3996
39996
399996
0

Input
6 6
6 6 6 6 6 6
6 66 666 6666 66666 666666
1 6
2 13
3 6
4 11
5 6
6 6

Output
36
11058
99996
4333326
0
0



-----Note-----

In the first sample, $5$ customers will be served as follows. Customer $1$ will be served $6$ dishes of the $2$-nd kind, $1$ dish of the $4$-th kind, and $1$ dish of the $6$-th kind. The cost is $6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$. The remain of the $8$ kinds of food will be $\{8, 0, 2, 0, 4, 4, 7, 5\}$. Customer $2$ will be served $4$ dishes of the $1$-st kind. The cost is $4 \cdot 6 = 24$. The remain will be $\{4, 0, 2, 0, 4, 4, 7, 5\}$. Customer $3$ will be served $4$ dishes of the $6$-th kind, $3$ dishes of the $8$-th kind. The cost is $4 \cdot 2 + 3 \cdot 2 = 14$. The remain will be $\{4, 0, 2, 0, 4, 0, 7, 2\}$. Customer $4$ will be served $2$ dishes of the $3$-rd kind, $2$ dishes of the $8$-th kind. The cost is $2 \cdot 3 + 2 \cdot 2 = 10$. The remain will be $\{4, 0, 0, 0, 4, 0, 7, 0\}$. Customer $5$ will be served $7$ dishes of the $7$-th kind, $3$ dishes of the $1$-st kind. The cost is $7 \cdot 3 + 3 \cdot 6 = 39$. The remain will be $\{1, 0, 0, 0, 4, 0, 0, 0\}$.

In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $6$ dishes of the second kind, so the cost is $66 \cdot 6 = 396$.

In the third sample, some customers may not be served what they order. For example, the second customer is served $6$ dishes of the second kind, $6$ of the third and $1$ of the fourth, so the cost is $66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$.

Source: codeforces | Difficulty: MEDIUM
Tags: Data structures

Implementation


Solutions:
import math
from collections import Counter
import itertools
l = []
l1 = []
q = []
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(m):
	q += [list(map(int, input().split()))]
c = [0] + c
a = [0] + a
o = []
for i in range(1, n + 1):
	o += [[c[i], a[i]]]
o = [[0, 0]] + o
p = []
for i in range(0, n + 1):
	p += [[c[i], i]]
p.sort()
s = 1
for i in q:
	r = 0
	if o[i[0]][1] >= i[1]:
		o[i[0]][1] -= i[1]
		r += o[i[0]][0] * i[1]
	elif o[i[0]][1] < i[1]:
		i[1] -= o[i[0]][1]
		r += o[i[0]][0] * o[i[0]][1]
		j = i[1]
		o[i[0]][1] = 0
		while j > 0:
			if s < n + 1:
				if j > o[p[s][1]][1]:
					j -= o[p[s][1]][1]
					r += o[p[s][1]][1] * p[s][0]
					o[p[s][1]][1] = 0
					s += 1
				elif j < o[p[s][1]][1]:
					o[p[s][1]][1] -= j
					r += j * p[s][0]
					j = 0
				else:
					o[p[s][1]][1] = 0
					r += j * p[s][0]
					j = 0
					s += 1
			else:
				r = 0
				z = 1
				break
	print(r)


def inpl():
	return list(map(int, input().split()))
(N, M) = inpl()
A = inpl()
C = inpl()
Dishnum = sum(A)
ACi = [[c, i, a] for (i, (a, c)) in enumerate(zip(A, C), 1)]
ACi.sort()
Orig = dict()
for (i, (_, j, _)) in enumerate(ACi):
	Orig[j] = i
ctr = 0
for _ in range(M):
	ans = 0
	(t, d) = inpl()
	t = Orig[t]
	Dishnum -= d
	if Dishnum < 0:
		print(ans)
		continue
	k = min(d, ACi[t][2])
	ACi[t][2] -= k
	d -= k
	ans += k * ACi[t][0]
	while d > 0:
		k = min(d, ACi[ctr][2])
		ACi[ctr][2] -= k
		d -= k
		ans += k * ACi[ctr][0]
		if not ACi[ctr][2]:
			ctr += 1
	print(ans)


R = lambda : [*map(int, input().split())]
(n, m) = R()
(a, c) = (R(), R())
b = sorted(zip(c, range(n)))
i = 0
s = ''

def f():
	global r, d
	e = min(a[t], d)
	a[t] -= e
	d -= e
	r += x * e
for _ in [0] * m:
	(t, d) = R()
	t -= 1
	r = 0
	x = c[t]
	f()
	while d and i < n:
		(x, t) = b[i]
		f()
		if a[t] == 0:
			i += 1
	if d:
		r = 0
	s += f'{r} '
print(s)


from operator import itemgetter
(n, m) = map(int, input().split())
food = list(map(int, input().split()))
cost = list(map(int, input().split()))
arr = [0] * n
for i in range(n):
	arr[i] = [0] * 2
	arr[i][0] = i
	arr[i][1] = cost[i]
arr = sorted(arr, key=itemgetter(1))
index = 0
for i in range(m):
	ans = 0
	(t, d) = map(int, input().split())
	if food[t - 1] >= d:
		ans += cost[t - 1] * d
		food[t - 1] -= d
		d = 0
	else:
		d -= food[t - 1]
		ans += cost[t - 1] * food[t - 1]
		food[t - 1] = 0
		if d > 0:
			ind = index
			for j in range(ind, n):
				y = min(d, food[arr[j][0]])
				ans += arr[j][1] * y
				food[arr[j][0]] -= y
				d -= y
				if food[arr[j][0]] == 0:
					index += 1
				if d == 0:
					break
	if d == 0:
		print(ans)
	else:
		print(0)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return len(set(factors))

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))
MOD = 1000000007
PMOD = 998244353
T = 1
for _ in range(T):
	(n, m) = list(map(int, stdin.readline().rstrip().split()))
	a = list(map(int, stdin.readline().rstrip().split()))
	c = list(map(int, stdin.readline().rstrip().split()))
	s = []
	for i in range(n):
		s.append([c[i], i])
	s.sort()
	while m > 0:
		(t, d) = list(map(int, stdin.readline().rstrip().split()))
		t -= 1
		ans = 0
		if d < a[t]:
			ans += c[t] * d
			a[t] -= d
			d = 0
		else:
			ans += c[t] * a[t]
			d -= a[t]
			a[t] = 0
			while d > 0 and len(s) > 0:
				ix = s[0][1]
				if t == ix:
					s.pop(0)
					continue
				if d <= a[ix]:
					ans += c[ix] * d
					a[ix] -= d
					d = 0
				else:
					ans += c[ix] * a[ix]
					d -= a[ix]
					a[ix] = 0
					s.pop(0)
		if d != 0:
			print(0)
		else:
			print(ans)
		m -= 1


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
p = [x for (_, x) in sorted(zip(b, range(n)))][::-1]
for _ in range(m):
	(x, y) = map(int, input().split())
	s = 0
	d = min(y, a[x - 1])
	s += b[x - 1] * d
	y -= d
	a[x - 1] -= d
	while p and y > 0:
		x = p[-1]
		d = min(a[x], y)
		s += b[x] * d
		y -= d
		a[x] -= d
		if not a[x]:
			p.pop()
	print(0 if y else s)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
p = []
for i in range(n):
	p.append([i, c[i]])
p = sorted(p, key=lambda item: item[1])
zer0 = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		print(c[t] * d)
		a[t] -= d
		continue
	else:
		ans = 0
		req = d
		req -= a[t]
		ans += c[t] * a[t]
		a[t] = 0
		if req > 0:
			for j in range(zer0, n):
				y = min(req, a[p[j][0]])
				ans += p[j][1] * y
				a[p[j][0]] -= y
				req -= y
				if a[p[j][0]] == 0:
					zer0 += 1
				if req == 0:
					break
		if req != 0:
			print(0)
			continue
		else:
			print(ans)


(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
crr = []
for i in range(n):
	crr.append([brr[i], i, arr[i]])
crr.sort()
last_index = 0
for i in range(m):
	(idx, cnt) = map(int, input().split())
	idx -= 1
	cost = 0
	if arr[idx] >= cnt:
		cost = cnt * brr[idx]
		arr[idx] -= cnt
		cnt = 0
		print(cost)
	else:
		cost = arr[idx] * brr[idx]
		cnt -= arr[idx]
		arr[idx] = 0
		while cnt > 0 and crr[-1][2] != 0:
			for i in range(last_index, n):
				c_ka_idx = crr[i][1]
				if arr[c_ka_idx] != crr[i][2]:
					crr[i][2] = arr[c_ka_idx]
				if crr[i][2] > 0:
					if crr[i][2] >= cnt:
						cost += cnt * crr[i][0]
						crr[i][2] -= cnt
						arr[c_ka_idx] -= cnt
						cnt = 0
						if crr[i][2] == 0:
							last_index = i + 1
					else:
						cost += crr[i][2] * crr[i][0]
						cnt -= crr[i][2]
						crr[i][2] = 0
						last_index = i + 1
						arr[c_ka_idx] = 0
				if cnt <= 0:
					break
			if cnt <= 0:
				break
		if cnt == 0:
			print(cost)
		else:
			print(0)


import sys
read = lambda : map(int, sys.stdin.readline().split())
write = sys.stdout.write
(n, m) = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(1, n + 1):
	remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
	(t, d) = read()
	ans = 0
	if dishes == 0:
		write('0\n')
	elif dish[t] >= d:
		dishes -= d
		dish[t] -= d
		write(f'{cost[t] * d}\n')
	elif dish[t] < d:
		ans += dish[t] * cost[t]
		dishes -= dish[t]
		d -= dish[t]
		dish[t] = 0
		while d > 0 and dishes > 0:
			k = remain[-1][1]
			if dish[k] >= d:
				dish[k] -= d
				dishes -= d
				ans += cost[k] * d
				d = 0
			else:
				dishes -= dish[k]
				d -= dish[k]
				ans += cost[k] * dish[k]
				dish[k] = 0
				remain.pop()
		if d > 0 and dishes == 0:
			write('0\n')
		else:
			write(f'{ans}\n')


from collections import deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
h = list(zip(c, range(n)))
h.sort(key=lambda x: (x[0], x[1]))
h = deque(h)
ans = ''
for _ in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	cc = 0
	if a[t] >= d:
		a[t] -= d
		cc += d * c[t]
		d = 0
	else:
		if a[t] > 0:
			d -= a[t]
			cc += a[t] * c[t]
			a[t] = 0
		while d > 0 and h:
			if a[h[0][1]] == 0:
				h.popleft()
			elif a[h[0][1]] >= d:
				a[h[0][1]] -= d
				cc += d * c[h[0][1]]
				d = 0
			else:
				d -= a[h[0][1]]
				cc += a[h[0][1]] * c[h[0][1]]
				a[h[0][1]] = 0
				h.popleft()
	if d > 0:
		ans += '0\n'
	else:
		ans += str(cc) + '\n'
print(ans)


from sys import stdin, stdout
import cProfile, math
from collections import Counter, deque
from bisect import bisect_left, bisect, bisect_right
import itertools
from copy import deepcopy
from fractions import Fraction
import sys, threading
import operator as op
from functools import reduce
sys.setrecursionlimit(10 ** 6)
threading.stack_size(2 ** 27)
fac_warmup = False
printHeap = str()
memory_constrained = False
P = 10 ** 9 + 7
import sys

class Operation:

	def __init__(self, name, function, function_on_equal, neutral_value=0):
		self.name = name
		self.f = function
		self.f_on_equal = function_on_equal

def add_multiple(x, count):
	return x * count

def min_multiple(x, count):
	return x

def max_multiple(x, count):
	return x
sum_operation = Operation('sum', sum, add_multiple, 0)
min_operation = Operation('min', min, min_multiple, 1000000000.0)
max_operation = Operation('max', max, max_multiple, -1000000000.0)

class SegmentTree:

	def __init__(self, array, operations=[sum_operation, min_operation, max_operation]):
		self.array = array
		if type(operations) != list:
			raise TypeError('operations must be a list')
		self.operations = {}
		for op in operations:
			self.operations[op.name] = op
		self.root = SegmentTreeNode(0, len(array) - 1, self)

	def query(self, start, end, operation_name):
		if self.operations.get(operation_name) == None:
			raise Exception('This operation is not available')
		return self.root._query(start, end, self.operations[operation_name])

	def summary(self):
		return self.root.values

	def update(self, position, value):
		self.root._update(position, value)

	def update_range(self, start, end, value):
		self.root._update_range(start, end, value)

	def __repr__(self):
		return self.root.__repr__()

class SegmentTreeNode:

	def __init__(self, start, end, segment_tree):
		self.range = (start, end)
		self.parent_tree = segment_tree
		self.range_value = None
		self.values = {}
		self.left = None
		self.right = None
		if start == end:
			self._sync()
			return
		self.left = SegmentTreeNode(start, start + (end - start) // 2, segment_tree)
		self.right = SegmentTreeNode(start + (end - start) // 2 + 1, end, segment_tree)
		self._sync()

	def _query(self, start, end, operation):
		if end < self.range[0] or start > self.range[1]:
			return None
		if start <= self.range[0] and self.range[1] <= end:
			return self.values[operation.name]
		self._push()
		left_res = self.left._query(start, end, operation) if self.left else None
		right_res = self.right._query(start, end, operation) if self.right else None
		if left_res is None:
			return right_res
		if right_res is None:
			return left_res
		return operation.f([left_res, right_res])

	def _update(self, position, value):
		if position < self.range[0] or position > self.range[1]:
			return
		if position == self.range[0] and self.range[1] == position:
			self.parent_tree.array[position] = value
			self._sync()
			return
		self._push()
		self.left._update(position, value)
		self.right._update(position, value)
		self._sync()

	def _update_range(self, start, end, value):
		if end < self.range[0] or start > self.range[1]:
			return
		if start <= self.range[0] and self.range[1] <= end:
			self.range_value = value
			self._sync()
			return
		self._push()
		self.left._update_range(start, end, value)
		self.right._update_range(start, end, value)
		self._sync()

	def _sync(self):
		if self.range[0] == self.range[1]:
			for op in self.parent_tree.operations.values():
				current_value = self.parent_tree.array[self.range[0]]
				if self.range_value is not None:
					current_value = self.range_value
				self.values[op.name] = op.f([current_value])
		else:
			for op in self.parent_tree.operations.values():
				result = op.f([self.left.values[op.name], self.right.values[op.name]])
				if self.range_value is not None:
					bound_length = self.range[1] - self.range[0] + 1
					result = op.f_on_equal(self.range_value, bound_length)
				self.values[op.name] = result

	def _push(self):
		if self.range_value is None:
			return
		if self.left:
			self.left.range_value = self.range_value
			self.right.range_value = self.range_value
			self.left._sync()
			self.right._sync()
			self.range_value = None

	def __repr__(self):
		ans = '({}, {}): {}\n'.format(self.range[0], self.range[1], self.values)
		if self.left:
			ans += self.left.__repr__()
		if self.right:
			ans += self.right.__repr__()
		return ans

def display(string_to_print):
	stdout.write(str(string_to_print) + '\n')

def primeFactors(n):
	factors = dict()
	for i in range(2, math.ceil(math.sqrt(n)) + 1):
		while n % i == 0:
			if i in factors:
				factors[i] += 1
			else:
				factors[i] = 1
			n = n // i
	if n > 2:
		factors[n] = 1
	return factors

def isprime(n):
	if n < 4:
		return True
	if n % 2 == 0:
		return False
	if n % 3 == 0:
		return False
	i = 5
	w = 2
	while i * i <= n:
		if n % i == 0:
			return False
		i += w
		w = 6 - w
	return True
factorial_modP = []

def warm_up_fac(MOD):
	nonlocal factorial_modP, fac_warmup
	if fac_warmup:
		return
	factorial_modP = [1 for _ in range(fac_warmup_size + 1)]
	for i in range(2, fac_warmup_size):
		factorial_modP[i] = factorial_modP[i - 1] * i % MOD
	fac_warmup = True

def InverseEuler(n, MOD):
	return pow(n, MOD - 2, MOD)

def nCr(n, r, MOD):
	nonlocal fac_warmup, factorial_modP
	if not fac_warmup:
		warm_up_fac(MOD)
		fac_warmup = True
	return factorial_modP[n] * (pow(factorial_modP[r], MOD - 2, MOD) * pow(factorial_modP[n - r], MOD - 2, MOD) % MOD) % MOD

def test_print(*args):
	if testingMode:
		print(args)

def display_list(list1, sep=' '):
	stdout.write(sep.join(map(str, list1)) + '\n')

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))
memory = dict()

def clear_cache():
	nonlocal memory
	memory = dict()

def cached_fn(fn, *args):
	nonlocal memory
	if args in memory:
		return memory[args]
	else:
		result = fn(*args)
		memory[args] = result
		return result
TestCases = False
testingMode = False
fac_warmup_size = 10 ** 5 + 100
optimiseForReccursion = True

def main():
	(n, m) = get_tuple()
	remaining = get_list()
	costs = get_list()
	ki = [(ele, i) for (i, ele) in enumerate(costs)]
	ki.sort()
	ind = 0
	res = []
	for _ in range(m):
		(t, d) = get_tuple()
		t -= 1
		if remaining[t] >= d:
			res.append(costs[t] * d)
			remaining[t] -= d
		else:
			cost = remaining[t] * costs[t]
			d -= remaining[t]
			remaining[t] = 0
			while ind < n:
				(a_cost, a_index) = (ki[ind][0], ki[ind][1])
				if remaining[a_index] >= d:
					cost += costs[a_index] * d
					remaining[a_index] -= d
					d = 0
					break
				else:
					cost += remaining[a_index] * costs[a_index]
					d -= remaining[a_index]
					remaining[a_index] = 0
				ind += 1
			if d == 0:
				res.append(cost)
			else:
				res.append(0)
	for i in res:
		print(i)
if TestCases:
	for _ in range(get_int()):
		cProfile.run('main()') if testingMode else main()
else:
	(cProfile.run('main()') if testingMode else main()) if not optimiseForReccursion else threading.Thread(target=main).start()


from collections import deque
(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
z = deque(sorted([(c[i], i) for i in range(n)]))
for _ in range(m):
	(t, d) = [int(x) for x in input().split()]
	ans = 0
	t -= 1
	k = min(d, a[t])
	a[t] -= k
	ans += k * c[t]
	d -= k
	while d > 0 and z:
		curr = z[0]
		k = min(a[curr[1]], d)
		a[curr[1]] -= k
		d -= k
		ans += curr[0] * k
		if not a[curr[1]]:
			z.popleft()
	if not d:
		print(ans)
	else:
		print(0)


import heapq
(n, m) = map(int, input().split())
dish = list(map(int, input().split()))
cost = list(map(int, input().split()))
arrange_cost = []
nomore = 0
for i in range(n):
	heapq.heappush(arrange_cost, [cost[i], i])
for i in range(m):
	(a, b) = map(int, input().split())
	if nomore:
		print(0)
	elif dish[a - 1] >= b:
		dish[a - 1] -= b
		print(cost[a - 1] * b)
	else:
		price = 0
		if dish[a - 1] > 0:
			price += dish[a - 1] * cost[a - 1]
			b -= dish[a - 1]
			dish[a - 1] = 0
		while len(arrange_cost) > 0 and b > 0:
			(p, d) = heapq.heappop(arrange_cost)
			if dish[d] > 0:
				if dish[d] >= b:
					price += p * b
					dish[d] -= b
					b = 0
					if dish[d] > 0:
						heapq.heappush(arrange_cost, [p, d])
				else:
					price += p * dish[d]
					b -= dish[d]
					dish[d] = 0
		if b < 1:
			print(price)
		else:
			print(0)
			nomore = 1


(n, m) = map(int, input().split())
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
d = [[price[i], i] for i in range(n)]
j = 0
d = sorted(d, key=lambda x: x[0])
for i in range(m):
	out = 0
	(a, b) = map(int, input().split())
	v = min(ost[a - 1], b)
	b -= v
	out += v * price[a - 1]
	ost[a - 1] -= v
	while j < n:
		if b == 0:
			break
		v = min(ost[d[j][1]], b)
		b -= v
		ost[d[j][1]] -= v
		out += v * price[d[j][1]]
		if ost[d[j][1]] == 0:
			j += 1
	if b == 0:
		print(out)
	else:
		print(0)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
c = list(map(int, input().split()))
l = 0
s = sum(a)
b = {}
for i in range(n):
	if c[i] in b:
		b[c[i]].append(i)
	else:
		b[c[i]] = [i]
d = list(set(c))
d.sort()
e = []
for i in d:
	t = b[i]
	for j in t:
		e.append(j)
t = 0
for _ in range(m):
	(p, q) = list(map(int, input().split()))
	k = 0
	l += q
	if l > s:
		print(0)
	else:
		if a[p - 1] >= q:
			k += c[p - 1] * q
			a[p - 1] = a[p - 1] - q
		else:
			if a[p - 1] > 0:
				k += c[p - 1] * a[p - 1]
				q = q - a[p - 1]
				a[p - 1] = 0
			while t < n and q > 0:
				if a[e[t]] >= q:
					k += c[e[t]] * q
					a[e[t]] = a[e[t]] - q
					q = 0
				else:
					k += c[e[t]] * a[e[t]]
					q = q - a[e[t]]
					a[e[t]] = 0
					t = t + 1
		print(k)


(n, m) = input().split()
n = int(n)
m = int(m)
a = list(map(int, input().split()))
c = list(map(int, input().split()))
x = []
for i in range(n):
	x.append([c[i], i])
x.sort()
o = 0
for i in range(m):
	ans = 0
	(t, d) = input().split()
	t = int(t)
	d = int(d)
	if d <= a[t - 1]:
		a[t - 1] = a[t - 1] - d
		print(d * c[t - 1])
	else:
		ans = a[t - 1] * c[t - 1]
		r = d - a[t - 1]
		a[t - 1] = 0
		while o < n:
			(g, v) = (x[o][1], x[o][0])
			if a[g] >= r:
				a[g] = a[g] - r
				ans = ans + r * v
				r = 0
				break
			else:
				ans = ans + a[g] * v
				r = r - a[g]
				a[g] = 0
			o += 1
		if r > 0:
			print(0)
		else:
			print(ans)


import sys
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
lines = sys.stdin.readlines()
tmp = list(zip(c, range(n)))
tmp.sort()
cheapest = 0
result = []
for idx in range(m):
	(t, d) = map(int, lines[idx].split())
	t -= 1
	score = 0
	while cheapest < n and d != 0:
		if a[t] >= d:
			score += c[t] * d
			a[t] -= d
			d = 0
		elif 0 < a[t] < d:
			score += c[t] * a[t]
			d -= a[t]
			a[t] = 0
		elif a[t] == 0:
			while cheapest < n and a[tmp[cheapest][1]] == 0:
				cheapest += 1
			if cheapest == n:
				break
			elif a[tmp[cheapest][1]] >= d:
				score += c[tmp[cheapest][1]] * d
				a[tmp[cheapest][1]] -= d
				d = 0
			elif 0 < a[tmp[cheapest][1]] < d:
				score += c[tmp[cheapest][1]] * a[tmp[cheapest][1]]
				d -= a[tmp[cheapest][1]]
				a[tmp[cheapest][1]] = 0
			else:
				raise Exception('test0')
		else:
			raise Exception('test')
	if cheapest < n:
		result.append(score)
	else:
		result.append(0)
print('\n'.join(list(map(str, result))))


from heapq import *
R = lambda : [*map(int, input().split())]
(n, m) = R()
(a, c) = (R(), R())
b = [*zip(c, range(n))]
heapify(b)
for _ in [0] * m:
	(t, d) = R()
	t -= 1
	r = 0
	e = min(a[t], d)
	a[t] -= e
	d -= e
	r += c[t] * e
	while d and b:
		(x, t) = b[0]
		e = min(a[t], d)
		a[t] -= e
		d -= e
		r += x * e
		if a[t] == 0:
			heappop(b)
	print((0, r)[d == 0])


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def get_ints():
	return map(int, sys.stdin.readline().split())
(n, m) = get_ints()
dish = list(get_ints())
cost = list(get_ints())
arr = []
for i in range(n):
	arr.append([i, cost[i]])
arr = sorted(arr, key=lambda x: (x[1], x[0]))
ans = [0] * m
j = 0
flag = False
for k in range(m):
	(i, qty) = map(int, input().split())
	c = 0
	i -= 1
	if qty > dish[i]:
		qty -= dish[i]
		c += dish[i] * cost[i]
		dish[i] = 0
		while qty != 0:
			if j == n:
				flag = True
				break
			if qty > dish[arr[j][0]]:
				c += dish[arr[j][0]] * cost[arr[j][0]]
				qty -= dish[arr[j][0]]
				dish[arr[j][0]] = 0
				j += 1
			elif qty == dish[arr[j][0]]:
				dish[arr[j][0]] = 0
				c += qty * cost[arr[j][0]]
				qty = 0
				j += 1
			else:
				c += qty * cost[arr[j][0]]
				dish[arr[j][0]] -= qty
				qty = 0
	else:
		c = qty * cost[i]
		dish[i] -= qty
		qty = 0
	if flag:
		break
	ans[k] = c
for i in ans:
	print(i)


(num_dishes, num_customers) = [int(x) for x in input().split()]
dish_amounts = [int(x) for x in input().split()]
dish_costs = [int(x) for x in input().split()]
dishes_by_price = sorted(list(range(num_dishes)), key=lambda i: dish_costs[i])
dbp_i = 0
for j in range(num_customers):
	(dish, amount) = [int(x) for x in input().split()]
	dish -= 1
	served = min(dish_amounts[dish], amount)
	dish_amounts[dish] -= served
	cost = served * dish_costs[dish]
	not_served = amount - served
	while not_served > 0 and dbp_i != num_dishes:
		i = dishes_by_price[dbp_i]
		served = min(dish_amounts[i], not_served)
		cost += served * dish_costs[i]
		dish_amounts[i] -= served
		not_served -= served
		if dish_amounts[i] == 0:
			dbp_i += 1
	if not_served > 0:
		cost = 0
	print(cost)


import heapq

def rlist():
	return list(map(int, input().split()))

def rdi():
	return int(input())
(n, m) = rlist()
count = rlist()
price = rlist()
users = list()
for i in range(m):
	(x, y) = rlist()
	users.append((x - 1, y))
menu = list()
for i in range(n):
	heapq.heappush(menu, (price[i], i))
for user in users:
	(ind, cnt) = user
	if count[ind] >= cnt:
		count[ind] -= cnt
		print(cnt * price[ind])
		continue
	else:
		m = 0
		if count[ind] != 0:
			cnt -= count[ind]
			m += count[ind] * price[ind]
			count[ind] = 0
		while len(menu) != 0 and cnt != 0:
			if count[menu[0][1]] == 0:
				heapq.heappop(menu)
			elif count[menu[0][1]] >= cnt:
				count[menu[0][1]] -= cnt
				m += menu[0][0] * cnt
				cnt = 0
			elif count[menu[0][1]] < cnt:
				m += menu[0][0] * count[menu[0][1]]
				cnt -= count[menu[0][1]]
				count[menu[0][1]] = 0
		if cnt != 0:
			print(0)
		else:
			print(m)


def main():
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	c = list(map(int, input().split()))
	b = [(c[i], i) for i in range(n)]
	b.sort()
	b = [b[i][1] for i in range(n)]
	bi = 0
	for i in range(m):
		(t, d) = list(map(int, input().split()))
		t -= 1
		s = 0
		if a[t] >= d:
			a[t] -= d
			print(d * c[t])
		else:
			s += a[t] * c[t]
			d -= a[t]
			a[t] = 0
			while bi < n:
				if a[b[bi]] >= d:
					s += d * c[b[bi]]
					a[b[bi]] -= d
					d = 0
					break
				s += a[b[bi]] * c[b[bi]]
				d -= a[b[bi]]
				a[b[bi]] = 0
				bi += 1
			if d > 0:
				print(0)
			else:
				print(s)
main()


from sys import stdin, stdout
from itertools import combinations
from collections import defaultdict

def listIn():
	return list(map(int, stdin.readline().strip().split()))

def stringListIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def stringIn():
	return stdin.readline()
(n, m) = listIn()
a = listIn()
c = listIn()
minn = float('inf')
flag = False
di = defaultdict(int)
for j in range(n):
	di[c[j], j] = a[j]
b = sorted(di.keys())
j = 0
count = 0
for i in range(m):
	total = 0
	if not flag:
		(t, d) = listIn()
		if a[t - 1] >= d:
			a[t - 1] -= d
			di[c[t - 1], t - 1] -= d
			total += c[t - 1] * d
		else:
			total += c[t - 1] * a[t - 1]
			d -= a[t - 1]
			a[t - 1] = 0
			count += 1
			di[c[t - 1], t - 1] = 0
			while j < n:
				ele = b[j]
				val = di[ele]
				if val != 0:
					if val >= d:
						total += d * ele[0]
						a[ele[1]] -= d
						di[ele] -= d
						d = 0
						break
					else:
						total += ele[0] * val
						a[ele[1]] = 0
						d -= val
						di[ele] = 0
						count += 1
				j += 1
			if d != 0:
				total = 0
	stdout.write(str(total) + '\n')


(n, m) = map(int, input().split())
a = [int(s) for s in input().split()]
c = [int(s) for s in input().split()]
types = dict()
for i in range(n):
	types[i] = c[i]
types = sorted(types.items(), key=lambda kv: kv[1])
min_c = types[0]
ind = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	summ = 0
	if a[t] < d:
		summ += a[t] * c[t]
		d -= a[t]
		a[t] = 0
		while a[min_c[0]] < d:
			summ += a[min_c[0]] * c[min_c[0]]
			d -= a[min_c[0]]
			a[min_c[0]] = 0
			ind += 1
			if ind >= n:
				summ = 0
				ind -= 1
				break
			else:
				min_c = types[ind]
		else:
			summ += d * c[min_c[0]]
			a[min_c[0]] -= d
	else:
		summ += d * c[t]
		a[t] -= d
	print(summ)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))
d = dict()
d1 = dict()
for i in range(n):
	if l1[i] in d:
		d[l1[i]] += l[i]
		d1[l1[i]].append(i)
	else:
		d.update({l1[i]: l[i]})
		d1.update({l1[i]: [i]})
key = sorted(d.items())
ls = []
e = 0
for j in key:
	ls.append(j[0])
t = 0
for i in range(m):
	ans = 0
	(a, b) = map(int, input().split())
	if b <= l[a - 1]:
		print(l1[a - 1] * b)
		d[l1[a - 1]] -= b
		l[a - 1] -= b
		continue
	else:
		ans = l1[a - 1] * l[a - 1]
		d[l1[a - 1]] -= l[a - 1]
		b -= l[a - 1]
		l[a - 1] = 0
		if len(ls) == 0:
			print(0)
			continue
		while b > 0:
			ans += min(b, l[d1[ls[e]][t]]) * ls[e]
			r = min(b, l[d1[ls[e]][t]])
			b -= r
			l[d1[ls[e]][t]] -= r
			d[ls[e]] -= r
			if l[d1[ls[e]][t]] == 0:
				t += 1
			if d[ls[e]] == 0:
				ls.pop(0)
				t = 0
			if len(ls) == 0:
				break
		if b != 0:
			ans = 0
		print(ans)


def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(mi())
(n, m) = mi()
a = li()
c = li()
x = list(range(n))
x.sort(key=lambda i: (c[i], i))
cur = 0
out = []
for i in range(m):
	(t, d) = mi()
	p = min(d, a[t - 1])
	d -= p
	a[t - 1] -= p
	ans = c[t - 1] * p
	while d:
		while cur < n and a[x[cur]] == 0:
			cur += 1
		if cur == n:
			ans = 0
			break
		p = min(d, a[x[cur]])
		d -= p
		a[x[cur]] -= p
		ans += c[x[cur]] * p
	out.append(str(ans))
print(*out, sep='\n')


from collections import deque

def get(t, d):
	bill = 0
	flag = True
	if blud[t] >= d:
		bill += d * cost[t]
		blud[t] -= d
		flag = False
		d = 0
	elif blud[t] != 0:
		bill += blud[t] * cost[t]
		d -= blud[t]
		blud[t] = 0
	return (bill, d, flag)

def count_bill(t, d):
	bill = 0
	t -= 1
	(bill, d, emp) = get(t, d)
	if not d:
		return bill
	while d != 0:
		if arr:
			t = arr[0][2]
			(cost, d, emp) = get(t, d)
			if emp:
				arr.popleft()
			bill += cost
		else:
			return 0
	return bill
(n, m) = map(int, input().split())
blud = list(map(int, input().split()))
cost = list(map(int, input().split()))
arr = [(cost[i], blud[i], i) for i in range(n)]
arr.sort()
arr = deque(arr)
for i in range(m):
	(t, d) = map(int, input().split())
	res = count_bill(t, d)
	print(res)


from bisect import *
R = lambda : [*map(int, input().split())]
(n, m) = R()
(a, c) = (R(), R())
b = sorted(zip(c, range(n)))
for _ in [0] * m:
	(t, d) = R()
	t -= 1
	r = 0
	if a[t]:
		e = min(a[t], d)
		a[t] -= e
		d -= e
		r += c[t] * e
	i = 0
	for (x, t) in b:
		e = min(a[t], d)
		a[t] -= e
		d -= e
		r += x * e
		if d == 0:
			break
		i += 1
	b[:i] = []
	print((0, r)[d == 0])


import re, math, decimal, bisect

def read():
	return input().strip()

def iread():
	return int(input().strip())

def viread():
	return [int(_) for _ in input().strip().split()]
(n, m) = viread()
items = []
remain = viread()
cost = viread()
for i in range(n):
	items.append([cost[i], i + 1, remain[i]])
items.sort()
idx = [0] * (n + 1)
for i in range(n):
	idx[items[i][1]] = i
canpick = n
firstnonempty = 0
for i in range(m):
	(t, d) = viread()
	cost = 0
	target = items[idx[t]]
	if target[2] >= d:
		target[2] -= d
		cost += d * target[0]
		if target[2] == 0:
			canpick -= 1
	else:
		if target[2] != 0:
			canpick -= 1
		cost += target[2] * target[0]
		d -= target[2]
		target[2] = 0
		nxt = firstnonempty
		while d > 0 and canpick > 0 and (nxt <= n):
			if items[nxt][2] == 0:
				nxt += 1
			elif items[nxt][2] >= d:
				items[nxt][2] -= d
				cost += d * items[nxt][0]
				d = 0
				if items[nxt][2] == 0:
					canpick -= 1
					nxt += 1
			else:
				cost += items[nxt][2] * items[nxt][0]
				d -= items[nxt][2]
				items[nxt][2] = 0
				canpick -= 1
				nxt += 1
		if d != 0:
			cost = 0
		firstnonempty = nxt
	print(cost)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
from heapq import *

def main():
	(n, m) = map(int, input().split())
	a = [*map(int, input().split())]
	c = [*map(int, input().split())]
	D = []
	for i in range(n):
		D.append([c[i], i])
	D.sort(key=lambda z: z[0])
	q = deque(D)
	for i in range(m):
		ans = 0
		(t, d) = map(int, input().split())
		t -= 1
		if a[t] > d:
			ans = d * c[t]
			a[t] -= d
			d = 0
		else:
			ans = a[t] * c[t]
			d -= a[t]
			a[t] = 0
			while q:
				if a[q[0][1]] >= d:
					ans += c[q[0][1]] * d
					a[q[0][1]] -= d
					d = 0
					if a[q[0][1]] == 0:
						q.popleft()
					break
				else:
					ans += c[q[0][1]] * a[q[0][1]]
					d -= a[q[0][1]]
					a[q[0][1]] = 0
					q.popleft()
		if d > 0:
			print(0)
		else:
			print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
import math
import bisect
MOD = int(1000000000.0 + 7)
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
c = list(map(int, input().split()))
cp = sorted(((y, x) for (x, y) in enumerate(c)))
pcp = 0
for i in range(m):
	(t, d) = list(map(int, input().split()))
	a[t - 1] -= d
	if a[t - 1] >= 0:
		print(d * c[t - 1])
	else:
		need = -a[t - 1]
		ans = (d - need) * c[t - 1]
		while pcp < n and need > 0:
			index = cp[pcp][-1]
			if a[index] > 0:
				if a[index] >= need:
					a[index] -= need
					ans += need * c[index]
					need = 0
				else:
					need -= a[index]
					ans += a[index] * c[index]
					a[index] = 0
			else:
				pcp += 1
		if need:
			print(0)
		else:
			a[t - 1] = 0
			print(ans)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
c = list(map(int, input().split()))
ss = [(i, c[i]) for i in range(n)]
ss = sorted(ss, key=lambda x: (x[1], x[0]))
p = 0
ans1 = []
for _ in range(m):
	(t, d) = list(map(int, input().split()))
	t -= 1
	ans = 0
	c1 = min(d, a[t])
	a[t] -= c1
	ans += c1 * c[t]
	d -= c1
	while d > 0 and p < n:
		nt = ss[p][0]
		nc = ss[p][1]
		c2 = min(a[nt], d)
		a[nt] -= c2
		d -= c2
		ans += nc * c2
		if a[nt] == 0:
			p += 1
	if d == 0:
		print(ans)
	else:
		print(0)


(n, m) = map(int, input().split())
A = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
O = [list(map(int, input().split())) for i in range(m)]
C2 = [[C[i + 1], i + 1] for i in range(n)]
C2.sort()
C2NOW = 0
for (f, d) in O:
	ANS = 0
	if A[f] >= d:
		ANS += C[f] * d
		A[f] -= d
		print(ANS)
		continue
	else:
		ANS += A[f] * C[f]
		d -= A[f]
		A[f] = 0
		while d > 0:
			if C2NOW == n:
				ANS = 0
				d = 0
				break
			if A[C2[C2NOW][1]] == 0:
				C2NOW += 1
				continue
			if A[C2[C2NOW][1]] >= d:
				ANS += d * C2[C2NOW][0]
				A[C2[C2NOW][1]] -= d
				d = 0
			else:
				ANS += A[C2[C2NOW][1]] * C2[C2NOW][0]
				d -= A[C2[C2NOW][1]]
				A[C2[C2NOW][1]] = 0
				C2NOW += 1
		print(ANS)


def main():
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	c = list(map(int, input().split()))
	price_index = []
	for i in range(n):
		price_index.append((c[i], i))
	price_index.sort()
	ptr = 0
	for _ in range(m):
		(t, d) = list(map(int, input().split()))
		t -= 1
		cost = 0
		if a[t] > 0:
			served_num = min(a[t], d)
			a[t] -= served_num
			d -= served_num
			cost += served_num * c[t]
		while ptr < n and d > 0:
			(_, index) = price_index[ptr]
			if a[index] == 0:
				ptr += 1
			served_num = min(a[index], d)
			a[index] -= served_num
			d -= served_num
			cost += served_num * c[index]
		if d > 0:
			print(0)
		else:
			print(cost)

def __starting_point():
	main()
__starting_point()


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
ic = [(i, c[i]) for i in range(n)]
ic.sort(key=lambda k: (k[1], k[0]))
ic_idx = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		a[t] -= d
		print(c[t] * d)
	else:
		ans = c[t] * a[t]
		d -= a[t]
		a[t] = 0
		while ic_idx < n:
			t2 = ic[ic_idx][0]
			if a[t2] >= d:
				ans += c[t2] * d
				a[t2] -= d
				d = 0
				break
			else:
				ans += c[t2] * a[t2]
				d -= a[t2]
				a[t2] = 0
				ic_idx += 1
		if d != 0:
			for _ in range(m - i):
				print(0)
			exit()
		print(ans)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
costs = sorted([(i, cost) for (i, cost) in enumerate(c)], key=lambda x: (x[1], x[0]))
co = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	price = 0
	if a[t] > d:
		price = d * c[t]
		a[t] -= d
	else:
		price = a[t] * c[t]
		d -= a[t]
		a[t] = 0
		while d > 0 and co < n:
			(ai, cost) = costs[co]
			if a[ai] > d:
				price += d * cost
				a[ai] -= d
				d = 0
			else:
				price += a[ai] * cost
				d -= a[ai]
				a[ai] = 0
				co += 1
		if d > 0:
			price = 0
	print(price)


from sys import stdin, stdout

def listIn():
	return [int(x) for x in stdin.readline().split()]

def stringListIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def stringIn():
	return stdin.readline()
(n, m) = listIn()
a = listIn()
c = listIn()
minn = float('inf')
flag = False
li = []
for i in range(n):
	li.append((c[i], i))
li.sort()
i = 0
for j in range(m):
	total = 0
	(t, d) = listIn()
	if a[t - 1] >= d:
		a[t - 1] -= d
		total += c[t - 1] * d
	else:
		total += c[t - 1] * a[t - 1]
		d -= a[t - 1]
		a[t - 1] = 0
		while i < n:
			cost = li[i][0]
			pos = li[i][1]
			val = a[pos]
			if val != 0:
				if val >= d:
					a[pos] -= d
					total += cost * d
					d = 0
					break
				else:
					total += cost * val
					a[pos] = 0
					d -= val
			i += 1
		if d != 0:
			total = 0
	stdout.write(str(total) + '\n')


from sys import stdin
(n, m) = map(int, stdin.readline().strip().split())
s1 = list(map(int, stdin.readline().strip().split()))
s2 = list(map(int, stdin.readline().strip().split()))
x = []
for i in range(n):
	x.append([s2[i], i, s1[i]])
x.sort()
pos = [-1 for i in range(n)]
y = 0
for i in range(n):
	pos[x[i][1]] = i

def sol(i):
	global b, y
	t = min(b, x[y][2])
	x[y][2] -= t
	b -= t
	ans = t * x[y][0]
	return ans
for j in range(m):
	ans = 0
	(a, b) = map(int, stdin.readline().strip().split())
	a -= 1
	t = min(b, x[pos[a]][2])
	ans += x[pos[a]][0] * t
	x[pos[a]][2] -= t
	b -= t
	while b > 0 and y < n:
		while y < n and x[y][2] == 0:
			y += 1
		if y < n:
			ans += sol(b)
	if b > 0:
		ans = 0
	print(ans)


import sys
from heapq import heappush, heappop, heapify

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

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

def input():
	return sys.stdin.readline().strip('\n')
(n, k) = get_ints()
khana = get_array()
rate = get_array()
paisa = [[j, i] for (i, j) in enumerate(rate)]
paisa.sort()
i = 0
for _ in range(k):
	(thali, plate) = get_ints()
	thali -= 1
	if khana[thali] >= plate:
		print(rate[thali] * plate)
		khana[thali] -= plate
	else:
		kharcha = khana[thali] * rate[thali]
		plate -= khana[thali]
		khana[thali] = 0
		while i < n:
			(rupaya, jagah) = (paisa[i][0], paisa[i][1])
			if khana[jagah] >= plate:
				kharcha += rate[jagah] * plate
				khana[jagah] -= plate
				plate = 0
				break
			else:
				kharcha += rate[jagah] * khana[jagah]
				plate -= khana[jagah]
				khana[jagah] = 0
			i += 1
		if plate == 0:
			print(kharcha)
		else:
			print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
ordered_cost = []
for i in range(n):
	ordered_cost.append([c[i], i])
ordered_cost.sort()
r = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	cost = 0
	if a[t] >= d:
		a[t] -= d
		cost += c[t] * d
	else:
		d -= a[t]
		cost += a[t] * c[t]
		a[t] = 0
		while d > 0:
			t = ordered_cost[r][1]
			if a[t] >= d:
				a[t] -= d
				cost += c[t] * d
				d = 0
			else:
				d -= a[t]
				cost += a[t] * c[t]
				a[t] = 0
				if r == n - 1:
					cost = 0
					break
				else:
					r += 1
	print(cost)


from collections import OrderedDict
(n, m) = list(map(int, input().split()))
an = list(map(int, input().split()))
cn = list(map(int, input().split()))
tmp = {}
for i in range(n):
	tmp[i] = cn[i]
tmp = sorted(tmp.items(), key=lambda x: x[1])
dic = OrderedDict(tmp)
key = list(dic.keys())
last = 0
for _ in range(m):
	res = 0
	(t, d) = list(map(int, input().split()))
	t -= 1
	if an[t] >= d:
		an[t] -= d
		res += d * cn[t]
		d = 0
	else:
		res += an[t] * cn[t]
		d -= an[t]
		an[t] = 0
		for ii in range(last, n):
			k = key[ii]
			if an[k] == 0:
				last += 1
				continue
			if an[k] >= d:
				an[k] -= d
				res += d * cn[k]
				d = 0
				break
			else:
				res += an[k] * cn[k]
				d -= an[k]
				an[k] = 0
				last += 1
	if d > 0:
		print(0)
	else:
		print(res)


class CodeforcesTask1106BSolution:

	def __init__(self):
		self.result = ''
		self.n_m = []
		self.stock = []
		self.prices = []
		self.customers = []

	def read_input(self):
		self.n_m = [int(x) for x in input().split(' ')]
		self.stock = [int(x) for x in input().split(' ')]
		self.prices = [int(x) for x in input().split(' ')]
		for x in range(self.n_m[1]):
			self.customers.append([int(y) for y in input().split(' ')])

	def process_task(self):
		results = []
		stock_pricing = [(self.prices[x], x) for x in range(self.n_m[0])]
		stock_pricing.sort(reverse=True)
		for customer in self.customers:
			cost = 0
			base_order = min(customer[1], self.stock[customer[0] - 1])
			rem = customer[1] - base_order
			cost += base_order * self.prices[customer[0] - 1]
			self.stock[customer[0] - 1] -= base_order
			while rem:
				if stock_pricing:
					cheap_order = min(self.stock[stock_pricing[-1][1]], rem)
					cost += cheap_order * stock_pricing[-1][0]
					self.stock[stock_pricing[-1][1]] -= cheap_order
					rem -= cheap_order
					if not self.stock[stock_pricing[-1][1]]:
						stock_pricing.pop(-1)
				else:
					cost = 0
					break
			results.append(cost)
		self.result = '\n'.join([str(x) for x in results])

	def get_result(self):
		return self.result
Solution = CodeforcesTask1106BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())


(n, m) = map(int, input().split())
quant = list(map(int, input().split()))
cost = list(map(int, input().split()))
index = [i for i in range(n)]
total = sum(quant)
z = list(map(list, zip(cost, index, quant)))
z.sort()
refdic = {}
for j in range(n):
	refdic[z[j][1]] = j
lowitem = 0
titem = 0
for j in range(m):
	money = 0
	(item, number) = map(int, input().split())
	if number > total:
		print(0)
		total = 0
		continue
	total -= number
	costid = refdic[item - 1]
	if z[costid][2] >= number:
		z[costid][2] -= number
		money += z[costid][0] * number
	else:
		number = number - z[costid][2]
		money += z[costid][0] * z[costid][2]
		z[costid][2] = 0
		while number > 0:
			if z[lowitem][2] >= number:
				z[lowitem][2] -= number
				money += z[lowitem][0] * number
				number = 0
			else:
				number = number - z[lowitem][2]
				money += z[lowitem][0] * z[lowitem][2]
				z[lowitem][2] = 0
				lowitem += 1
	print(money)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
c = list(map(int, input().split()))

def argsort(seq):
	return sorted(range(len(seq)), key=seq.__getitem__)
ind = argsort(c)
pos = 0
for i in range(m):
	sm = 0
	s = list(map(int, input().split()))
	(t, d) = (s[0], s[1])
	if d > a[t - 1]:
		d -= a[t - 1]
		sm += c[t - 1] * a[t - 1]
		a[t - 1] = 0
		if pos == n:
			sm = 0
		else:
			prepos = pos
			for j in range(pos, n):
				if d == 0:
					break
				e = min(d, a[ind[j]])
				d -= e
				sm += c[ind[j]] * e
				a[ind[j]] -= e
				prepos += 1
			pos = prepos - 1
			if d != 0:
				sm = 0
	else:
		sm += c[t - 1] * d
		a[t - 1] -= d
	print(sm)


from collections import *

def f():
	global e, d, r
	e = min(a[t], d)
	a[t] -= e
	d -= e
	r += x * e
R = lambda : [*map(int, input().split())]
(n, m) = R()
(a, c) = (R(), R())
b = deque(sorted(zip(c, range(n))))
for _ in [0] * m:
	(t, d) = R()
	t -= 1
	r = 0
	x = c[t]
	f()
	while d and b:
		(x, t) = b[0]
		f()
		if a[t] == 0:
			b.popleft()
	print((0, r)[d == 0])


(nDishes, nCustomers) = map(int, input().split())
rem = list(map(int, input().split()))
cost = list(map(int, input().split()))
minIdx = list(map(lambda x: x[1], sorted(((cost[i], i) for i in range(nDishes)))))
ptr = 0
for _ in range(nCustomers):
	(dish, count) = map(int, input().split())
	dish -= 1
	nOrdered = min(rem[dish], count)
	rem[dish] -= nOrdered
	paid = nOrdered * cost[dish]
	need = count - nOrdered
	while need > 0 and ptr < nDishes:
		curMin = minIdx[ptr]
		nextDish = min(rem[curMin], need)
		rem[curMin] -= nextDish
		need -= nextDish
		paid += nextDish * cost[curMin]
		if rem[curMin] == 0:
			ptr += 1
	print(paid if need == 0 else 0)


import copy
import fractions
import itertools
import numbers
import string
import sys

def powmod(x, p, m):
	if p <= 0:
		return 1
	if p <= 1:
		return x % m
	return powmod(x * x % m, p // 2, m) * (x % m) ** (p % 2) % m

def to_basex(num, x):
	while num > 0:
		yield (num % x)
		num //= x

def from_basex(it, x):
	ret = 0
	p = 1
	for d in it:
		ret += d * p
		p *= x
	return ret

def core():
	(n, m) = (int(x) for x in input().split())
	a = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	s = [(c[i], i) for i in range(n)]
	s.sort(reverse=True)
	for _ in range(m):
		if not s:
			print(0)
		else:
			(tj, dj) = (int(x) for x in input().split())
			tj -= 1
			if a[tj] >= dj:
				print(dj * c[tj])
				a[tj] -= dj
			else:
				bill = a[tj] * c[tj]
				dj -= a[tj]
				a[tj] = 0
				while dj > 0:
					if not s:
						bill = 0
						break
					if a[s[-1][1]] == 0:
						_ = s.pop()
					elif a[s[-1][1]] >= dj:
						bill += dj * c[s[-1][1]]
						a[s[-1][1]] -= dj
						dj = 0
					else:
						bill += a[s[-1][1]] * c[s[-1][1]]
						dj -= a[s[-1][1]]
						a[s[-1][1]] = 0
						_ = s.pop()
				print(bill)
core()


(n, m) = map(int, input().split())
dish = list(map(int, input().split()))
cost = list(map(int, input().split()))
scost = []
for i in range(n):
	scost.append([cost[i], dish[i], i])
scost = sorted(scost)
cur = 0
for i in range(m):
	(x, y) = map(int, input().split())
	x -= 1
	price = 0
	if dish[x] >= y:
		price += cost[x] * y
		dish[x] -= y
		y = 0
	else:
		price += cost[x] * dish[x]
		y -= dish[x]
		dish[x] = 0
		while y > 0:
			try:
				tmp = scost[cur][-1]
				if dish[tmp] >= y:
					price += cost[tmp] * y
					dish[tmp] -= y
					y = 0
				else:
					price += cost[tmp] * dish[tmp]
					y -= dish[tmp]
					dish[tmp] = 0
					cur += 1
			except IndexError:
				price = 0
				y = 0
	print(price)


(n, m) = map(int, input().split())
counts = list(map(int, input().split()))
costs = list(map(int, input().split()))
cost_with_ind = sorted([(y, x) for (x, y) in enumerate(costs)])
min_c = 0
for i in range(m):
	(t, c_n) = list(map(int, input().split()))
	t -= 1
	get_need = min(c_n, counts[t])
	counts[t] -= get_need
	c_n -= get_need
	local_cost = costs[t] * get_need
	while c_n != 0 and min_c < len(cost_with_ind):
		(_, index) = cost_with_ind[min_c]
		get_need = min(c_n, counts[index])
		counts[index] -= get_need
		c_n -= get_need
		local_cost += costs[index] * get_need
		if counts[index] == 0:
			min_c += 1
	if c_n:
		print(0)
	else:
		print(local_cost)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
(n, m) = ilele()
A = alele()
C = alele()
D = []
mark = {}
for i in range(1, n + 1):
	D.append((C[i - 1], i))
	mark[i] = A[i - 1]
D.sort()
D = deque(D)
for i in range(m):
	(t, c) = ilele()
	if not D:
		print(0)
	else:
		tot = mark[t]
		if tot >= c:
			mark[t] -= c
			print(c * C[t - 1])
		else:
			rem = c - mark[t]
			ans = mark[t] * C[t - 1]
			mark[t] = 0
			while D:
				z = mark[D[0][1]]
				if z == 0:
					D.popleft()
				elif z >= rem:
					mark[D[0][1]] -= rem
					ans += rem * D[0][0]
					rem = 0
					print(ans)
					break
				else:
					rem -= z
					mark[D[0][1]] = 0
					ans += z * D[0][0]
					D.popleft()
					if rem == 0:
						print(ans)
						break
			if rem != 0:
				print(0)


(n, m) = [int(s) for s in input().split(' ')]
amount = [int(s) for s in input().split(' ')]
cost = [int(s) for s in input().split(' ')]
t = [0 for i in range(m)]
d = [0 for i in range(m)]
real_cost = []
for i in range(m):
	(t[i], d[i]) = [int(s) for s in input().split(' ')]
cost_with_index = [(c, i) for (i, c) in enumerate(cost)]
sorted_index = sorted(cost_with_index, key=lambda x: (x[0], x[1]))
price_list = [atr[1] for atr in sorted_index]
cheepset = 0
dish_sum = sum(amount)
for i in range(m):
	now_kind = t[i] - 1
	now_need = d[i]
	now_cost = 0
	if amount[now_kind] > now_need:
		now_cost = now_need * cost[now_kind]
		amount[now_kind] -= now_need
		now_need = 0
	else:
		now_cost += amount[now_kind] * cost[now_kind]
		now_need -= amount[now_kind]
		amount[now_kind] = 0
		j = cheepset
		while now_need > 0 and j < n:
			if amount[price_list[j]] == 0:
				j += 1
				continue
			elif amount[price_list[j]] >= now_need:
				now_cost += now_need * cost[price_list[j]]
				amount[price_list[j]] -= now_need
				now_need = 0
			else:
				now_cost += amount[price_list[j]] * cost[price_list[j]]
				now_need -= amount[price_list[j]]
				amount[price_list[j]] = 0
		cheepset = j
	if now_need > 0:
		print(0)
	else:
		print(now_cost)


(m, n) = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
	a = [item, i, r[i - 1]]
	costa.append(a)
	i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
	dic[item[1]] = i
	i += 1
index = len(costa) - 1
for item in range(n):
	counter = 0
	(a, b) = [int(x) for x in input().split()]
	if r[a - 1] >= b:
		counter += cost[a - 1] * b
		r[a - 1] -= b
		costa[dic[a]][2] -= b
	else:
		i = index
		counter += cost[a - 1] * r[a - 1]
		costa[dic[a]][2] = 0
		b -= r[a - 1]
		r[a - 1] = 0
		while i >= 0:
			if costa[i][2] >= b:
				counter += costa[i][0] * b
				r[costa[i][1] - 1] -= b
				costa[i][2] -= b
				break
			else:
				counter += costa[i][0] * costa[i][2]
				r[costa[i][1] - 1] = 0
				index -= 1
				b -= costa[i][2]
				costa[i][2] = 0
			i -= 1
		else:
			counter = 0
	print(counter)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
pair = []
for i in range(len(c)):
	pair.append([c[i], i])
pair.sort()
cost = []
sry = 0
for cust in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		a[t] -= d
		cost.append(d * c[t])
	else:
		cost.append(a[t] * c[t])
		d -= a[t]
		a[t] = 0
		while d > 0:
			if sry == n:
				cost[-1] = 0
				break
			elif a[pair[sry][1]] >= d:
				a[pair[sry][1]] -= d
				cost[-1] += d * c[pair[sry][1]]
				d = 0
			else:
				cost[-1] += a[pair[sry][1]] * c[pair[sry][1]]
				d -= a[pair[sry][1]]
				a[pair[sry][1]] = 0
				sry += 1
for i in cost:
	print(i)


import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
	if flag == 0:
		return [int(i) for i in sys.stdin.readline().split()]
	else:
		return int(sys.stdin.readline())
(n, m) = ri()
a = ri()
c = ri()
hee = []
for i in range(n):
	heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
	cost = 0
	(t, d) = ri()
	t -= 1
	fm = 0
	if avail[t] >= d:
		avail[t] = avail[t] - d
		cost += d * c[t]
	else:
		rem = d - avail[t]
		cost = avail[t] * c[t]
		avail[t] = 0
		while rem > 0:
			try:
				(nowc, nowi) = heapq.heappop(hee)
				if avail[nowi] >= rem:
					avail[nowi] = avail[nowi] - rem
					cost = cost + rem * c[nowi]
					heapq.heappush(hee, (c[nowi], nowi))
					rem = 0
				else:
					cost = cost + avail[nowi] * c[nowi]
					mk = rem - avail[nowi]
					avail[nowi] = 0
					rem = mk
			except:
				fm = 1
				break
	if fm == 0:
		print(cost)
	else:
		print(0)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
s = [(i, c[i]) for i in range(n)]
s = sorted(s, key=lambda x: (x[1], x[0]))
cheapest = 0
for _ in range(m):
	cost = 0
	(t, d) = map(int, input().split())
	minimo = min(a[t - 1], d)
	cost += minimo * c[t - 1]
	a[t - 1] -= minimo
	d -= minimo
	while d > 0 and cheapest < n:
		i_min = s[cheapest][0]
		cost_min = s[cheapest][1]
		minimo = min(a[i_min], d)
		a[i_min] -= minimo
		cost += cost_min * minimo
		d -= minimo
		if a[i_min] == 0:
			cheapest += 1
	if d == 0:
		print(cost)
	else:
		print(0)


import sys
input = sys.stdin.readline
MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input().strip('\n'))
si = lambda : input().strip('\n')
dgl = lambda : list(map(int, input().strip('\n')))
f = lambda : map(int, input().strip('\n').split())
il = lambda : list(map(int, input().strip('\n').split()))
ls = lambda : list(input().strip('\n'))
let = 'abcdefghijklmnopqrstuvwxyz'
(n, m) = f()
count = il()
cost = [[j, i] for (i, j) in enumerate(il())]
d = dict()
cost.sort()
for i in range(n):
	d[cost[i][1]] = i
ind = 0
for _ in range(m):
	(kind, num) = f()
	x = min(num, count[kind - 1])
	num -= x
	count[kind - 1] -= x
	cst = x * cost[d[kind - 1]][0]
	while ind < n and num > 0:
		x = min(num, count[cost[ind][1]])
		num -= x
		count[cost[ind][1]] -= x
		cst += x * cost[ind][0]
		if count[cost[ind][1]] == 0:
			ind += 1
	if num == 0:
		print(cst)
	else:
		print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
dishlist = []
for i in range(n):
	dishlist.append([c[i], i])
dishlist.sort()
costrank = 0
for i in range(m):
	(n1, n2) = map(int, input().split())
	ans = 0
	if a[n1 - 1] >= n2:
		a[n1 - 1] -= n2
		ans += c[n1 - 1] * n2
	else:
		n2 -= a[n1 - 1]
		ans += a[n1 - 1] * c[n1 - 1]
		a[n1 - 1] = 0
		while n2 > 0:
			n1 = dishlist[costrank][1]
			if a[n1] >= n2:
				a[n1] -= n2
				ans += c[n1] * n2
				n2 = 0
			else:
				n2 -= a[n1]
				ans += a[n1] * c[n1]
				a[n1] = 0
				if costrank == n - 1:
					ans = 0
					break
				else:
					costrank += 1
	print(ans)


import sys
(n, m) = map(int, input().split())
dishes = list(map(int, input().split()))
costs = list(map(int, input().split()))
cheaper = [i for (i, v) in sorted(enumerate(costs), key=lambda x: (x[1], x[0]), reverse=True)]
ans = []
append = ans.append
for (t, d) in (map(int, l.split()) for l in sys.stdin):
	t -= 1
	count = min(d, dishes[t])
	price = costs[t] * count
	dishes[t] -= count
	d -= count
	while d and cheaper:
		t = cheaper[-1]
		count = min(d, dishes[t])
		dishes[t] -= count
		if not dishes[t]:
			cheaper.pop()
		price += costs[t] * count
		d -= count
	append(0 if d else price)
print(*ans, sep='\n')


(food_num, cus_num) = [int(i) for i in input().strip().split()]
food_dict = dict()
food_order = []
line1 = [int(i) for i in input().strip().split()]
line2 = [int(i) for i in input().strip().split()]
for i in range(1, food_num + 1):
	food_dict[i] = [line1[i - 1], line2[i - 1]]
food_order = sorted(food_dict, key=lambda x: (food_dict[x][1], x))
ans = 0
cheap_index = 0
done = False
for i in range(cus_num):
	ans = 0
	(kind, kind_num) = [int(i) for i in input().strip().split()]
	if cheap_index == food_num - 1 and food_dict[food_order[cheap_index]][0] <= 0:
		print(0)
	else:
		remain = food_dict[kind][0] - kind_num
		if remain >= 0:
			food_dict[kind][0] = remain
			print(kind_num * food_dict[kind][1])
		else:
			temp = food_dict[kind][0] * food_dict[kind][1]
			food_dict[kind][0] = 0
			remain = abs(remain)
			while remain >= 0:
				if cheap_index > food_num - 1:
					done = True
					break
				holder = remain
				remain = food_dict[food_order[cheap_index]][0] - remain
				if remain >= 0:
					food_dict[food_order[cheap_index]][0] = remain
					temp += holder * food_dict[food_order[cheap_index]][1]
					break
				else:
					remain = abs(remain)
					temp += food_dict[food_order[cheap_index]][0] * food_dict[food_order[cheap_index]][1]
					food_dict[food_order[cheap_index]][0] = 0
					cheap_index += 1
			if not done:
				ans += temp
				print(temp)
			else:
				print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
mc = sorted(((y, x) for (x, y) in enumerate(c)), reverse=True)
for _ in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		print(c[t] * d)
		a[t] -= d
	else:
		x = a[t] * c[t]
		d -= a[t]
		a[t] = 0
		while d:
			if not mc:
				print(0)
				break
			(cost, index) = mc[-1]
			if a[index] >= d:
				x += cost * d
				a[index] -= d
				d = 0
			else:
				x += cost * a[index]
				d -= a[index]
				a[index] = 0
			if a[index] == 0:
				mc.pop()
		else:
			print(x)


def main():
	(n, m) = map(int, input().split())
	remain = list(map(int, input().split()))
	cost = list(map(int, input().split()))
	stack = []
	for i in range(n):
		stack.append((cost[i], i))
	stack.sort()
	stack.reverse()
	for i in range(m):
		(t, d) = map(int, input().split())
		cst = 0
		if remain[t - 1] >= d:
			remain[t - 1] -= d
			cst += d * cost[t - 1]
		else:
			r = d - remain[t - 1]
			cst += remain[t - 1] * cost[t - 1]
			remain[t - 1] = 0
			while r != 0:
				if not stack:
					cst = 0
					break
				c = stack.pop()
				if remain[c[1]] >= r:
					cst += r * cost[c[1]]
					remain[c[1]] -= r
					r = 0
					if remain[c[1]] > 0:
						stack.append(c)
				else:
					r -= remain[c[1]]
					cst += remain[c[1]] * cost[c[1]]
					remain[c[1]] = 0
		print(cst)
main()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
C = [0] * m
P = []
for i in range(n):
	P.append((c[i], i))
P = sorted(P)
k = 0
for i in range(m):
	(t, d) = map(int, input().split())
	num = 0
	q = min(a[t - 1], d)
	a[t - 1] -= q
	num += q * c[t - 1]
	d -= q
	while d > 0 and k < n:
		q = min(a[P[k][1]], d)
		a[P[k][1]] -= q
		d -= q
		num += q * P[k][0]
		if a[P[k][1]] == 0:
			k += 1
	if d == 0:
		print(num)
	else:
		print(0)


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip('\r\n')
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
z = [(c[i], i) for i in range(n)]
z.sort()
z = deque(z)
for _ in range(m):
	(t, d) = map(int, input().split())
	ans = 0
	t -= 1
	k = min(d, a[t])
	a[t] -= k
	ans += k * c[t]
	d -= k
	while d > 0 and z:
		first = z[0]
		k = min(a[first[1]], d)
		a[first[1]] -= k
		d -= k
		ans += first[0] * k
		if not a[first[1]]:
			z.popleft()
	if not d:
		print(ans)
	else:
		print(0)


import math
import sys
import collections

def In():
	return map(int, sys.stdin.readline().split())
input = sys.stdin.readline

def lunarnew():
	(n, m) = In()
	dishes = list(In())
	cost = list(In())
	cheapest = sorted(enumerate(cost), key=lambda x: (x[1], x[0]))
	cheapos = 0
	for _ in range(m):
		if cheapos >= n:
			print(0)
			continue
		(kind, req) = In()
		kind -= 1
		maxhave = min(req, dishes[kind])
		req -= maxhave
		dishes[kind] -= maxhave
		c = maxhave * cost[kind]
		while req:
			while cheapos < n and (not dishes[cheapest[cheapos][0]]):
				cheapos += 1
			if cheapos >= n:
				c = 0
				break
			nowche = cheapest[cheapos][0]
			maxhave = min(req, dishes[nowche])
			c += maxhave * cost[nowche]
			dishes[nowche] -= maxhave
			req -= maxhave
			if req:
				cheapos += 1
		print(c)
lunarnew()


(n, m) = map(int, input().split())
aa = list(map(int, input().split()))
c = list(map(int, input().split()))
a = [(j, i) for (i, j) in enumerate(c)]
a.sort()
ans = []
su = 0
for _ in range(m):
	cost = 0
	(i, j) = map(int, input().split())
	if j > aa[i - 1]:
		cost += aa[i - 1] * c[i - 1]
		j -= aa[i - 1]
		aa[i - 1] = 0
	else:
		cost += j * c[i - 1]
		aa[i - 1] -= j
		j = 0
	ii = su
	while j > 0 and ii < n:
		(z, k) = a[ii]
		if aa[k] <= 0:
			ii += 1
			su = ii
			continue
		if j > aa[k]:
			cost += aa[k] * c[k]
			j -= aa[k]
			aa[k] = 0
		else:
			cost += j * c[k]
			aa[k] -= j
			j = 0
		ii += 1
	if ii == n and j != 0:
		cost = 0
	ans.append(cost)
print(*ans, sep='\n')


from collections import deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
pack = deque(sorted(enumerate(c), key=lambda x: x[1]))
total_earned = 0
for _ in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	price = 0
	is_break = False
	if a[t] >= d:
		a[t] -= d
		price = c[t] * d
	else:
		d -= a[t]
		price = c[t] * a[t]
		a[t] = 0
		while d > 0:
			while len(pack) > 0 and a[pack[0][0]] == 0:
				pack.popleft()
			if len(pack) == 0:
				is_break = True
				break
			alternative_idx = pack[0][0]
			alternative_count = min(a[alternative_idx], d)
			d -= alternative_count
			a[alternative_idx] -= alternative_count
			price += c[alternative_idx] * alternative_count
	if not is_break:
		total_earned += price
		print(price)
	else:
		print(0)


(n, m) = map(int, input().split())
a = [0, *map(int, input().split())]
c = [0, *map(int, input().split())]
il = [i for i in range(n + 1)]
ci = sorted(zip(c, il), key=lambda x: x[0], reverse=True)
for _ in range(m):
	(t, d) = map(int, input().split())
	if a[t] >= d:
		a[t] -= d
		print(d * c[t])
	else:
		d -= a[t]
		cost = a[t] * c[t]
		a[t] = 0
		ii = len(ci) - 2
		while ii >= 0:
			(cc, i) = ci[ii]
			if a[i] >= d:
				a[i] -= d
				cost += c[i] * d
				d = 0
				break
			else:
				cost += c[i] * a[i]
				d -= a[i]
				a[i] = 0
				ci.pop(ii)
				ii -= 1
		if d > 0:
			print(0)
		else:
			print(cost)


(n, m) = map(int, input().split())
rem = list(map(int, input().split()))
cos = list(map(int, input().split()))
co = [[cos[i], i] for i in range(n)]
co.sort()
ans = []
j = 0
for i in range(m):
	(b, a) = map(int, input().split())
	if rem[b - 1] >= a:
		rem[b - 1] -= a
		ans.append(cos[b - 1] * a)
	else:
		cost = 0
		a -= rem[b - 1]
		cost += rem[b - 1] * cos[b - 1]
		rem[b - 1] = 0
		while a > 0 and j < n:
			bb = co[j][1]
			if rem[bb] >= a:
				rem[bb] -= a
				ans.append(cost + cos[bb] * a)
				break
			else:
				a -= rem[bb]
				cost += rem[bb] * cos[bb]
				rem[bb] = 0
				j += 1
				if j == n:
					h = 0
					ans.append(0)
					j -= 1
					break
for i in ans:
	print(i)


(n, m) = map(int, input().split())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
arr3 = []
for i in range(n):
	arr3.append((arr2[i], i))
arr3.sort()
arr4 = [0] * n
ansarr = [0] * m
index = 0
for i in range(m):
	ans = 0
	count = 0
	(x, y) = map(int, input().split())
	if arr1[x - 1] >= y:
		count += y
		ans += y * arr2[x - 1]
		arr1[x - 1] -= y
		ansarr[i] = ans
	else:
		count += arr1[x - 1]
		ans += count * arr2[x - 1]
		arr1[x - 1] = 0
		while index < n and count < y:
			i1 = arr3[index][1]
			if count + arr1[i1] > y:
				diff = y - count
				count += diff
				ans += diff * arr2[i1]
				arr1[i1] -= diff
				break
			elif count + arr1[i1] == y:
				diff = y - count
				count += diff
				ans += diff * arr2[i1]
				arr1[i1] -= diff
				index += 1
				break
			else:
				ans += arr1[i1] * arr2[i1]
				count += arr1[i1]
				arr1[i1] = 0
				index += 1
		if index == n and count != y:
			ansarr[i] = 0
		else:
			ansarr[i] = ans
print(*ansarr)


import os
from io import BytesIO
if os.name == 'nt':
	input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	(n, m) = map(int, input().split())
	amounts = map(int, input().split())
	costs = map(int, input().split())
	dishes = [list(a) for a in zip(costs, range(n), amounts)]
	dishes.sort(key=lambda a: (a[0], a[1]))
	index_in_arr = {}
	for (ind, (_, number, _)) in enumerate(dishes):
		index_in_arr[number] = ind
	cur_replacement = 0
	for _ in range(m):
		(t, d) = map(int, input().split())
		t -= 1
		if cur_replacement == n:
			print(0)
			continue
		desired_index = index_in_arr[t]
		customer_cost = 0
		if desired_index >= cur_replacement:
			to_remove = min(d, dishes[desired_index][2])
			customer_cost += to_remove * dishes[desired_index][0]
			dishes[desired_index][2] -= to_remove
			d -= to_remove
		while d > 0:
			while cur_replacement < n and dishes[cur_replacement][2] == 0:
				cur_replacement += 1
			if cur_replacement == n:
				break
			to_remove = min(d, dishes[cur_replacement][2])
			customer_cost += to_remove * dishes[cur_replacement][0]
			dishes[cur_replacement][2] -= to_remove
			d -= to_remove
		print(customer_cost if d == 0 else 0)
main()


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

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

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))
MM = 10 ** 10
(n, m) = inpl()
a = inpl()
c = inpl()
q = []
for i in range(n):
	heappush(q, (c[i] * MM + i, i))
for i in range(m):
	(t, d) = inpl()
	t -= 1
	res = 0
	if not q:
		print(res)
		continue
	if a[t] < d:
		res += a[t] * c[t]
		d -= a[t]
		a[t] = 0
		while q:
			(key, ind) = heappop(q)
			if a[ind] == 0:
				continue
			if a[ind] < d:
				res += a[ind] * c[ind]
				d -= a[ind]
				a[ind] = 0
			else:
				res += d * c[ind]
				a[ind] -= d
				d = 0
				if a[ind] > 0:
					heappush(q, (key, ind))
				break
	else:
		res += d * c[t]
		a[t] -= d
		d = 0
	if d > 0:
		print(0)
	else:
		print(res)


(m, n) = map(int, input().split())
x = list(map(lambda a, b: [b, a[0], a[1]], enumerate(map(int, input().split())), map(int, input().split())))
y = sorted(x)
cur = 0
for _ in range(n):
	(a, b) = map(int, input().split())
	a -= 1
	bb = min(b, x[a][2])
	r = bb * x[a][0]
	b -= bb
	x[a][2] -= bb
	while b > 0:
		while cur < m and y[cur][2] == 0:
			cur += 1
		if cur == m:
			print(0)
			break
		bb = min(b, y[cur][2])
		r += bb * y[cur][0]
		b -= bb
		y[cur][2] -= bb
	else:
		print(r)


from sys import stdin, stdout
(n, m) = [int(x) for x in stdin.readline().split()]
a_list = [int(x) for x in stdin.readline().split()]
c_list = [int(x) for x in stdin.readline().split()]
c_list_with_index = []
for i in range(n):
	c_list_with_index.append([c_list[i]] + [i])
c_list_with_index.sort()
(starting_index, curr, broke) = (0, 0, True)
for i in range(m):
	total_cost = 0
	(t, d) = [int(x) for x in stdin.readline().split()]
	remaining = a_list[t - 1] - d
	broke = False
	if remaining > -1:
		total_cost += d * c_list[t - 1]
		a_list[t - 1] = remaining
		broke = True
	else:
		total_cost += c_list[t - 1] * a_list[t - 1]
		a_list[t - 1] = 0
		starting_index = curr
		for l in range(starting_index, n):
			remaining = abs(remaining)
			remaining = a_list[c_list_with_index[l][1]] - remaining
			if remaining > -1:
				total_cost += (a_list[c_list_with_index[l][1]] - remaining) * c_list[c_list_with_index[l][1]]
				a_list[c_list_with_index[l][1]] = remaining
				broke = True
				if remaining == 0:
					curr = l + 1
				break
			else:
				total_cost += c_list[c_list_with_index[l][1]] * a_list[c_list_with_index[l][1]]
				a_list[c_list_with_index[l][1]] = 0
				curr = l + 1
	stdout.write(str(total_cost) + '\n' if broke else '0\n')


(n, m) = map(int, input().split())
remain = list(map(int, input().split()))
price = list(map(int, input().split()))
product = sorted(list(zip(price, range(n))))
j = 0
for i in range(m):
	(index, quantity) = map(int, input().split())
	index -= 1
	total = 0
	while j < n:
		if remain[index] > 0:
			minimum = min(quantity, remain[index])
			total += minimum * price[index]
			quantity -= minimum
			remain[index] -= minimum
			if quantity == 0:
				break
		index = product[j][1]
		if remain[index] == 0:
			j += 1
	else:
		total = 0
	print(total)


import sys
(n, m) = [int(tmp) for tmp in sys.stdin.readline().split()]
a = [0] + [int(tmp) for tmp in sys.stdin.readline().split()]
c = [0] + [int(tmp) for tmp in sys.stdin.readline().split()]
co = [tmp for tmp in range(n + 1)]
co.sort(key=lambda z: c[z])
cop = 1
nb = False
for i in range(m):
	(t, d) = [int(tmp) for tmp in sys.stdin.readline().split()]
	if nb:
		print(0)
		continue
	s = 0
	botf = min([d, a[t]])
	a[t] -= botf
	s = botf * c[t]
	brts = d - botf
	while brts != 0:
		botf = min([brts, a[co[cop]]])
		if botf == 0:
			cop += 1
			if cop == n + 1:
				nb = True
				s = 0
				break
		a[co[cop]] -= botf
		brts -= botf
		s += botf * c[co[cop]]
	print(s)


(n, m) = map(int, input().split())
(left, prices) = (list(map(int, input().split())), list(map(int, input().split())))
options = [[left[i], prices[i]] for i in range(n)]
original = options.copy()
options.sort(key=lambda x: x[1])
cheapest = 0
empty = False
for _ in range(m):
	if empty:
		print(0)
		continue
	(t, d) = map(int, input().split())
	t -= 1
	curr = original[t]
	mc = d if d < curr[0] else curr[0]
	curr[0] -= mc
	d -= mc
	p = mc * curr[1]
	while d > 0:
		while cheapest < n and options[cheapest][0] == 0:
			cheapest += 1
		if cheapest == n:
			empty = True
			print(0)
			break
		curr = options[cheapest]
		mc = d if d < curr[0] else curr[0]
		curr[0] -= mc
		d -= mc
		p += mc * curr[1]
	else:
		print(p)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
newa = list()
total = 0
cost = list(map(int, input().split()))
counter = 0
for i in range(len(a)):
	newa.append([i, a[i], cost[i]])
	total += a[i]
newa = sorted(newa, key=lambda item: item[2])
for i in range(m):
	tempcost = 0
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		tempcost = d * cost[t]
		print(tempcost)
		total -= d
		a[t] -= d
	else:
		check = a[t]
		tempcost += a[t] * cost[t]
		a[t] = 0
		flag = 0
		if len(newa) == counter:
			flag = 1
		else:
			temp = newa[counter]
			while check < d:
				items = temp[1]
				key = temp[0]
				smaller = min(a[key], items, d - check)
				check += smaller
				if a[key] - smaller == 0:
					tempcost += smaller * cost[key]
					counter += 1
					a[key] = 0
					if counter != len(newa):
						temp = newa[counter]
					else:
						flag = 1
						break
				else:
					tempcost += smaller * cost[key]
					a[key] = a[key] - smaller
		if flag != 1 or check == d:
			print(tempcost)
		else:
			print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
h = []
d = {}
for i in range(len(a)):
	if c[i] not in d:
		d[c[i]] = []
	d[c[i]].append((a[i], i))
for i in sorted(d, reverse=True):
	for j in sorted(d[i]):
		h.append((i, *j))
for i in range(m):
	(t, d) = map(int, input().split())
	cost = 0
	if d <= a[t - 1]:
		a[t - 1] -= d
		print(c[t - 1] * d)
		continue
	cost += c[t - 1] * a[t - 1]
	d -= a[t - 1]
	a[t - 1] = 0
	flag = 0
	while d > 0:
		if not h:
			print(0)
			flag = 1
			break
		(save, save1, m1) = h.pop()
		if d <= a[m1]:
			a[m1] -= d
			cost += c[m1] * d
			h.append((save, save1, m1))
			break
		cost += c[m1] * a[m1]
		d -= a[m1]
		a[m1] = 0
	if flag:
		continue
	print(cost)


(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
c = [[i[1], a[i[0]], i[0]] for i in enumerate(map(int, input().split()))]
c.sort(key=lambda x: x[0])
del a
s = [0] * n
for i in range(n):
	s[c[i][2]] = i
ukaz = 0
for i in range(m):
	if ukaz == n:
		print(0)
		continue
	(typ, col) = map(int, input().split())
	typ -= 1
	schet = 0
	if c[s[typ]][1] >= col:
		c[s[typ]][1] -= col
		schet = c[s[typ]][0] * col
		col = 0
	else:
		col -= c[s[typ]][1]
		schet = c[s[typ]][1] * c[s[typ]][0]
		c[s[typ]][1] = 0
	while ukaz < n:
		if c[ukaz][1] == 0:
			ukaz += 1
			continue
		elif c[ukaz][1] >= col:
			c[ukaz][1] -= col
			schet += c[ukaz][0] * col
			col = 0
			break
		else:
			col -= c[ukaz][1]
			schet += c[ukaz][1] * c[ukaz][0]
			c[ukaz][1] = 0
			ukaz += 1
	if col != 0:
		print(0)
	else:
		print(schet)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
f = list()
for i in range(n):
	f.append((c[i], i))
f.sort()
low = 0
for i in range(m):
	(t, d) = map(int, input().split())
	r = 0
	j = min(d, a[t - 1])
	a[t - 1] -= j
	r += j * c[t - 1]
	j = d - j
	while j > 0 and low < n:
		while low < n and a[f[low][1]] == 0:
			low += 1
		if low == n:
			break
		k = min(j, a[f[low][1]])
		j -= k
		a[f[low][1]] -= k
		r += k * f[low][0]
	if j == 0:
		print(r)
	else:
		print(0)


def serve(a, c, nb, typ):
	fact = 0
	if nb <= a[typ]:
		a[typ] -= nb
		fact += c[typ] * nb
		return (a, 0, fact)
	elif a[typ] > 0:
		nb -= a[typ]
		fact += c[typ] * a[typ]
		a[typ] = 0
		return (a, nb, fact)
	else:
		return (a, nb, 0)
(n, m) = tuple(map(int, input().split(' ')))
t = [0 for _ in range(0, m + 1)]
d = [0 for _ in range(0, m + 1)]
a = [0] + list(map(int, input().split(' ')))
c = [0] + list(map(int, input().split(' ')))
for cost in range(1, m + 1):
	(tt, dd) = tuple(map(int, input().split(' ')))
	t[cost] = tt
	d[cost] = dd
order = list(range(0, len(c)))
order.sort(key=lambda i: c[i])
cost = 1
open = True
i_dish_rep = 0
while cost <= m:
	if not open:
		print(0)
	else:
		fact = 0
		(a, nb, f) = serve(a, c, d[cost], t[cost])
		fact += f
		if nb == 0:
			print(fact)
		else:
			while nb > 0 and open:
				while a[order[i_dish_rep]] == 0:
					i_dish_rep += 1
					if i_dish_rep > n:
						print(0)
						open = False
						break
				if not open:
					break
				else:
					(a, nb, f) = serve(a, c, nb, order[i_dish_rep])
					fact += f
			if open:
				print(fact)
	cost += 1


def dishes(f, c, orders):
	arr = []
	n = len(f)
	for i in range(n):
		arr.append([c[i], i, f[i]])
	arr.sort()
	beg = 0
	indices = [0 for i in range(n)]
	for i in range(n):
		indices[arr[i][1]] = i
	j = 0
	for order in orders:
		f = order[1]
		i = indices[order[0]]
		cursum = 0
		min_el = min(arr[i][2], f)
		cursum += min_el * arr[i][0]
		f -= min_el
		arr[i][2] -= min_el
		while f > 0 and beg < n:
			min_el = min(arr[beg][2], f)
			cursum += min_el * arr[beg][0]
			f -= min_el
			arr[beg][2] -= min_el
			if arr[beg][2] == 0:
				beg += 1
		if beg == n and f > 0:
			print(0)
		else:
			print(cursum)
line = input()
line = line.split()
n = int(line[0])
m = int(line[1])
line = input()
food = [int(i) for i in line.split()]
line = input()
cost = [int(i) for i in line.split()]
orders = []
for i in range(m):
	line = input()
	orders.append([int(i) for i in line.split()])
	orders[i][0] -= 1
dishes(food, cost, orders)


(n, m) = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
	pr = 0
	(bl, kol) = list(map(int, input().split()))
	bl -= 1
	if ost[bl] >= kol:
		pr = kol * price[bl]
		ost[bl] -= kol
	else:
		kol -= ost[bl]
		pr = ost[bl] * price[bl]
		ost[bl] = 0
		while kol > 0:
			if minost == n:
				pr = 0
				break
			minbl = minprice[minost][1]
			if ost[minbl] >= kol:
				pr += kol * price[minbl]
				ost[minbl] -= kol
				kol = 0
			else:
				kol -= ost[minbl]
				pr += ost[minbl] * price[minbl]
				ost[minbl] = 0
				minost += 1
				if minost == n:
					pr = 0
					break
	print(pr)


import sys
stdin = sys.stdin
sys.setrecursionlimit(10 ** 5)

def li():
	return map(int, stdin.readline().split())

def li_():
	return map(lambda x: int(x) - 1, stdin.readline().split())

def lf():
	return map(float, stdin.readline().split())

def ls():
	return stdin.readline().split()

def ns():
	return stdin.readline().rstrip()

def lc():
	return list(ns())

def ni():
	return int(stdin.readline())

def nf():
	return float(stdin.readline())
from collections import deque
(n, m) = li()
a = list(li())
c = list(li())
dic = {idx: ai for (idx, ai) in enumerate(a)}
cord = [idx for (_, idx) in sorted([(ci, idx) for (idx, ci) in enumerate(c)])]
cord = deque(cord)
for _ in range(m):
	(dish, num) = li()
	dish -= 1
	ans = 0
	if num <= dic[dish]:
		dic[dish] -= num
		ans = c[dish] * num
		print(ans)
	else:
		ans = c[dish] * dic[dish]
		num -= dic[dish]
		dic[dish] = 0
		while num > 0:
			if cord:
				nex = cord.popleft()
			else:
				ans = 0
				num = 0
			if dic[nex] > num:
				ans += c[nex] * num
				dic[nex] -= num
				cord.appendleft(nex)
				num = 0
			elif dic[nex] == num:
				ans += c[nex] * num
				dic[nex] = 0
				num = 0
			else:
				ans += c[nex] * dic[nex]
				num -= dic[nex]
				dic[nex] = 0
		print(ans)


from collections import defaultdict
import operator
(n, m) = map(int, input().split())
remain = defaultdict(int)
cost = {}
k = list(map(int, input().split()))
v = list(map(int, input().split()))
for i in range(n):
	remain[i] = k[i]
	cost[i] = v[i]
sorted_d = sorted(cost.items(), key=operator.itemgetter(1))
start = 0
for i in range(m):
	(t, d) = map(int, input().split())
	c = 0
	if remain[t - 1] >= d:
		remain[t - 1] -= d
		c += cost[t - 1] * d
	else:
		r = d - remain[t - 1]
		c += cost[t - 1] * remain[t - 1]
		remain[t - 1] = 0
		while r > 0:
			if start == n:
				c = 0
				break
			if remain[sorted_d[start][0]] > 0:
				if remain[sorted_d[start][0]] >= r:
					c += cost[sorted_d[start][0]] * r
					remain[sorted_d[start][0]] -= r
					r = 0
				else:
					c += cost[sorted_d[start][0]] * remain[sorted_d[start][0]]
					r -= remain[sorted_d[start][0]]
					remain[sorted_d[start][0]] = 0
					start += 1
			else:
				start += 1
	print(c)


class Heap:

	def __init__(self, arr, key=None, heap_type='min'):
		self.arr = arr
		self.key = key
		self.heap_type = heap_type
		if key == None:
			self.key = lambda x: x
		self.heapify()

	def __repr__(self):
		return str(self.arr)

	def __compare(self, index1, index2):
		return self.__compare_keys(self[index1], self[index2])

	def __compare_keys(self, key1, key2):
		ans = 0
		if key1 > key2:
			ans = 1
		elif key1 < key2:
			ans = -1
		else:
			ans = 0
		return ans if self.heap_type == 'min' else -1 * ans

	def heapify(self):
		for i in range(0, len(self)):
			self.__bubble_up(i)

	def insert(self, item):
		self.arr.append(item)
		self.__bubble_up(len(self) - 1)

	def __getitem__(self, index):
		return self.key(self.arr[index])

	def __bubble_up(self, index):
		parent = (index - 1) // 2
		while parent >= 0 and self.__compare(index, parent) == -1:
			(self.arr[parent], self.arr[index]) = (self.arr[index], self.arr[parent])
			(index, parent) = (parent, (parent - 1) // 2)

	def __bubble_down(self, index):
		high = len(self)
		while True:
			(l, r) = (index * 2 + 1, index * 2 + 2)
			if r < high:
				if self.__compare(r, l) == -1:
					if self.__compare(r, index) >= 0:
						break
					(self.arr[r], self.arr[index]) = (self.arr[index], self.arr[r])
					index = r
				else:
					if self.__compare(l, index) >= 0:
						break
					(self.arr[l], self.arr[index]) = (self.arr[index], self.arr[l])
					index = l
			elif l < high:
				if self.__compare(l, index) >= 0:
					break
				(self.arr[l], self.arr[index]) = (self.arr[index], self.arr[l])
				break
			else:
				break

	def __len__(self):
		return len(self.arr)

	def pop(self):
		(self.arr[0], self.arr[-1]) = (self.arr[-1], self.arr[0])
		top = self.arr.pop(-1)
		self.__bubble_down(0)
		return top
(n, m) = map(int, input().split())
avail = list(map(int, input().split()))
cost = list(map(int, input().split()))
orders = [tuple(map(int, input().split())) for _ in range(m)]
cost_index = Heap([(cost_i, index_i) for (cost_i, index_i) in zip(cost, range(n))])
ans = []
for (d, k) in orders:
	d = d - 1
	total = 0
	while k != 0:
		if avail[d] > 0:
			if avail[d] >= k:
				total += cost[d] * k
				avail[d] -= k
				k -= k
			else:
				total += cost[d] * avail[d]
				k -= avail[d]
				avail[d] = 0
		elif len(cost_index) == 0:
			total = 0
			break
		else:
			while k != 0 and len(cost_index) > 0:
				(_, d) = cost_index.pop()
				if avail[d] > 0:
					if avail[d] >= k:
						total += cost[d] * k
						avail[d] -= k
						k -= k
						cost_index.insert((cost[d], d))
					else:
						total += cost[d] * avail[d]
						k -= avail[d]
						avail[d] = 0
			if k == 0:
				break
			else:
				total = 0
				break
	ans.append(str(total))
print('\n'.join(ans))


(n, m) = map(int, input().split())
dishes = list(map(int, input().split()))
prices = list(map(int, input().split()))
minPrice = [[prices[i], i] for i in range(len(prices))]
minPrice = sorted(minPrice)
index = 0
for i in range(m):
	(food, amount) = map(int, input().split())
	food -= 1
	cost = 0
	if dishes[food] >= amount:
		dishes[food] -= amount
		cost = prices[food] * amount
	else:
		amount -= dishes[food]
		cost = prices[food] * dishes[food]
		dishes[food] = 0
		while amount > 0:
			if index == n:
				cost = 0
				break
			minimum = minPrice[index][1]
			if dishes[minimum] >= amount:
				dishes[minimum] -= amount
				cost += prices[minimum] * amount
				amount = 0
			else:
				amount -= dishes[minimum]
				cost += prices[minimum] * dishes[minimum]
				dishes[minimum] = 0
				index += 1
				if index == n:
					cost = 0
					break
	print(cost)


(n, m) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
sorted = [i[0] for i in sorted(enumerate(c), key=lambda x: x[1])]
chipest = 0
for i in range(m):
	result = 0
	(t, d) = [int(i) for i in input().split()]
	t -= 1
	if d < a[t]:
		result += c[t] * d
		a[t] -= d
		d = 0
	else:
		result += c[t] * a[t]
		d -= a[t]
		a[t] = 0
		while d != 0:
			if chipest >= n:
				result = 0
				break
			if d < a[sorted[chipest]]:
				result += c[sorted[chipest]] * d
				a[sorted[chipest]] -= d
				d = 0
			else:
				result += c[sorted[chipest]] * a[sorted[chipest]]
				d -= a[sorted[chipest]]
				a[sorted[chipest]] = 0
				chipest += 1
	print(result)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
ss = [(i, c[i]) for i in range(n)]
ss = sorted(ss, key=lambda x: (x[1], x[0]))
fk = 0
for i in range(m):
	(t, d) = map(int, input().split())
	ans = 0
	dish = min(a[t - 1], d)
	a[t - 1] -= dish
	ans += c[t - 1] * dish
	d -= dish
	while d > 0 and fk < n:
		nt = ss[fk][0]
		nc = ss[fk][1]
		dish2 = min(a[nt], d)
		a[nt] -= dish2
		d -= dish2
		ans += nc * dish2
		if a[nt] == 0:
			fk += 1
	print(ans if d == 0 else 0)


(m, n) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
dic2 = {}
dic = {}
for i in range(m):
	dic2[i + 1] = [c[i], a[i]]
ss = sorted(dic2.items(), key=lambda kv: kv[1][0])
for i in ss:
	dic[i[0]] = i[1]
items = list(dic.keys())
shoro = 0
ans = ''
for i in range(n):
	sum = 0
	(t, d) = map(int, input().split())
	x = min(dic[t][1], d)
	dic[t][1] -= x
	sum += x * dic[t][0]
	d -= x
	if d > 0:
		for j in range(shoro, len(items)):
			if dic[items[j]][1] == 0:
				shoro += 1
				continue
			x = min(dic[items[j]][1], d)
			dic[items[j]][1] -= x
			sum += x * dic[items[j]][0]
			d -= x
			if d == 0:
				break
	if d != 0:
		sum = 0
	ans += str(sum) + '\n'
print(ans)


(n, m) = list(map(int, input().lstrip().split(' ')))
a = list(map(int, input().lstrip().split(' ')))
c = list(map(int, input().lstrip().split(' ')))
costs = sorted([(i, cost) for (i, cost) in enumerate(c)], key=lambda x: (x[1], x[0]))
ci = 0
for _ in range(m):
	cost = 0
	(t, d) = list(map(int, input().lstrip().split(' ')))
	t -= 1
	if a[t] > d:
		cost = d * c[t]
		a[t] -= d
	else:
		cost = a[t] * c[t]
		d -= a[t]
		a[t] = 0
		while d > 0 and ci < n:
			(ai, _cost) = costs[ci]
			if a[ai] > d:
				cost += d * _cost
				a[ai] -= d
				d = 0
			else:
				cost += a[ai] * _cost
				d -= a[ai]
				a[ai] = 0
				ci += 1
		if d > 0:
			cost = 0
	print(cost)


(n, m) = map(int, input().split())
a = [int(j) for j in input().split()]
c = [int(j) for j in input().split()]
arr = [0 for j in range(n)]
for x in range(n):
	arr[x] = [c[x], a[x], x]
arr.sort()
var = 0
cheap = 0
for i in range(m):
	if var == 1:
		print(0)
		continue
	cost = 0
	(food, no) = map(int, input().split())
	food -= 1
	while no != 0:
		if no != 0 and cheap == n and (arr[cheap - 1][1] == 0):
			var = 1
			cost = 0
			break
		if a[food] >= no:
			a[food] -= no
			cost += c[food] * no
			no = 0
			break
		else:
			no -= a[food]
			cost += c[food] * a[food]
			a[food] = 0
		while a[arr[cheap][2]] == 0:
			arr[cheap][1] = a[arr[cheap][2]]
			cheap += 1
			if cheap == n:
				break
		if cheap != n:
			food = arr[cheap][2]
	print(cost)


def read_nums():
	return [int(x) for x in input().split()]

def main():
	(num_foods, num_customers) = read_nums()
	available = read_nums()
	cost = read_nums()
	cheapest_foods = list(map(lambda x: x[0], sorted(enumerate(cost), key=lambda x: x[1] * 999999999 + x[1])))
	index_of_cheapest_food_index = 0
	for _ in range(num_customers):
		(i, d) = read_nums()
		i -= 1
		res = 0
		while available[i] > 0 and d > 0:
			take = min(available[i], d)
			available[i] -= take
			res += cost[i] * take
			d -= take
		while d > 0 and index_of_cheapest_food_index < len(cheapest_foods):
			if available[cheapest_foods[index_of_cheapest_food_index]] > 0:
				take = min(d, available[cheapest_foods[index_of_cheapest_food_index]])
				available[cheapest_foods[index_of_cheapest_food_index]] -= take
				res += cost[cheapest_foods[index_of_cheapest_food_index]] * take
				d -= take
			else:
				index_of_cheapest_food_index += 1
		if d > 0:
			res = 0
		print(res)
main()


(kinds, num) = [int(x) for x in input().split()]
remains = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
sorted_cost = []
for t in range(kinds):
	sorted_cost.append([cost[t], t])
sorted_cost.sort()
min_recorder = 0
min_cost_index = sorted_cost[min_recorder][1]
ran_out = False
for x in range(num):
	if ran_out:
		print(0)
		continue
	bill = 0
	(dish_type, dish_amount) = [int(y) for y in input().split()]
	dish_type -= 1
	ori_val = remains[dish_type]
	if ori_val > 0:
		deduct = ori_val - dish_amount
		if deduct < 0:
			dish_amount = -deduct
			bill += cost[dish_type] * ori_val
			remains[dish_type] = 0
		else:
			bill += cost[dish_type] * dish_amount
			remains[dish_type] = deduct
			print(bill)
			continue
	while True:
		while remains[min_cost_index] == 0:
			min_recorder += 1
			if min_recorder == kinds:
				ran_out = True
				print(0)
				break
			min_cost_index = sorted_cost[min_recorder][1]
		if ran_out == True:
			break
		val = remains[min_cost_index]
		deduct = val - dish_amount
		if deduct < 0:
			bill += cost[min_cost_index] * val
			remains[min_cost_index] = 0
			dish_amount = -deduct
		else:
			bill += cost[min_cost_index] * dish_amount
			remains[min_cost_index] = deduct
			print(bill)
			break


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
z = list(range(n))
d = []
for (i, j, k) in zip(a, c, z):
	d.append([j, i, k])
d.sort(key=lambda x: -x[0])
for i in range(m):
	(x, y) = map(int, input().split())
	x -= 1
	ans = 0
	if a[x]:
		if a[x] >= y:
			print(c[x] * y)
			a[x] -= y
			continue
		else:
			ans += a[x] * c[x]
			y -= a[x]
			a[x] = 0
	while d and y > 0:
		(q, w, e) = d.pop()
		w = a[e]
		if w >= y:
			ans += q * y
			a[e] = w - y
			y = 0
			d.append([q, w - y, e])
		else:
			ans += w * q
			a[e] = 0
			y -= w
	if y:
		print(0)
	else:
		print(ans)


import collections
import time
import os
import sys
import bisect
import heapq
(N, M) = map(int, input().split())
A = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
cheapest = [(c, i + 1) for (i, c) in enumerate(C)]
cheapest.sort()
cheapest = [i for (c, i) in cheapest]
counts = {i + 1: v for (i, v) in enumerate(A)}
costs = {i + 1: c for (i, c) in enumerate(C)}
ans = []
ci = 0
for i in range(M):
	(t, d) = map(int, input().split())
	count = counts[t]
	if count > d:
		counts[t] -= d
		ans.append(costs[t] * d)
	else:
		counts[t] = 0
		cost = costs[t] * count
		d -= count
		while ci < len(cheapest):
			dish = cheapest[ci]
			count = counts[dish]
			if count >= d:
				counts[dish] -= d
				cost += d * costs[dish]
				d = 0
				break
			else:
				counts[dish] = 0
				d -= count
				cost += count * costs[dish]
				ci += 1
		cost = 0 if d > 0 else cost
		ans.append(cost)
print('\n'.join(map(str, ans)))


import sys
from collections import deque
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input().split()))
ip = lambda : input()
fi = lambda : float(input())
li = lambda : list(input())
pr = lambda x: print(x)
(n, m) = il()
a = il()
c = il()
z = [[c[i], i] for i in range(n)]
z.sort()
z = deque(z)
for _ in range(m):
	(x, y) = il()
	ans = 0
	x -= 1
	t = min(y, a[x])
	a[x] -= t
	ans += t * c[x]
	y -= t
	while y > 0 and z:
		f = z[0]
		t = min(a[f[1]], y)
		a[f[1]] -= t
		y -= t
		ans += f[0] * t
		if a[f[1]] == 0:
			z.popleft()
	if y == 0:
		print(ans)
	else:
		print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
cl = []
for i in range(n):
	cl.append([c[i], i])

def fun(itm):
	return itm[0]
cl.sort(key=fun)
idx = 0
for i in range(m):
	(x, y) = map(int, input().split())
	x -= 1
	cost = 0
	if a[x] >= y:
		a[x] -= y
		cost += c[x] * y
		y = 0
	else:
		cost += c[x] * a[x]
		y -= a[x]
		a[x] = 0
		flag = 0
		while idx < n and y > 0:
			if a[cl[idx][1]] >= y:
				a[cl[idx][1]] -= y
				cost += cl[idx][0] * y
				y = 0
				flag = 1
			else:
				cost += cl[idx][0] * a[cl[idx][1]]
				y -= a[cl[idx][1]]
				a[cl[idx][1]] = 0
				idx += 1
		if flag == 0:
			cost = 0
	print(cost)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
l = []
for i in range(len(c)):
	l.append((c[i], i))
l.sort()
ptr = 0
for i in range(m):
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] >= d:
		a[t] = a[t] - d
		ans = c[t] * d
		sys.stdout.write(str(ans) + '\n')
	elif ptr == n:
		sys.stdout.write('0\n')
	else:
		ans = c[t] * a[t]
		d = d - a[t]
		a[t] = 0
		while ptr < n and d > 0:
			if a[l[ptr][1]] > 0:
				cost = l[ptr][0]
				if d > a[l[ptr][1]]:
					d = d - a[l[ptr][1]]
					ans = ans + a[l[ptr][1]] * cost
					a[l[ptr][1]] = 0
					ptr += 1
				else:
					a[l[ptr][1]] -= d
					ans = ans + cost * d
					d = 0
			else:
				ptr += 1
		if ptr == n and d > 0:
			sys.stdout.write('0\n')
		else:
			sys.stdout.write(str(ans) + '\n')


def main():
	nm = list(map(int, input().split()))
	n = nm[0]
	m = nm[1]
	count = list(map(int, input().split()))
	princes = list(map(int, input().split()))
	pairs = []
	for i in range(n):
		pairs.append(Pair(princes[i], i))
	pairs.sort(key=pred)
	j = 0
	for i in range(m):
		td = list(map(int, input().split()))
		t = td[0]
		d = td[1]
		sum = 0
		if count[t - 1] >= d:
			count[t - 1] -= d
			print(d * princes[t - 1])
			continue
		else:
			sum += count[t - 1] * princes[t - 1]
			d -= count[t - 1]
			count[t - 1] = 0
		while j < len(pairs):
			pair = pairs[j]
			if count[pair.b] >= d:
				count[pair.b] -= d
				sum += d * princes[pair.b]
				d = 0
				break
			else:
				d -= count[pair.b]
				sum += count[pair.b] * princes[pair.b]
				count[pair.b] = 0
				j += 1
		if d == 0:
			print(sum)
		else:
			print(0)

def pred(elem):
	return elem.a

class Pair:

	def __init__(self, a, b):
		self.a = a
		self.b = b
main()


def sortf(a, b):
	if a[0] < b[0]:
		return True
	elif a[0] == b[0]:
		return True if a[1] <= b[1] else False
	else:
		return False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
mins = [[c[i], i, a[i]] for i in range(n)]
mins.sort(key=lambda x: x[0])
h = {}
for i in range(n):
	h[mins[i][1]] = i
j = 0
for i in range(m):
	cost = 0
	(t, d) = map(int, input().split())
	t -= 1
	if a[t] < d:
		cost += c[t] * a[t]
		d -= a[t]
		mins[h[t]][2] -= a[t]
		a[t] = 0
		while d > 0 and j < n:
			if mins[j][2] != 0:
				k = min(mins[j][2], d)
				cost += mins[j][0] * k
				a[mins[j][1]] -= k
				mins[j][2] -= k
				d -= k
				j += 1 if mins[j][2] == 0 else 0
			else:
				j += 1
		if d == 0:
			print(cost)
		else:
			print(0)
	else:
		cost += c[t] * d
		a[t] -= d
		mins[h[t]][2] -= d
		print(cost)


from collections import OrderedDict
(n, m) = map(int, input().split())
a = map(int, input().split())
c = map(int, input().split())
dishes = map(list, zip(a, c))
sorted_dishes = sorted(list(zip(range(n), dishes)), key=lambda dish: dish[1][1])
keys = [dish[0] for dish in sorted_dishes]
sorted_dishes = OrderedDict(list(sorted_dishes))
min_dish = 0
while m:
	count = 0
	(index, dish) = map(int, input().split())
	while dish and min_dish < len(keys):
		if sorted_dishes[index - 1][0] > 0:
			rest = sorted_dishes[index - 1][0] - dish
			if rest > 0:
				count += sorted_dishes[index - 1][1] * dish
				sorted_dishes[index - 1][0] = rest
				break
			count += sorted_dishes[index - 1][0] * sorted_dishes[index - 1][1]
			dish -= sorted_dishes[index - 1][0]
			sorted_dishes[index - 1][0] = 0
		elif index != keys[min_dish] + 1:
			index = keys[min_dish] + 1
		else:
			min_dish += 1
			if min_dish >= len(keys):
				break
			index = keys[min_dish] + 1
	if min_dish >= len(keys):
		print(0)
	else:
		print(count)
	m -= 1


(n, m) = map(int, input().split())
dish = list(map(int, input().split()))
cost = list(map(int, input().split()))
arr = []
for i in range(n):
	arr.append([i, cost[i]])
arr = sorted(arr, key=lambda x: (x[1], x[0]))
ans = [0] * m
j = 0
flag = False
for k in range(m):
	(i, qty) = map(int, input().split())
	c = 0
	i -= 1
	if qty > dish[i]:
		qty -= dish[i]
		c += dish[i] * cost[i]
		dish[i] = 0
		while qty != 0:
			if j == n:
				flag = True
				break
			if qty > dish[arr[j][0]]:
				c += dish[arr[j][0]] * cost[arr[j][0]]
				qty -= dish[arr[j][0]]
				dish[arr[j][0]] = 0
				j += 1
			elif qty == dish[arr[j][0]]:
				dish[arr[j][0]] = 0
				c += qty * cost[arr[j][0]]
				qty = 0
				j += 1
			else:
				c += qty * cost[arr[j][0]]
				dish[arr[j][0]] -= qty
				qty = 0
	else:
		c = qty * cost[i]
		dish[i] -= qty
		qty = 0
	if flag:
		break
	ans[k] = c
for i in ans:
	print(i)