Polycarp wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.

After that, he erased some letters from the string $s$, and he rewrote the remaining letters in any order. As a result, he got some new string $t$. You have to find it with some additional information.

Suppose that the string $t$ has length $m$ and the characters are numbered from left to right from $1$ to $m$. You are given a sequence of $m$ integers: $b_1, b_2, \ldots, b_m$, where $b_i$ is the sum of the distances $|i-j|$ from the index $i$ to all such indices $j$ that $t_j > t_i$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $b_i$, Polycarp finds all such indices $j$ that the index $j$ contains a letter that is later in the alphabet than $t_i$ and sums all the values $|i-j|$.

For example, if $t$ = "abzb", then:  since $t_1$='a', all other indices contain letters which are later in the alphabet, that is: $b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$;  since $t_2$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_2=|2-3|=1$;  since $t_3$='z', then there are no indexes $j$ such that $t_j>t_i$, thus $b_3=0$;  since $t_4$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_4=|4-3|=1$. 

Thus, if $t$ = "abzb", then $b=[6,1,0,1]$.

Given the string $s$ and the array $b$, find any possible string $t$ for which the following two requirements are fulfilled simultaneously:  $t$ is obtained from $s$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $t$ according to the rules above, equals to the array $b$ specified in the input data. 


-----Input-----

The first line contains an integer $q$ ($1 \le q \le 100$) — the number of test cases in the test. Then $q$ test cases follow.

Each test case consists of three lines:  the first line contains string $s$, which has a length from $1$ to $50$ and consists of lowercase English letters;  the second line contains positive integer $m$ ($1 \le m \le |s|$), where $|s|$ is the length of the string $s$, and $m$ is the length of the array $b$;  the third line contains the integers $b_1, b_2, \dots, b_m$ ($0 \le b_i \le 1225$). 

It is guaranteed that in each test case an answer exists.


-----Output-----

Output $q$ lines: the $k$-th of them should contain the answer (string $t$) to the $k$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.


-----Example-----
Input
4
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0

Output
aac
b
aba
codeforces



-----Note-----

In the first test case, such strings $t$ are suitable: "aac', "aab".

In the second test case, such trings $t$ are suitable: "a", "b", "c".

In the third test case, only the string $t$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Greedy algorithms

Sorting

Implementation

Constructive algorithms


Solutions:
from collections import Counter

def solve():
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ans = ['' for _ in range(m)]
	cv = [(k, v) for (k, v) in Counter(s).items()]
	cv.sort(key=lambda x: x[0], reverse=True)
	count = 0
	cvi = 0
	while count != m:
		zeros = [i for (i, x) in enumerate(b) if x == 0]
		lz = len(zeros)
		count += lz
		while cv[cvi][1] < lz:
			cvi += 1
		c = cv[cvi][0]
		for zero_index in zeros:
			ans[zero_index] = c
			b[zero_index] = -1
		cvi += 1
		for i in range(m):
			if b[i] < 0:
				continue
			for zero_index in zeros:
				b[i] -= abs(i - zero_index)
	return ''.join(ans)
t = int(input())
while t > 0:
	t -= 1
	ans = solve()
	print(ans)


from collections import Counter

def solve(t, m, b):
	c = Counter(t)
	letters = list(sorted(c))
	ix = len(letters) - 1
	res = [None] * m
	solved = 0
	while solved < m:
		zeros = [i for (i, v) in enumerate(b) if not res[i] and (not v)]
		lz = len(zeros)
		while c[letters[ix]] < lz:
			ix -= 1
		ll = letters[ix]
		ix -= 1
		for z in zeros:
			res[z] = ll
		solved += lz
		for i in range(m):
			if not res[i]:
				for z in zeros:
					b[i] -= abs(z - i)
	return ''.join(res)
q = int(input())
for i_q in range(q):
	t = input()
	m = int(input())
	b = list(map(int, input().split(' ')))
	print(solve(t, m, b))


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 Y(c):
	print(['NO', 'YES'][c])

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

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	s = input()
	C = Counter(s)
	N = int(input())
	A = alele()
	S = sorted(s)
	Ans = [''] * N
	while True:
		D = []
		for i in range(N):
			if A[i] == 0:
				D.append(i)
		l = len(D)
		if l == 0:
			break
		while len(S) > 0 and C[S[-1]] < l:
			S.pop()
		if len(S):
			for j in D:
				for i in range(N):
					if i not in D:
						A[i] -= abs(i - j)
					else:
						A[i] = -1
				y = S.pop()
				C[y] = 0
				Ans[j] = y
		else:
			break
	print(''.join(Ans))


import collections
t = int(input())
for _ in range(t):
	s = input()
	n = int(input())
	nums = list(map(int, input().split()))
	cnt = list(collections.Counter(s).items())
	cnt.sort()
	(count, res, k) = (0, [0] * n, len(cnt) - 1)
	while count < n:
		que = []
		for i in range(n):
			if nums[i] == 0:
				que.append(i)
				nums[i] = -1
				count += 1
		for i in range(n):
			if nums[i] > 0:
				nums[i] -= sum((abs(i - j) for j in que))
		while cnt[k][1] < len(que):
			k -= 1
		for i in que:
			res[i] = cnt[k][0]
		k -= 1
	print(''.join(res))


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

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

def fi():
	return float(input())

def si():
	return input()

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

def li():
	return list(mi())

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
from math import *
import bisect
from decimal import *
getcontext().prec = 50
abc = 'abcdefghijklmnopqrstuvwxyz'
pi = 3.141592653589793

def main():
	for _ in range(ii()):
		s = si()
		n = ii()
		b = li()
		h = [0] * 26
		for i in range(len(s)):
			h[ord(s[i]) - 97] += 1
		ans = ['.'] * n
		f = [0] * n
		g = 11
		while True:
			l = []
			for i in range(n):
				if f[i] == b[i] and ans[i] == '.':
					l.append(i)
			for j in range(25, -1, -1):
				if h[j] - len(l) >= 0:
					c = j
					h[j] = 0
					break
				else:
					h[j] = 0
			if len(l):
				for j in range(len(l)):
					ans[l[j]] = chr(97 + c)
				for j in range(n):
					if ans[j] == '.':
						for k in range(len(l)):
							f[j] += abs(l[k] - j)
			if ans.count('.') == 0:
				break
		print(''.join(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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	t = [-1 for i in range(m)]
	zeroes = b.count(0)
	char = 'z'

	def findchar(s, zeroes, char):
		while 1:
			if s.count(char) >= zeroes:
				break
			else:
				char = chr(ord(char) - 1)
		return char
	char = findchar(s, zeroes, char)
	while -1 in t:
		pos = []
		for i in range(m):
			if b[i] == 0:
				b[i] = -1
				t[i] = char
				pos.append(i)
		for j in range(m):
			if b[j] != -1:
				for p in pos:
					b[j] -= abs(j - p)
		zeroes = b.count(0)
		char = findchar(s, zeroes, chr(ord(char) - 1))
	for i in range(m):
		print(t[i], end='')
	print()


def add_to_t(s, t, b):
	ind_0 = []
	for i in range(len(b)):
		if b[i] == 0:
			ind_0.append(i)
	max_char = max(s)
	while len(ind_0) > s.count(max_char):
		s = s.replace(max_char, '')
		max_char = max(s)
	for i in ind_0:
		t[i] = max_char
		b[i] = -1
		for j in range(len(b)):
			if b[j] != 0 and b[j] != -1:
				b[j] -= int(abs(i - j))
	s = s.replace(max_char, '')
	return s
for _ in range(int(input())):
	s = input()
	n = int(input())
	b = list(map(int, input().split()))
	t = [None] * n
	count_1 = b.count(-1)
	while count_1 != n:
		s = add_to_t(s, t, b)
		count_1 = b.count(-1)
	t = ''.join(t)
	print(t)


import sys

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

def input_split():
	return [int(i) for i in input().split()]
t = int(input())
for tests in range(t):
	s = input()
	n = int(input())
	b = input_split()
	q = []
	ans = []
	for i in range(len(b)):
		if b[i] == 0:
			q.append(i)
	ans.append(len(q))
	while len(q) < n:
		new_q = []
		for i in range(n):
			if i in q:
				continue
			runnning_sum = 0
			for j in q:
				runnning_sum += abs(i - j)
			if runnning_sum == b[i]:
				new_q.append(i)
		ans.append(len(new_q))
		q.extend(new_q)
	nums = {}
	for i in s:
		if i not in nums:
			nums[i] = 1
		else:
			nums[i] += 1
	nums = list(nums.items())
	nums.sort(reverse=True)
	ans_ind = 0
	nums_ind = 0
	ret = []
	while ans_ind < len(ans) and nums_ind < len(nums):
		if nums[nums_ind][1] >= ans[ans_ind]:
			ans_ind += 1
			ret.append(nums[nums_ind][0])
		nums_ind += 1
	final_s = ['' for i in range(n)]
	q_ind = 0
	ret_ind = 0
	for i in range(len(ret)):
		for j in range(ans[i]):
			final_s[q[q_ind]] = ret[i]
			q_ind += 1
	print(''.join(final_s))


for _ in range(int(input())):
	s = input()
	m = int(input())
	arr = list(map(int, input().split()))
	n = len(arr)
	s = sorted(s, reverse=True)
	ss = []
	ans = [-1] * m
	ma = 0
	while True:
		c = 0
		for i in range(n):
			if arr[i] == 0:
				c += 1
		if c == 0:
			break
		for i in s:
			if s.count(i) >= c and i not in ss and (ma == 0 or ord(i) < ord(ss[-1])):
				ma = i
				ss.append(i)
				break
		l = []
		for i in range(n):
			if arr[i] == 0:
				ans[i] = ma
				l.append(i)
				arr[i] = -1
		for i in range(n):
			for j in l:
				arr[i] -= abs(j - i)
	print(''.join(ans))


q = int(input())
for i in range(q):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	d = {}
	l = sorted(list(set(s)), reverse=True)
	for alphabet in l:
		d[alphabet] = s.count(alphabet)
	ret = '0' * m
	l0 = -1
	while 1:
		bcopy = b.copy()
		n = b.count(0)
		if n == 0:
			break
		for j in range(1, 30):
			if d[l[l0 + j]] >= n:
				l0 += j
				alphabet = l[l0]
				break
		for j in range(m):
			if b[j] == 0:
				ret = ret[0:j] + alphabet + ret[j + 1:]
				for k in range(m):
					if b[k] != 0:
						bcopy[k] -= abs(k - j)
				bcopy[j] = -1
		b = bcopy
	print(ret)


def idealString(parentArr, values, length, alphabets):
	countAlpha = dict()
	for x in alphabets:
		countAlpha[x] = parentArr.count(x)
	arr = [0 for _ in range(length)]
	parentArr.sort()
	lastAlphaRemoved = 0
	currentZeros = []
	while True:
		if 0 not in arr:
			break
		for i in range(length):
			if values[i] == 0:
				currentZeros.append(i + 1)
				values[i] = -1
		for alpha in alphabets:
			if countAlpha[alpha] >= len(currentZeros) and lastAlphaRemoved == 0:
				for j in currentZeros:
					arr[j - 1] = alpha
					countAlpha[alpha] = 0
					lastAlphaRemoved = alpha
				break
			elif countAlpha[alpha] >= len(currentZeros) and lastAlphaRemoved > alpha:
				for j in currentZeros:
					arr[j - 1] = alpha
					countAlpha[alpha] = 0
					lastAlphaRemoved = alpha
				break
		for i in range(length):
			for j in currentZeros:
				if values[i] != 0 and values[i] != -1:
					values[i] -= abs(i + 1 - j)
		currentZeros = []
	return ''.join(arr)
alphabets = sorted(list('abcdefghijklmnopqrstuvwxyz'), reverse=True)
for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	print(idealString(list(s), b, m, alphabets))


import sys, collections
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().rstrip()
	m = int(input())
	b = list(map(int, input().split()))
	t = [None] * m
	letter = sorted(set(s), reverse=True)
	for l in letter:
		zeros = []
		for i in range(len(b)):
			if b[i] == 0:
				zeros.append(i)
		if len(zeros) > s.count(l):
			continue
		for i in range(len(b)):
			if b[i] != 0:
				b[i] -= sum(map(lambda z: abs(z - i), zeros))
		for zero_idx in zeros:
			b[zero_idx] = -1
			t[zero_idx] = l
	print(''.join(t))


tc = int(input())
while tc:
	s = sorted(input())
	n = int(input())
	lst = []
	zeros = []
	lst = list(map(int, input().split()))
	for i in range(n):
		if lst[i] == 0:
			zeros.append(i)
	res = [None] * n
	si = len(s) - 1
	while zeros:
		while s[si] != s[si - len(zeros) + 1]:
			si -= 1
		for ind in zeros:
			res[ind] = s[si]
			si -= 1
		while si >= 0 and s[si] == s[si + 1]:
			si -= 1
		tzeros = []
		for i in range(n):
			if lst[i] <= 0:
				continue
			for ind in zeros:
				lst[i] -= abs(i - ind)
			if lst[i] == 0:
				tzeros.append(i)
		zeros = tzeros
	print(''.join(res))
	tc -= 1


t = int(input())
for q in range(t):
	s = list(input())
	x = sorted(set(s))
	m = int(input())
	b = list(map(int, input().split()))
	l = [-1] * m
	while sum(b) != -m:
		z = set()
		for i in range(m):
			if b[i] == 0:
				z.add(i)
				b[i] = -1
		while True:
			q = x.pop()
			if len(z) <= s.count(q):
				for i in z:
					l[i] = q
				break
		for i in z:
			for k in range(m):
				if b[k] != -1:
					b[k] -= abs(i - k)
	print(''.join(l))


from collections import deque
q = int(input())
for _ in range(q):
	s = input()
	m = int(input())
	B = list(map(int, input().split()))
	marked = 0
	check = [False] * m
	order = list()
	while marked < m:
		toCheck = list()
		for i in range(m):
			if B[i] == 0 and (not check[i]):
				toCheck.append(i)
				check[i] = True
		for i in toCheck:
			for j in range(i + 1, m):
				if B[j] != 0:
					B[j] -= abs(i - j)
			for j in range(i):
				if B[j] != 0:
					B[j] -= abs(i - j)
		order.append(toCheck)
		marked += len(toCheck)
	chars = [0] * 26
	for ch in s:
		chars[ord(ch) - ord('a')] += 1
	assign = list()
	i = 0
	j = 25
	while i < len(order):
		req = len(order[i])
		while chars[j] < req:
			j -= 1
		assign.append(chr(ord('a') + j))
		j -= 1
		i += 1
	output = [None] * m
	for i in range(len(order)):
		for j in order[i]:
			output[j] = assign[i]
	print(''.join(output))


def alldone(l):
	for i in l:
		if i == 0:
			return 0
	return 1
t = int(input())
for you in range(t):
	s = input()
	freq = [0 for i in range(26)]
	done = [0 for i in range(26)]
	for i in s:
		freq[ord(i) - 97] += 1
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	fist = [0 for i in range(n)]
	lfi = []
	l = []
	donefors = [0 for i in range(n)]
	for i in range(n):
		if li[i] == 0:
			l.append(i)
			donefors[i] = 1
			lfi.append(i)
	for i in range(25, -1, -1):
		if freq[i] >= len(l) and done[i] == 0:
			done[i] = 1
			for j in l:
				fist[j] = chr(97 + i)
			l = []
			break
		else:
			done[i] = 1
	while alldone(donefors) == 0:
		for i in range(n):
			if donefors[i] == 1:
				continue
			else:
				z = li[i]
				for j in lfi:
					li[i] = li[i] - abs(i - j)
				if li[i] == 0:
					continue
				li[i] = z
		for i in range(n):
			if li[i] == 0 and donefors[i] == 0:
				l.append(i)
				donefors[i] = 1
		for i in l:
			lfi.append(i)
		for i in range(25, -1, -1):
			if freq[i] >= len(l) and done[i] == 0:
				done[i] = 1
				for j in l:
					fist[j] = chr(97 + i)
				l = []
				break
			else:
				done[i] = 1
	for i in fist:
		print(i, end='')
	print()


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

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

def fi():
	return float(stdin.readline())

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

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

def li():
	return list(mi())

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

def lsi():
	return list(si())
res = ['Yes', 'No']
test_case = ii()
while test_case:
	test_case -= 1
	a = lsi()
	n = ii()
	b = li()
	v = [0] * 26
	for i in a:
		v[ord(i) - 97] += 1
	val = 25
	tot = 0
	ans = ['0'] * n
	while tot < n:
		z = []
		for i in range(n):
			if not b[i]:
				z.append(i)
		while v[val] < len(z):
			val -= 1
		for i in z:
			ans[i] = chr(val + 97)
			for j in range(n):
				if b[j]:
					b[j] -= abs(i - j)
			b[i] = -1
		tot += len(z)
		val -= 1
	print(*ans, sep='')


import time

def getZero(arr):
	ans = []
	for i in range(len(arr)):
		if arr[i][0] == 0:
			ans.append(i)
	return ans
for _ in range(int(input())):
	s = [ord(i) for i in input()]
	m = int(input())
	arr = [[int(val), i] for (i, val) in enumerate(input().split())]
	temp = {}
	for i in s:
		if temp.get(i) != None:
			temp[i] += 1
		else:
			temp[i] = 1
	s = list(temp.items())
	s.sort(reverse=True)
	resp = [0 for i in range(m)]
	put = 0
	cont = 0
	while cont < m:
		x = getZero(arr)
		while len(x) > s[0][1]:
			del s[0]
		for j in x:
			(val, pos) = arr[j]
			resp[pos] = s[0][0]
			cont += 1
			for k in range(len(arr)):
				(valAt, posAt) = arr[k]
				arr[k][0] -= abs(pos - posAt)
		del s[0]
		for j in x:
			arr[j][0] = -1
	for i in resp:
		print(chr(i), end='')
	print()


from collections import defaultdict
t = int(input())
for test in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	count = defaultdict(int)
	for i in s:
		count[i] += 1
	order = sorted(list(set(s)))
	while b.count(0) != 0:
		pos = []
		req = b.count(0)
		while count[order[-1]] < req:
			order.pop()
		for i in range(m):
			if b[i] == 0:
				pos.append(i)
				b[i] = order[-1]
		order.pop()
		for i in range(m):
			if str(b[i]).isdigit():
				for j in pos:
					b[i] -= abs(i - j)
	print(''.join(b))


class AlphaHz:

	def __init__(self, s, m, b):
		self.s = s
		self.m = m
		self.b = b
		code = map(lambda x: ord(x) - ord('a'), s)
		self.count = [0] * 27
		for c in code:
			self.count[c] += 1
		self.mcode = 26
		self.t = ['\x00'] * m

	def solve(self):
		while True:
			zeros = []
			for i in range(m):
				if b[i] == 0:
					zeros.append(i)
					b[i] = -1
			if self.count[self.mcode] < len(zeros):
				for i in range(self.mcode - 1, -1, -1):
					if self.count[i] >= len(zeros):
						self.mcode = i
						break
			for zero in zeros:
				self.t[zero] = chr(ord('a') + self.mcode)
			for i in range(m):
				for zero in zeros:
					b[i] -= abs(i - zero)
			if not len(zeros):
				break
			self.mcode -= 1
		return ''.join(self.t)
t = int(input())
for i in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	obj = AlphaHz(s, m, b)
	t = obj.solve()
	print(t)


from collections import defaultdict as dft
for _ in range(int(input())):
	s = input()
	s = sorted(s)[::-1]
	n = int(input())
	res = ['a'] * n
	arr = list(map(int, input().split()))
	x = 0
	vis = [0] * n
	count = 0
	last = None
	while count < n:
		while last and s[x] == last:
			x += 1
		ls = []
		for i in range(n):
			if arr[i] == 0 and vis[i] == 0:
				ls.append(i)
				count += 1
				vis[i] = 1
		ln = len(ls)
		mile = 1
		last = s[x]
		while mile < ln:
			x += 1
			if s[x] == last:
				mile += 1
			else:
				mile = 1
				last = s[x]
		for ind in ls:
			res[ind] = last
		for i in range(n):
			if not vis[i]:
				for ind in ls:
					arr[i] -= abs(ind - i)
	print(''.join(res))


T = int(input())
D = []
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(0, T):
	str = input()
	n = int(input())
	B = [int(x) for x in input().split(' ')]
	A = [alphabet.index(x) for x in str]
	C = [0 for x in range(n)]
	r = 0
	while r < n:
		mx = max(A)
		if A.count(mx) >= B.count(0):
			B_new = B.copy()
			for k in range(0, n):
				if B[k] == 0:
					C[k] = alphabet[mx]
					r += 1
					for l in range(0, n):
						if B_new[l] > 0:
							B_new[l] = B_new[l] - abs(l - k)
					B_new[k] = -1
			B = B_new
		for j in range(0, len(A)):
			if A[j] == mx:
				A[j] = -1
	s = ''.join(C)
	D.append(s)
for i in D:
	print(i)


for _ in range(int(input())):
	ct = [0] * 26
	for c in input():
		ct[ord(c) - ord('a')] += 1
	n = int(input())
	a = list(map(int, input().split()))
	ans = [''] * n
	ptr = 25
	while any([x != -1 for x in a]):
		ls = [i for i in range(n) if a[i] == 0]
		for idx in ls:
			a[idx] = -1
			for i in range(idx - 1, -1, -1):
				if a[i] > 0:
					a[i] -= idx - i
			for i in range(idx + 1, n):
				if a[i] > 0:
					a[i] -= i - idx
		while ct[ptr] < len(ls):
			ptr -= 1
		for idx in ls:
			ans[idx] = chr(ord('a') + ptr)
		ptr -= 1
	print(*ans, sep='')


letters = list('abcdefghijklmnopqrstuvwxyz')
from collections import defaultdict
for _ in range(int(input())):
	string = input()
	d = {}
	d = defaultdict(lambda : 0, d)
	for i in range(len(string)):
		d[string[i]] = d[string[i]] + 1
	letter = []
	for i in d.keys():
		letter.append(i)
	letter.sort(reverse=True)
	n = int(input())
	a = input().split(' ')
	for i in range(n):
		a[i] = int(a[i])
	ans = [0] * n
	prev = []
	while a != []:
		index = []
		for i in range(len(a)):
			if a[i] == 0 and i not in prev:
				index.append(i)
		num = len(index)
		for i in range(len(a)):
			if a[i] == 0:
				continue
			temp = 0
			for j in index:
				temp = temp + abs(i - j)
			a[i] = a[i] - temp
		while letter != []:
			if d[letter[0]] < num:
				letter.remove(letter[0])
			else:
				break
		if letter == []:
			break
		for i in index:
			ans[i] = letter[0]
			prev.append(i)
		letter.remove(letter[0])
	finalans = ''
	for i in ans:
		finalans = finalans + i
	print(finalans)


from sys import stdin
for _ in range(int(stdin.readline())):
	s = stdin.readline().strip()
	dictt = {}
	for i in s:
		if i not in dictt:
			dictt[i] = 1
		else:
			dictt[i] += 1
	m = int(stdin.readline())
	val = list(map(int, stdin.readline().split()))
	stack = sorted(list(set([ord(c) for c in s])))
	final = [0] * m
	while len(stack) != 0:
		new = []
		count = 0
		for i in range(m):
			if val[i] == 0 and final[i] == 0:
				val[i] = 3000
				new.append(i)
				count += 1
		while dictt[chr(stack[-1])] < count:
			stack.pop()
		for i in new:
			final[i] = chr(stack[-1])
		stack.pop()
		for i in range(m):
			for j in new:
				val[i] -= abs(i - j)
	print(''.join(final))


import sys
import math

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	s = SI()
	m = II()
	b = LI()
	d = [0] * 26
	ans = [''] * m
	for i in s:
		d[ord(i) - 97] += 1
	for i in range(m):
		zeros = []
		count = 0
		for j in range(m):
			if b[j] == 0:
				zeros.append(j)
				count += 1
		letter = ''
		for j in range(25, -1, -1):
			if d[j] >= count:
				letter = chr(j + 97)
				for k in range(j, 26):
					d[k] = 0
				break
		for j in range(count):
			b[zeros[j]] = -1
			ans[zeros[j]] = letter
		for j in range(count):
			for k in range(m):
				if b[k] != -1:
					b[k] -= abs(k - zeros[j])
	test = [0] * m
	for i in range(m):
		count = 0
		for j in range(m):
			if ans[i] < ans[j]:
				count += abs(j - i)
		test[i] = count
	print(''.join(ans))


from collections import Counter
q = int(input())
for _ in range(q):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	c = Counter(s)
	c = list(c.items())
	c.sort(key=lambda x: x[0])
	ans = [None for _ in range(m)]
	while not all(ans):
		indices = []
		for i in range(m):
			if b[i] == 0:
				indices.append(i)
				b[i] = -1
		while True:
			if c[-1][1] >= len(indices):
				for idx in indices:
					ans[idx] = c[-1][0]
				c.pop()
				break
			else:
				c.pop()
		for j in range(m):
			for idx in indices:
				b[j] -= abs(idx - j)
	print(''.join(map(str, ans)))


import sys
from collections import Counter as CO
from collections import defaultdict as dd
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	word = list(map(str, input().strip()))
	df = dd(int)
	for k in word:
		df[k] += 1
	n = int(input())
	arr = list(map(int, input().split()))
	d = dict()
	l = []
	maxi = []
	while sum(arr) != 0:
		for i in range(len(arr)):
			if arr[i] == 0 and i not in d:
				maxi += [i]
				d[i] = 1
		l += [maxi]
		for i in maxi:
			for j in range(len(arr)):
				if arr[j] != 0:
					arr[j] -= abs(i - j)
		maxi = []
	for i in range(len(arr)):
		if arr[i] == 0 and i not in d:
			maxi += [i]
	l += [maxi]
	ind = 0
	final = [0] * n
	for k in sorted(df, reverse=True):
		if ind == len(l):
			break
		if len(l[ind]) > df[k]:
			continue
		for i in range(len(l[ind])):
			final[l[ind][i]] = k
		ind += 1
	print(''.join(final))


tests = int(input())
for _ in range(tests):
	s = input()
	n = int(input())
	b = list(map(int, input().split()))
	g = sorted(b)
	ans = ['a'] * n
	d = dict()
	for i in set(s):
		d[i] = 0
	for i in s:
		d[i] += 1
	tec = 122
	r = b.count(0)
	while r != 0:
		flag = True
		while flag:
			if chr(tec) in d:
				if d[chr(tec)] >= r:
					flag = False
					break
			tec -= 1
		sp = []
		for i in range(n):
			if b[i] == 0:
				sp.append(i)
				b[i] = -1
		for i in range(n):
			summ = 0
			if b[i] < 0:
				continue
			for j in sp:
				summ += abs(i - j)
			b[i] -= summ
		for i in sp:
			ans[i] = chr(tec)
		tec -= 1
		r = b.count(0)
	for i in ans:
		print(i, end='')
	print()


for _ in range(int(input())):
	s = sorted(input())
	m = int(input())
	b = list(map(int, input().split()))
	a = [0] * 26
	for i in s:
		a[ord(i) - 97] += 1
	x = 25
	while True:
		z = [i for i in range(m) if b[i] == 0]
		if len(z) == 0:
			break
		while a[x] < len(z):
			x -= 1
		symbol = chr(x + 97)
		for i in z:
			b[i] = symbol
			for j in range(i):
				if type(b[j]) is int:
					b[j] += j - i
			for j in range(i + 1, m):
				if type(b[j]) is int:
					b[j] += i - j
		x -= 1
	print(''.join(b))


import math
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	result.append(n)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	s = input()
	n = int(input())
	l = list(map(int, input().split()))
	m = 10 ** 9 + 7
	d = {}
	for j in s:
		d[j] = 0
	for j in s:
		d[j] += 1
	l1 = []
	f = 0
	while f == 0:
		l2 = []
		for j in range(0, n):
			if l[j] == 0:
				l[j] = m
				l2.append(j)
		if len(l2) == 0:
			break
		l1.append(l2)
		for j in l2:
			for k in range(0, n):
				if l[k] != 0 and k != j and (l[k] != m):
					l[k] -= abs(j - k)
	l2 = list(set(s))
	l2.sort()
	k = len(l2)
	s1 = ['-1' for j in range(0, n)]
	for j in range(0, len(l1)):
		k -= 1
		while d[l2[k]] < len(l1[j]):
			k -= 1
		for p in l1[j]:
			s1[p] = l2[k]
			d[l2[k]] -= 1
	print(''.join(s1))
t = int(input())
for i in range(0, t):
	main()


import io
import os

def solve():
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ans = ['a'] * m
	cur = 25
	while b.count(0):
		l = []
		for (i, v) in enumerate(b):
			if v == 0:
				l.append(i)
				b[i] = -1
		for pos in l:
			for i in range(m):
				b[i] -= abs(pos - i)
		while s.count(chr(ord('a') + cur)) < len(l):
			cur -= 1
		for pos in l:
			ans[pos] = chr(ord('a') + cur)
		cur -= 1
	print(''.join(ans))
t = int(input())
for _ in range(t):
	solve()


from collections import Counter
for _ in range(int(input())):
	s = input()
	m = int(input())
	l = list(map(int, input().split()))
	alp = [[char, num] for (char, num) in Counter(s).items()]
	alp.sort(key=lambda val: val[0], reverse=True)
	order = []
	x = 1
	while any((i >= 0 for i in l)):
		zeros = []
		for i in range(m):
			if l[i] == 0:
				zeros.append(i)
				l[i] = -x
		order.append(len(zeros))
		for i in zeros:
			for j in range(m):
				l[j] -= abs(j - i) if l[j] > 0 else 0
		x += 1
	(i, j, charSet) = (0, 0, [])
	while True:
		if j == len(order):
			break
		if order[j] <= alp[i][1]:
			charSet.append(alp[i][0])
			i += 1
			j += 1
		else:
			i += 1
	for j in l:
		print(charSet[-j - 1], end='')
	print()


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def main():

	def solve():
		ss = list(input()) + [' ']
		m = int(input())
		bb = [int(a) for a in input().split()]
		ss.sort(reverse=True)
		tt = ['a'] * m
		sp = 0
		while True:
			ilist = []
			p = -1
			while 0 in bb[p + 1:]:
				p = bb.index(0, p + 1)
				ilist.append(p)
				bb[p] = -1
			req = len(ilist)
			while True:
				base = ss[sp]
				bcount = 0
				while ss[sp] == base:
					bcount += 1
					sp += 1
				if bcount >= req:
					break
			for p in ilist:
				tt[p] = base
				for i in range(m):
					if bb[i] > 0:
						bb[i] -= abs(i - p)
			if 0 not in bb:
				break
		print(''.join(tt))
	t = int(inputi())
	for _ in range(t):
		solve()
main()


import collections
import threading
import string

def main():
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	cnt = 0
	pref = 0
	t = b[:]
	for c in reversed(string.ascii_lowercase):
		inc_cnt = 0
		inc_pref = 0
		target = pref
		back = 0
		for i in range(m):
			if type(t[i]) is str:
				back += 1
				target -= cnt - back
				target += back
				continue
			if t[i] == target:
				t[i] = c
				inc_cnt += 1
				inc_pref += i
			target = target - (cnt - back) + back
		pref += inc_pref
		cnt += inc_cnt
		if cnt == m:
			break
	c1 = collections.Counter(s)
	abc = sorted(list(set(t)))
	j = len(abc) - 1
	cnt = [t.count(ch) for ch in abc]
	d = dict()
	for c in reversed(string.ascii_lowercase):
		if c1[c] >= cnt[j]:
			d[abc[j]] = c
			j -= 1
			if j < 0:
				break
	for i in range(len(t)):
		t[i] = d[t[i]]
	print(''.join(t))
tn = int(input())
for _ in range(tn):
	main()


t = int(input())
for _ in range(t):
	tester = [0] * 26
	stri = list(input())
	n = int(input())
	ans = ['0'] * n
	testing = list(map(int, input().split()))
	nn = len(stri)
	for i in range(nn):
		k = ord(stri[i]) - 97
		tester[k] = tester[k] + 1
	max = 25
	while True:
		k = testing.count(0)
		if k == 0:
			break
		else:
			j = 0
			for i in range(max, -1, -1):
				if tester[i] >= k:
					max = i - 1
					j = i
					break
		ind = []
		for i in range(n):
			if testing[i] == 0:
				ind.append(i)
				ans[i] = chr(97 + j)
				testing[i] = 1000000
		for i in range(n):
			for a in range(len(ind)):
				testing[i] = testing[i] - abs(i - ind[a])
	print(*ans, sep='')


from collections import Counter
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

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

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		s = SI()
		m = II()
		bb = LI()
		ca = [(c, a) for (c, a) in sorted(Counter(s).items(), reverse=True)]
		ci = 0
		ans = [''] * m
		while 1:
			pos = []
			for i in range(m):
				if bb[i] == 0:
					pos.append(i)
					bb[i] = -1
			if not pos:
				break
			while ca[ci][1] < len(pos):
				ci += 1
			c = ca[ci][0]
			ci += 1
			for i in pos:
				ans[i] = c
				for d in range(1, max(i, m - i - 1) + 1):
					if i - d >= 0:
						bb[i - d] -= d
					if i + d < m:
						bb[i + d] -= d
		print(''.join(ans))
main()


t = int(input())
while t:
	t -= 1
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ans = ['.'] * m
	ss = ''.join(list(set(sorted(s))))
	idx = len(ss) - 1
	while True:
		idxx = []
		f = 0
		for i in range(m):
			if not b[i] and ans[i] == '.':
				idxx.append(i)
				f = 1
		if not f:
			break
		while s.count(ss[idx]) < len(idxx):
			idx -= 1
		for i in idxx:
			ans[i] = ss[idx]
		idx -= 1
		for i in range(m):
			if ans[i] == '.':
				for j in idxx:
					b[i] -= max(i - j, j - i)
	ans = ''.join(ans)
	print(ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	s = inputstring()
	m = inputnum()
	b = inputlist()
	d = {}
	for i in range(len(s)):
		if s[i] not in d:
			d[s[i]] = 1
		else:
			d[s[i]] += 1
	rtn = ['?'] * m
	while rtn.count('?'):
		inds = []
		for j in range(m):
			if b[j] == 0 and rtn[j] == '?':
				inds.append(j)
		nums = list(d)
		nums.sort(reverse=True)
		char = nums[0]
		while d[char] < len(inds):
			d.pop(char)
			nums = list(d)
			nums.sort(reverse=True)
			char = nums[0]
		d.pop(char)
		for j in inds:
			rtn[j] = char
		for j in inds:
			for k in range(m):
				if rtn[k] == '?':
					b[k] -= abs(j - k)
	for i in range(len(rtn)):
		print(rtn[i], end='')
	print()


from collections import Counter
t = int(input())
for _ in range(t):
	s = list(input())
	s.sort(reverse=True)
	now = 0
	n = int(input())
	l = list(map(int, input().split()))
	c = Counter(s)
	count = 0
	ans = [''] * n
	while count < n:
		ind = []
		for i in range(n):
			if l[i] == 0:
				ind.append(i)
		while c[s[now]] < len(ind):
			now += 1
		for i in ind:
			ans[i] = s[now]
		x = s[now]
		while now < len(s) and s[now] == x:
			now += 1
		for i in range(n):
			if l[i] <= 0:
				l[i] += 10 ** 10
			else:
				for j in ind:
					l[i] -= abs(i - j)
		count += len(ind)
	print(*ans, sep='')


import collections
t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	characters = sorted(set(s))
	freq = collections.Counter(list(s))
	ptr = len(characters) - 1
	fixed = m
	while fixed:
		curr = set()
		for x in range(m):
			if b[x] == 0:
				curr.add(x)
		fixed -= len(curr)
		while freq[characters[ptr]] < len(curr):
			ptr -= 1
		while curr:
			index = curr.pop()
			b[index] = characters[ptr]
			for x in range(m):
				if str(b[x]).isdigit():
					b[x] -= abs(x - index)
		ptr -= 1
	print(''.join(b))


from collections import Counter
for _ in range(int(input())):
	s = input()
	cnt = Counter(s)
	cnt = sorted([*cnt.items()])
	m = int(input())
	arr = [*map(int, input().split())]
	ans = ['-1'] * m
	while any((i >= 0 for i in arr)):
		zeros = []
		for i in range(m):
			if arr[i] == 0:
				zeros.append(i)
				arr[i] -= 1
		ch = -1
		for i in range(len(cnt) - 1, -1, -1):
			if cnt[i][1] >= len(zeros):
				ch = i
				break
			else:
				del cnt[i]
		for i in zeros:
			ans[i] = cnt[ch][0]
		del cnt[ch]
		for i in zeros:
			tom = 1
			for j in range(i + 1, m):
				arr[j] -= tom
				tom += 1
			tom = 1
			for j in range(i - 1, -1, -1):
				arr[j] -= tom
				tom += 1
	print(''.join(ans))


from collections import Counter
q = int(input())
for _ in range(q):
	s = Counter(input())
	m = int(input())
	b = [int(i) for i in input().split(' ')]
	h = []
	last = [b.index(0)]
	o = [[last[0]]]
	while len(h) + len(last) < m:
		for (i, num) in enumerate(b):
			if i in h or i in last:
				continue
			acc = 0
			for j in h:
				acc += abs(i - j)
			if num == acc:
				last.append(i)
				o[-1].append(i)
				break
			for j in last:
				acc += abs(i - j)
			if num == acc:
				h.extend(last)
				last = [i]
				o.append([i])
	ans = [' ' for i in range(m)]
	currchr = 0
	for i in range(26):
		c = chr(ord('z') - i)
		if currchr == len(o):
			break
		need = len(o[currchr])
		if s[c] >= need:
			for j in o[currchr]:
				ans[j] = c
			currchr += 1
	print(''.join(ans))


from collections import Counter
rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))
INF = float('inf')

def verify(s, arr):
	amts = []
	for i in range(0, len(s)):
		amt = 0
		for j in range(0, len(s)):
			if s[i] < s[j]:
				amt += abs(i - j)
		amts.append(amt)
	print(arr, amts)
	return all((arr[i] == amts[i] for _ in range(len(arr))))

def solve(S, M, arr):
	count = Counter(S)
	chars = [c for c in count]
	chars.sort()
	chars.reverse()
	ans = ['a' for _ in range(len(arr))]
	valid = True
	i = 0
	while valid:
		indices = []
		for j in range(0, len(arr)):
			if arr[j] == 0:
				indices.append(j)
		if indices == []:
			break
		while i < len(chars) and count[chars[i]] < len(indices):
			i += 1
		for ind in indices:
			arr[ind] = INF
			ans[ind] = chars[i]
		for j in range(0, len(arr)):
			if arr[j] != INF:
				for ind in indices:
					arr[j] -= abs(j - ind)
		valid = False
		for v in arr:
			if v != INF:
				valid = True
		i += 1
	return ''.join(ans)
q = int(input())
for _ in range(q):
	s = input()
	m = rri()
	arr = rrm()
	print(solve(s, m, arr))


t = int(input())
from collections import defaultdict
alpha = 'abcdefghijklmnopqrstuvwxyz'[::-1]

def find_largest(d, start):
	idx = alpha.index(start)
	while idx < len(alpha):
		if d[alpha[idx]] != 0:
			return alpha[idx]
		idx += 1
for _ in range(t):
	s = input().strip()
	d = defaultdict(int)
	for e in s:
		d[e] += 1
	m = int(input())
	n = len(s)
	bs = list(map(int, input().strip().split()))
	filled = 0
	s = [0] * m
	rem = n - m
	cur = 'z'
	while filled < m:
		assert rem >= 0
		cur = find_largest(d, cur)
		assert cur != None
		assert cur >= 'a'
		assert d[cur] > 0
		possible = 0
		pos = []
		if filled == 0:
			for i in range(m):
				if bs[i] == 0:
					possible += 1
					pos.append(i)
		else:
			for i in range(m):
				if s[i] != 0:
					continue
				c = 0
				for j in range(m):
					if j == i:
						continue
					if s[j] == 0:
						continue
					c += abs(j - i)
				if c == bs[i]:
					possible += 1
					pos.append(i)
		assert possible > 0
		if possible == d[cur]:
			for p in pos:
				s[p] = cur
			filled += len(pos)
		elif possible > d[cur]:
			assert rem >= d[cur]
			rem -= d[cur]
		else:
			assert rem >= d[cur] - possible
			rem -= d[cur] - possible
			for p in pos:
				s[p] = cur
			filled += len(pos)
		cur = chr(ord(cur) - 1)
	print(''.join(s))


from collections import Counter
for _ in range(int(input())):
	s = input()
	n = int(input())
	arr = list(map(int, input().split()))
	t = list(zip(arr, range(0, n)))
	t.sort()
	fixed = [-1] * n
	ch = 26
	ptr = 0
	while ptr < n:
		b = True
		for (l, m) in t:
			d = 0
			for i in range(n):
				if fixed[i] > ch:
					d += abs(i - m)
			if d == l:
				t.remove((l, m))
				fixed[m] = ch
				b = False
				ptr += 1
		if b:
			ch -= 1
	c = Counter(s)
	c = list(c.items())
	c.sort()
	m = min(fixed)
	ch = 26
	while ch >= m:
		cn = fixed.count(ch)
		while cn > c[-1][1]:
			c.pop()
		for i in range(n):
			if fixed[i] == ch:
				fixed[i] = c[-1][0]
		c.pop()
		ch -= 1
	print(''.join(fixed))


T = int(input())
for _ in range(T):
	s = input().strip()
	m = int(input())
	b = list(map(int, input().strip().split()))
	letters = [0] * 26
	for l in s:
		letters[ord(l) - 97] += 1
	z = []
	for (i, x) in enumerate(b):
		if x == 0:
			z.append(i)
	res = [0] * m
	letter_counts = []
	while len(z) > 0:
		zc = len(z)
		letter_counts.append(zc)
		for zs in z:
			res[zs] = len(letter_counts) - 1
			b[zs] = -1
		for i in range(m):
			index_diff = 0
			for zs in z:
				index_diff += abs(zs - i)
			b[i] -= index_diff
		z = []
		for (i, x) in enumerate(b):
			if x == 0:
				z.append(i)
	letter_map = []
	i = 0
	j = 25
	while i < len(letter_counts) and j > -1:
		if letters[j] >= letter_counts[i]:
			letter_map.append(chr(j + 97))
			i += 1
		j -= 1
	word = ''
	for r in res:
		word += letter_map[r]
	print(word)


def findval(x, arr):
	ans = 0
	for i in arr:
		tem = x - i
		if tem < 0:
			tem = tem * -1
		ans = ans + tem
	return ans

def findmin(arr, nrr):
	res = []
	for i in range(len(arr)):
		if arr[i] == -1:
			continue
		nu = findval(i, nrr)
		if nu == arr[i]:
			res.append(i)
			arr[i] = -1
	return (arr, res)
T = int(input())
for _ in range(T):
	s = input().rstrip()
	dic = {}
	for i in s:
		dic[i] = 0
	for i in s:
		dic[i] += 1
	s = ''
	for i in dic:
		s = s + i
	s = sorted(s)
	s.reverse()
	M = int(input())
	arr = list(map(int, input().rstrip().split()))
	ns = []
	ls = [0 for i in range(M)]
	while len(ns) != M:
		(arr, res) = findmin(arr, ns)
		ns = ns + res
		for i in range(len(s)):
			if dic[s[i]] >= len(res):
				chara = s[i]
				s = s[i + 1:]
				break
		for i in res:
			ls[i] = chara
	s = ''
	for i in range(M):
		s = s + ls[i]
	print(s)


import math
t = int(input())
rez = []
for i in range(t):
	s = input()
	m = int(input())
	b = input().split(' ')
	re = []
	rezu = ''
	for j in range(m):
		b[j] = int(b[j])
		re.append('')
	k = []
	al = 'abcdefghijklmnopqrstuvwxyz'
	n = len(al)
	for j in range(n):
		k.append(0)
	for j in range(len(s)):
		k[al.index(s[j])] += 1
	ind = 0
	while ind != -1:
		index = []
		kk = 0
		for j in range(m):
			if b[j] == 0:
				index.append(j)
				kk += 1
		if kk != 0:
			for j in range(n - 1, -1, -1):
				if k[j] >= kk:
					for y in index:
						re[y] = al[j]
					k[j] = 0
					n = j
					break
			for j in range(m):
				if b[j] != 0:
					for y in index:
						b[j] -= abs(y - j)
				else:
					b[j] = -1
		else:
			ind = -1
	for j in range(m):
		rezu += re[j]
	rez.append(rezu)
for i in range(len(rez)):
	print(rez[i])


from collections import Counter as C

def checkComplete(t):
	for c in t:
		if c == 'A':
			return False
	return True
t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	b = [int(x) for x in input().split()]
	cnt = C(s)
	letterCnts = []
	for (letter, count) in cnt.items():
		letterCnts.append([letter, count])
	letterCnts.sort(key=lambda x: x[0], reverse=True)
	t = ['A' for _ in range(m)]
	indexes = []
	for i in range(m):
		if b[i] == 0:
			indexes.append(i)
	for j in range(len(letterCnts)):
		if letterCnts[j][1] >= len(indexes):
			break
	for idx in indexes:
		t[idx] = letterCnts[j][0]
	while True:
		if checkComplete(t):
			print(''.join(t))
			break
		j += 1
		b_ = [-1 for _ in range(m)]
		for i in range(m):
			if t[i] == 'A':
				total = 0
				for idx in indexes:
					total += abs(idx - i)
				b_[i] = total
		newIndexes = []
		for i in range(m):
			if b[i] == b_[i]:
				newIndexes.append(i)
		while True:
			if letterCnts[j][1] >= len(newIndexes):
				break
			j += 1
		for idx in newIndexes:
			t[idx] = letterCnts[j][0]
		indexes = indexes + newIndexes


from math import *

def r1(t):
	return t(input())

def r2(t):
	return [t(i) for i in input().split()]

def r3(t):
	return [t(i) for i in input()]
for _ in range(r1(int)):
	s = r3(str)
	m = r1(int)
	b = r2(int)
	s.sort()
	mp = {}
	for i in s:
		mp[i] = 0
	for i in s:
		mp[i] += 1
	t = ['' for i in range(m)]
	for i in range(m):
		ind = []
		cnt = 0
		for j in range(m):
			if b[j] == 0:
				ind.append(j)
				cnt += 1
		if cnt == 0:
			break
		for x in ind:
			for j in range(m):
				b[j] -= max(abs(x - j), 1)
		tk = ''
		tkeys = list(sorted(list(mp.keys()), reverse=True))
		for k in tkeys:
			if mp[k] >= len(ind):
				tk = k
			del mp[k]
			if len(tk) > 0:
				break
		for x in ind:
			t[x] = tk
	print(''.join(t))


from collections import Counter
T = int(input())
for t in range(T):
	s = list(input())
	m = int(input())
	(*b,) = map(int, input().split())
	ans = [''] * m
	s.sort()
	s.reverse()
	cnt = Counter(s)
	prev = ''
	for c in s:
		if prev == c:
			continue
		ids = []
		for i in range(m):
			if ans[i] == '' and b[i] == 0:
				ids.append(i)
		if len(ids) <= cnt[c]:
			for i in ids:
				ans[i] = c
				for j in range(m):
					b[j] -= abs(i - j)
		prev = c
	print(''.join(ans))


from collections import defaultdict
for _ in range(int(input())):
	l = [0] * 26
	s = input()
	n = int(input())
	b = list(map(int, input().split()))
	ans = [None] * n
	for char in s:
		l[25 - (ord(char) - 97)] += 1
	c = 0
	ind = []
	for i in range(n):
		if b[i] == 0:
			c += 1
			ind.append(i)
	for char in range(26):
		if l[char] >= c:
			l[char] = -1
			for i in ind:
				ans[i] = chr(97 + 25 - char)
			break
		else:
			l[char] = -1
	while c != n:
		c1 = 0
		temp = []
		for i in range(n):
			if b[i] != 0:
				s = 0
				for j in ind:
					s += abs(i - j)
				if s == b[i]:
					c += 1
					c1 += 1
					b[i] = 0
					temp.append(i)
		for char in range(26):
			if l[char] >= c1:
				l[char] = -1
				for k in temp:
					ans[k] = chr(97 + 25 - char)
				break
			else:
				l[char] = -1
		ind += temp
	print(''.join(ans))


q = int(input())
for _ in range(q):
	letters = [0] * 26
	s = input()
	for a in s:
		letters[ord(a) - ord('a')] += 1
	m = int(input())
	b = list(map(int, input().split()))
	t = ['0'] * m
	deleted = 0
	lastletter = 25
	while deleted < m:
		x = b.count(0)
		while letters[lastletter] < x:
			lastletter -= 1
		zeros = []
		for qq in range(len(b)):
			if b[qq] == 0:
				t[qq] = chr(ord('a') + lastletter)
				zeros.append(qq)
				b[qq] = -1
		deleted += x
		for f in range(len(b)):
			if b[f] >= 0:
				for df in zeros:
					b[f] -= abs(df - f)
		lastletter -= 1
	print(''.join(t))


def main():
	q = int(input())
	for _ in range(q):
		s = input()
		m = int(input())
		b = [int(x) for x in input().split()]
		solve(s, m, b)

def solve(s, m, b):
	letters = sorted(set(s), reverse=True)
	t = ['X'] * m
	for l in letters:
		if s.count(l) < b.count(0):
			continue
		zero = [i for i in range(m) if b[i] == 0]
		positive = [j for j in range(m) if b[j] > 0]
		for i in zero:
			t[i] = l
			for j in positive:
				b[j] -= abs(i - j)
			b[i] = -1
	print(''.join(t))
main()


q = int(input())
for z in range(q):
	s = list(input())
	n = int(input())
	arr = list(map(int, input().split(' ')))
	res = [0 for _ in range(n)]
	s.sort(reverse=True)
	si = 0
	while True:
		f = False
		zv = []
		for i in range(arr.__len__()):
			if arr[i] == 0:
				f = True
				zv.append(i)
				arr[i] = -1
		for j in range(arr.__len__()):
			if arr[j] > 0:
				for i in zv:
					arr[j] -= abs(j - i)
		if not f:
			break
		else:
			i = si
			while True:
				ff = False
				letter = s[i]
				for j in range(i, i + zv.__len__()):
					if s[j] != letter:
						i = j
						ff = True
						break
				if not ff:
					for k in range(zv.__len__()):
						res[zv[k]] = s[i]
					si = i
					while si < s.__len__() and s[si] == letter:
						si += 1
					break
	print(''.join(res))


for _ in range(int(input())):
	s = list(input())
	n = int(input())
	l = list(map(int, input().split()))
	s.sort()
	ans = ['' for i in range(n)]
	while n > 0:
		k = []
		for i in range(len(l)):
			if l[i] == 0:
				l[i] = -1
				k.append(i)
		for i in k:
			for j in range(len(l)):
				l[j] = l[j] - abs(i - j)
		z = len(k)
		st = []
		while len(st) != z:
			if len(st) == 0:
				st.append(s.pop(-1))
			elif st[-1] == s[-1]:
				st.append(s.pop(-1))
			else:
				st = []
		while len(s) != 0 and s[-1] == st[-1]:
			s.pop(-1)
		for i in k:
			if n <= 0:
				break
			ans[i] = st[-1]
			n -= 1
	print(''.join(ans))


from collections import Counter

def visit(s, dist, digits, letters, mapping, letter_stat, letter_idx_start):
	for letter_idx in range(letter_idx_start, len(letters)):
		ch = letters[letter_idx]
		indices = []
		for z in range(len(dist)):
			if mapping[z] == '?' and dist[z] == sum((abs(z - j) for j in range(len(dist)) if mapping[j] != '?' and mapping[j] > ch)):
				indices.append(z)
		if letter_stat[ch] >= len(indices):
			for z in indices:
				mapping[z] = ch
			letter_stat[ch] -= len(indices)
			if mapping.count('?') == 0:
				return True
			match = visit(s, dist, digits, letters, mapping, letter_stat, letter_idx_start=letter_idx + 1)
			if match:
				return True
			for z in indices:
				mapping[z] = '?'
			letter_stat[ch] += 1
		else:
			pass
	return False

def solve(s, dist):
	letter_stat = Counter(s)
	digits = sorted(([v, i] for (i, v) in enumerate(dist)))
	mapping = ['?'] * len(dist)
	letters = sorted(set(letter_stat), reverse=True)
	visit(s, dist, digits, letters, mapping, letter_stat, 0)
	return ''.join(mapping)
for _ in range(int(input())):
	s = input()
	m = int(input())
	(*dist,) = map(int, input().split())
	print(solve(s, dist))


import string

def main(s: str, b):
	cnt = [(c, s.count(c)) for c in string.ascii_lowercase]
	res = ['' for c in b]
	while 0 in b:
		z_cnt = b.count(0)
		while cnt[-1][1] < z_cnt:
			cnt.pop()
		c = cnt.pop()[0]
		zeros = []
		for (i, v) in enumerate(b):
			if v == 0:
				res[i] = c
				zeros.append(i)
				b[i] = -1
		for (i, v) in enumerate(b):
			if v != -1:
				b[i] -= sum((abs(z - i) for z in zeros))
	return ''.join(res)
_t = int(input())
for _ in range(_t):
	_s = input()
	input()
	_b = [int(x) for x in input().split()]
	print(main(_s, _b))


from collections import defaultdict
a = int(input())
for i in range(a):
	s = input()
	x = int(input())
	z = list(map(int, input().split()))
	result = [0 for i in range(len(z))]
	pos = []
	tp = []
	for i in range(len(z)):
		if z[i] == 0:
			result[i] = 1
			pos.append(i)
			tp.append(i)
			z[i] == 0
	cha = 1
	zer = len(result) - result.count(1)
	while zer > 0:
		pos = tp.copy()
		tp = []
		cha += 1
		for i in range(len(result)):
			if not result[i]:
				for j in range(len(pos)):
					z[i] -= abs(pos[j] - i)
				if z[i] == 0:
					tp.append(i)
					result[i] = cha
					zer -= 1
	ans = []
	dl = defaultdict(int)
	al = defaultdict(int)
	for i in range(len(result)):
		dl[result[i]] += 1
	for i in range(len(s)):
		ans.append(s[i])
		al[s[i]] += 1
	maxa = max(result)
	ans = list(set(ans))
	ans.sort()
	ma = defaultdict(str)
	index = len(ans) - 1
	ch = 1
	while ch <= maxa:
		if al[ans[index]] >= dl[ch]:
			ma[ch] = ans[index]
			ch += 1
		index -= 1
	fin = []
	for i in range(len(result)):
		fin.append(ma[result[i]])
	print(''.join(map(str, fin)))


def f():
	a = input()
	n = int(input())
	b = list(map(int, input().split(' ')))
	string = ['0'] * len(b)
	a = list(a)
	a.sort(reverse=True)
	temp = []
	while 1:
		for i in range(0, len(b)):
			flag = 0
			s = 0
			if string[i] == '0':
				for j in range(0, len(temp)):
					if temp[j][0] > a[0]:
						s += abs(temp[j][1] - i)
				if s == b[i]:
					flag = 1
					temp.append([a[0], i])
					string[i] = a[0]
					break
		if flag == 0:
			string[temp[len(temp) - 1][1]] = '0'
			temp.pop(len(temp) - 1)
			continue
		if len(temp) == len(b):
			break
		a.pop(0)
	print(*string, sep='')
for i in range(int(input())):
	f()


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	values = {}
	for num in b:
		if num not in values:
			values[num] = 0
		values[num] += 1
	letters = {}
	for c in s:
		if c not in letters:
			letters[c] = 0
		letters[c] += 1
	sortedLetters = []
	sortedValues = []
	for elem in letters:
		sortedLetters.append((elem, letters[elem]))
	sortedLetters.sort()
	ans = ['' for _ in range(m)]
	while True:
		done = True
		toChange = []
		for i in range(m):
			dist = 0
			if ans[i] != '':
				continue
			for j in range(m):
				if ans[j] != '':
					dist += abs(i - j)
			if dist == b[i]:
				toChange.append(i)
		if len(toChange) == 0:
			break
		cnt = len(toChange)
		while sortedLetters[-1][1] < cnt:
			sortedLetters.pop(-1)
		for i in toChange:
			ans[i] = sortedLetters[-1][0]
		sortedLetters.pop(-1)
	print(''.join(ans))


t = int(input())
for _ in range(t):
	di = {}
	for i in input():
		if i in di:
			di[i] += 1
		else:
			di[i] = 1
	li = list(di.items())
	li.sort(reverse=True)
	m = int(input())
	b = list(map(int, input().split()))
	now = [0] * m
	ans = [None] * m
	for (c, cnt) in li:
		tmp = 0
		for i in range(m):
			if ans[i] is None and b[i] == now[i]:
				tmp += 1
		if tmp > cnt:
			continue
		nxt = now[:]
		for i in range(m):
			if b[i] != now[i] or ans[i] is not None:
				continue
			ans[i] = c
			for j in range(m):
				nxt[j] += abs(i - j)
		now = nxt
	print(''.join(ans))


import sys
from collections import Counter, deque
T = int(input())
for _ in range(T):
	s = input()
	(m, b) = (int(input()), list(map(int, input().split())))
	(cc, t) = ([0] * m, [0] * m)
	ch = 1
	while True:
		can = []
		for i in range(m):
			if not t[i] and b[i] == cc[i]:
				t[i] = ch
				can.append(i)
		ch += 1
		if not can:
			break
		for i in range(m):
			for j in can:
				if not t[i]:
					cc[i] += abs(i - j)
	tcc = Counter(t)
	tcc = list(sorted(list(tcc.items())))
	scc = Counter(s)
	scc = list(sorted(list(scc.items()), reverse=True))
	(chm, p) = ({}, 0)
	for (ch, cc) in scc:
		(ch_, cc_) = tcc[p]
		if cc >= cc_:
			chm[ch_] = ch
			p += 1
		if p == len(tcc):
			break
	res = [chm[t[i]] for i in range(m)]
	print(''.join(res))


q = int(input())
for _ in range(q):
	t = str(input())
	m = int(input())
	b = list(map(int, input().split()))
	alpha = 'abcdefghijklmnopqrstuvwxyz'
	counts = dict()
	t_chars = list()
	for i in range(len(t)):
		if t[i] not in counts.keys():
			counts[t[i]] = 0
		counts[t[i]] += 1
	ans = list()
	for i in range(len(alpha)):
		if alpha[i] in counts.keys():
			t_chars.append(counts[alpha[i]])
		else:
			t_chars.append(0)
	point = len(alpha) - 1
	zeroes = 0
	for i in range(m):
		ans.append('')
		if b[i] == 0:
			zeroes += 1
	while t_chars[point] < zeroes:
		point -= 1
	visited = set()
	for i in range(m):
		if b[i] == 0:
			ans[i] = alpha[point]
			visited.add(i)
	point -= 1
	left = m - zeroes
	while left != 0:
		next = set()
		for i in range(m):
			if i not in visited:
				num = 0
				for e in visited:
					num += abs(i - e)
				if num == b[i]:
					next.add(i)
		while t_chars[point] < len(next):
			point -= 1
		for e in next:
			ans[e] = alpha[point]
			visited.add(e)
		point -= 1
		left -= len(next)
	for i in range(m):
		print(ans[i], end='')
	print()


from collections import Counter
q = int(input())
for _ in range(q):
	s = input()
	m = int(input())
	b = [int(x) for x in input().split()]
	t = ['' for _ in range(m)]
	sd = [(k, v) for (k, v) in Counter(s).items()]
	sd.sort(key=lambda x: x[0], reverse=True)
	count = 0
	sdi = 0
	while count != m:
		zeros = [i for (i, x) in enumerate(b) if x == 0]
		lz = len(zeros)
		count += lz
		while sd[sdi][1] < lz:
			sdi += 1
		c = sd[sdi][0]
		for zero_index in zeros:
			t[zero_index] = c
			b[zero_index] = -1
		sdi += 1
		for i in range(m):
			if b[i] < 0:
				continue
			for zero_index in zeros:
				b[i] -= abs(i - zero_index)
	print(''.join(t))


def counter(l, a):
	count = 0
	for i in range(len(l)):
		if l[i] == a:
			count += 1
	return count
t = int(input())
for _ in range(t):
	s = list(input())
	n = len(s)
	m = int(input())
	b = list(map(int, input().split()))
	t = ['0'] * m
	while True:
		z = []
		for i in range(m):
			if b[i] == 0:
				z.append(i)
		maxx = max(s)
		if counter(s, maxx) >= len(z):
			for i in z:
				t[i] = maxx
				for j in range(m):
					if j not in z:
						b[j] -= abs(i - j)
				b[i] = -1
			for i in range(n):
				if s[i] == maxx:
					s[i] = '0'
		else:
			for i in range(n):
				if s[i] == maxx:
					s[i] = '0'
		if b == [-1] * m or s == ['0'] * n:
			break
	for i in range(m):
		print(t[i], end='')
	print('')


import sys
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

def solve():
	s = input()
	(m,) = I()
	b = I()
	count = dd(int)
	for i in s:
		count[i] += 1
	evr = sorted(set(s), reverse=True)
	cur = 0
	ans = ['0'] * m
	idx = []
	while cur < len(evr):
		now = []
		for i in range(m):
			if ans[i] != '0':
				continue
			rank = 0
			for j in idx:
				rank += abs(i - j)
			if rank == b[i]:
				now.append(i)
		while cur < len(evr) and count[evr[cur]] < len(now):
			cur += 1
		for i in now:
			ans[i] = evr[cur]
		idx += now
		cur += 1
	print(''.join(ans))
(t,) = I()
while t:
	t -= 1
	solve()


for ii in range(int(input())):
	s = input()
	m = int(input())
	l = [int(i) for i in input().split()]
	dic = {}
	for i in s:
		if i in dic:
			dic[i] += 1
		else:
			dic[i] = 1
	li = sorted(list(dic.keys()))
	dic2 = {}
	for i in range(m):
		dic2[i] = l[i]
	j = len(li) - 1
	ans = ['' for i in range(m)]
	while j >= 0:
		pos = [i for i in list(dic2.keys()) if dic2[i] == 0]
		if pos == []:
			break
		if dic[li[j]] >= len(pos):
			for i in pos:
				ans[i] = li[j]
				del dic2[i]
			for i in list(dic2.keys()):
				for p in pos:
					dic2[i] -= abs(i - p)
		j -= 1
	print(''.join(ans))


import sys
import math
from math import factorial, inf, gcd, sqrt
from heapq import *
from functools import *
from itertools import *
from collections import *
from typing import *
from bisect import *
import random
sys.setrecursionlimit(10 ** 5)

def rarray():
	return [int(i) for i in input().split()]
t = 1
t = int(input())
for ii in range(t):
	s = input()
	c = Counter(s)
	s = sorted(c.keys(), reverse=True)
	m = int(input())
	a = rarray()
	ans = [''] * m
	n = 0
	inp = 0
	while n < m:
		p = [i for i in range(m) if a[i] == 0 and ans[i] == '']
		t = len(p)
		while c[s[inp]] < t:
			inp += 1
		for i in p:
			ans[i] = s[inp]
		for (i, j) in enumerate(a):
			if j > 0:
				for k in p:
					a[i] -= abs(i - k)
		inp += 1
		n += t
	print(''.join(ans))


t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	s_simplified = []
	for i in set(s):
		s_simplified.append([i, s.count(i)])
	s_simplified.sort(key=lambda x: x[0])
	positions = []
	decoded_string = [-1] * m
	while len([i for i in b if i < 0]) != len(b):
		maxpos = []
		while 0 in b:
			ct = b.count(0)
			while ct > s_simplified[-1][1]:
				s_simplified.pop()
			maximum = b.index(0)
			maxpos.append(maximum)
			decoded_string[maximum] = s_simplified[-1][0]
			b[maximum] = -1
		for maximum in maxpos:
			for i in range(len(b)):
				if b[i] != 0:
					b[i] -= abs(i - maximum)
		s_simplified.pop()
	print(''.join(decoded_string))


t = int(input())
for _ in range(t):
	s = list(input())
	m = int(input())
	a = list(map(int, input().split()))
	s.sort()
	count = 0
	flag = True
	ans = [0] * m
	ptr = len(s) - 1
	while count < m:
		temp = []
		for i in range(m):
			if a[i] == 0:
				temp.append(i)
				a[i] = -1
		count = count + len(temp)
		c = 1
		if c != len(temp):
			for j in range(ptr - 1, -1, -1):
				if s[j] == s[j + 1]:
					c += 1
				else:
					c = 1
				if c == len(temp):
					ptr = j + c - 1
					break
		ch = s[ptr]
		for i in temp:
			ans[i] = s[ptr]
			ptr -= 1
			j = 1
			while i - j >= 0:
				if a[i - j] > 0:
					a[i - j] = a[i - j] - j
				j += 1
			j = 1
			while i + j < m:
				if a[i + j] > 0:
					a[i + j] -= j
				j += 1
		while ptr >= 0 and s[ptr] == ch:
			ptr -= 1
	for i in ans:
		print(i, end='')
	print()


q = int(input())
for t in range(q):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	a = {}
	output = [''] * m
	outpos = list(range(m))
	for i in s:
		if i in a:
			a[i] += 1
		else:
			a[i] = 1
	a = sorted(list(a.items()))[::-1]
	c = 0
	v = ''
	newm = m
	fv = 0
	while fv < m:
		nzeros = 0
		zero = []
		for i in range(newm):
			if b[i] == 0:
				nzeros += 1
				zero.append(i)
		f = 0
		for i in a[c:]:
			if i[1] >= nzeros:
				v = i[0]
				f = 1
			c += 1
			if f == 1:
				break
		for i in range(newm):
			if b[i] == 0:
				p = outpos[i]
				output[p] = v
				fv += 1
		for i in range(newm):
			for j in zero:
				if b[i] > 0:
					b[i] -= abs(j - i)
		for i in zero:
			b[i] = -1
			outpos[i] = -1
	print(''.join(output))


for _ in range(int(input())):
	s = ['#'] + sorted(list(input()))
	n = int(input())
	b = [-1] + [int(i) for i in input().split()]
	ans = ['#'] * (n + 1)
	while 0 in b:
		zero = []
		for i in range(1, n + 1):
			if b[i] == 0:
				zero.append(i)
				b[i] = -1
		while s.count(s[-1]) < len(zero):
			p = s[-1]
			while s[-1] == p:
				s.pop()
		p = 0
		for i in zero:
			p = ans[i] = s[-1]
		while s[-1] == p:
			s.pop()
		for i in range(1, n + 1):
			if ans[i] == '#':
				for j in zero:
					b[i] -= abs(j - i)
	print(''.join(ans[1:]))


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')

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

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

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

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	s = ri()
	m = int(ri())
	b = Ri()
	lis = []
	while True:
		tlis = []
		flag = True
		for i in range(len(b)):
			if b[i] == 0:
				tlis.append(i)
				b[i] = INF
				flag = False
		if flag:
			break
		lis.append(tlis[:])
		for i in range(len(b)):
			for j in range(len(tlis)):
				b[i] -= abs(tlis[j] - i)
	dic = {}
	for i in s:
		dic[i] = dic.get(i, 0) + 1
	ans = [''] * m
	cur = 0
	for i in range(25, -1, -1):
		ch = chr(ord('a') + i)
		if ch in dic and dic[ch] >= len(lis[cur]):
			for j in lis[cur]:
				ans[j] = ch
			cur += 1
		if cur == len(lis):
			break
	print(''.join(ans))


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for ii in range(int(input())):
	s = input()
	m = int(input())
	n = len(s)
	b = list(map(int, input().split()))
	freq = [0] * 26
	for i in range(n):
		freq[ord(s[i]) - ord('a')] += 1
	c = 25
	ans = ['.'] * m
	while True:
		zeros = []
		for i in range(m):
			if b[i] == 0:
				zeros.append(i)
				b[i] = -1
		if len(zeros) == 0:
			break
		while c >= 0 and freq[c] < len(zeros):
			c -= 1
		for ind in zeros:
			ans[ind] = chr(ord('a') + c)
		for i in range(m):
			if ans[i] == '.' or ord(ans[i]) - ord('a') < c:
				for ind in zeros:
					b[i] -= abs(ind - i)
		c -= 1
	for i in ans:
		print(i, end='')
	print()


def main():
	q = int(input())
	for _ in range(q):
		s = input()
		m = int(input())
		t = ['0' for __ in range(m)]
		b = list(map(int, input().split()))
		l = sorted(s)
		d = {}
		for x in s:
			if x in d:
				d[x] += 1
			else:
				d[x] = 1
		while True:
			idxs = []
			num0s = 0
			for (c, el) in enumerate(b):
				if el == 0:
					num0s += 1
					idxs.append(c)
					b[c] = -1
			if not num0s:
				break
			while True:
				chosen = l[-1]
				freq = d[chosen]
				if freq < num0s:
					l = l[:-freq]
				else:
					for ix in idxs:
						t[ix] = chosen
					l = l[:-freq]
					break
			for i in range(len(b)):
				for idx in idxs:
					b[i] -= abs(i - idx)
		print(''.join(t))
main()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
import copy

def gift():
	for _ in range(t):
		array = list(input())
		m = int(input())
		nums = list(map(int, input().split()))
		list1 = [0] * 26
		for a in array:
			list1[ord(a) - 97] += 1
		ans = [0] * m
		ind = 25
		while max(nums) >= 0:
			L = []
			for i in range(m):
				if nums[i] == 0:
					L.append(i)
					nums[i] -= 1
			lenl = len(L)
			while list1[ind] < lenl:
				ind -= 1
			for l in L:
				ans[l] = ind
			ind -= 1
			for l in L:
				for i in range(m):
					nums[i] -= abs(i - l)
		yield ''.join([chr(a + 97) for a in ans])
t = int(input())
ans = gift()
print(*ans, sep='\n')


def task_D():
	t = int(input())
	for _ in range(t):
		string = input()
		m = int(input())
		array_b = list(map(int, input().split()))
		char_dict = {c: string.count(c) for c in set(string)}
		ans = ['' for _ in range(m)]
		find_char_count = 0
		while find_char_count < m:
			count_0 = 0
			list_count_0 = []
			for i in range(m):
				if array_b[i] == 0:
					count_0 += 1
					list_count_0.append(i)
			while char_dict[max(char_dict)] < count_0:
				char_dict.pop(max(char_dict))
			max_char = max(char_dict)
			for pos in list_count_0:
				ans[pos] = max_char
			char_dict.pop(max_char)
			for i in range(m):
				if array_b[i] != 0:
					for pos in list_count_0:
						array_b[i] -= abs(i - pos)
				else:
					array_b[i] = -1
			find_char_count += count_0
		print(''.join(ans))

def main():
	task_D()
main()


import sys
try:
	sys.stdin = open('inputs.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
finally:
	input = sys.stdin.readline
	print = sys.stdout.write
t = int(input())
for _ in range(t):
	s = input().strip()
	m = int(input())
	b = list(map(int, input().split()))
	alphas = [0] * 26
	for ch in s:
		alphas[ord(ch) - 97] += 1
	out = [0] * m
	z = set()
	alpha_no = 25
	a = []
	while True:
		count = 0
		zs = []
		for j in range(m):
			if b[j] != 0:
				for zind in a:
					b[j] -= abs(j - zind)
			if b[j] == 0 and j not in z:
				count += 1
				zs.append(j)
		while alphas[alpha_no] < count:
			alpha_no -= 1
		for i in zs:
			out[i] = chr(alpha_no + 97)
			z.add(i)
		alpha_no -= 1
		a = zs
		if len(z) == m:
			break
	print(''.join(out))
	print('\n')


def works(c, i, prob, btgt, m):
	val = 0
	for j in range(m):
		if prob[j] != ' ' and c < prob[j]:
			val += abs(i - j)
	return val == btgt

def solve0(prob, s, slack, b, m, depth):
	if prob.find(' ') == -1:
		return (prob, True)
	c = s.pop()
	for i in range(m):
		if prob[i] != ' ':
			continue
		if works(c, i, prob, b[i], m):
			(ans, ok) = solve0(prob[:i] + c + prob[i + 1:], s.copy(), slack, b, m, depth + 1)
			if ok:
				return (ans, True)
	if slack > 0:
		(ans, ok) = solve0(prob, s, slack - 1, b, m, depth + 1)
		if ok:
			return (ans, True)
	return ('', False)

def solve(s, m, b):
	s = sorted(s)
	slack = len(s) - m
	(ans, correct) = solve0(' ' * m, s, slack, b, m, 0)
	return ans
cases = int(input().strip())
for _ in range(cases):
	s = input().strip()
	m = int(input().strip())
	b = list(map(int, input().strip().split()))
	print(solve(s, m, b))


for i in range(int(input())):
	a = input()
	b = int(input())
	c = list(map(int, input().split()))
	d = ''.join(sorted(set(a))[::-1])
	e = [None] * b
	f = []
	g = 0
	while g < len(d):
		h2 = []
		for i2 in range(b):
			h = 0
			for i3 in f:
				h += abs(i2 - i3)
			if h == c[i2] and e[i2] == None:
				h2.append(i2)
		if len(h2) <= a.count(d[g]):
			for i2 in h2:
				e[i2] = d[g]
			f += h2
		g += 1
	print(''.join(e))


from pprint import pprint
import sys
q = int(input())
import collections
for _ in range(q):
	s = input()
	m = int(input())
	dat = list(map(int, input().split()))
	l = len(dat)
	datc = collections.Counter(s)
	buf = []
	for k in datc:
		buf.append([k, datc[k]])
	buf.sort(reverse=True)
	fixedNum = 0
	decidedPositions = []
	captalIndex = 0
	finalstr = [None] * l
	while True:
		candidatePos = []
		for i in range(l):
			if i in decidedPositions:
				continue
			cnt = 0
			for j in range(len(decidedPositions)):
				cnt += abs(decidedPositions[j] - i)
			if cnt == dat[i]:
				candidatePos.append(i)
		candidateNum = len(candidatePos)
		while buf[captalIndex][1] < candidateNum:
			captalIndex += 1
		fixedChar = buf[captalIndex][0]
		captalIndex += 1
		for ind in candidatePos:
			finalstr[ind] = fixedChar
			decidedPositions.append(ind)
		fixedNum += candidateNum
		if fixedNum == l:
			break
	print(''.join(finalstr))


for i in range(int(input())):
	(S, s) = (input(), [])
	for i in range(len(S)):
		s.append(S[i])
	s.sort()
	(m, b) = (int(input()), [int(num) for num in input().split()])
	while b.count(0):
		temp = []
		for i in range(m):
			if b[i] == 0:
				temp.append(i)
		while s.count(s[-1]) < len(temp):
			while len(s) > 1 and s[-1] == s[-2]:
				s.pop()
			s.pop()
		k = s[-1]
		while len(s) and s[-1] == k:
			s.pop()
		for i in temp:
			b[i] = k
		for i in range(m):
			for x in temp:
				try:
					b[i] -= abs(i - x)
				except:
					pass
	print(''.join(b))


q = int(input())
for _ in range(q):
	s = str(input())
	m = int(input())
	B = list(map(int, input().split()))
	C = [0] * 26
	for c in s:
		C[ord(c) - ord('a')] += 1
	ans = [-1] * m
	used = set()
	for i in reversed(range(26)):
		if C[i] != 0:
			idx = []
			for (j, b) in enumerate(B):
				if j in used:
					continue
				if b == 0:
					idx.append(j)
			if len(idx) > C[i]:
				continue
			for j in idx:
				ans[j] = i
				used.add(j)
			for k in range(m):
				for j in idx:
					B[k] -= abs(k - j)
	ans = [chr(i + ord('a')) for i in ans]
	print(''.join(ans))


T = int(input())
for _ in range(T):
	s = input()
	m = int(input())
	l = list(map(int, input().split()))
	cnt = [0] * 26
	for i in range(len(s)):
		cnt[ord(s[i]) - 97] += 1
	ze = []
	li = []
	for i in range(m):
		if l[i] == 0:
			li.append(i)
	ze.append(li)
	while 1:
		li = []
		for i in range(m):
			if l[i] != 0:
				for j in range(len(ze[-1])):
					l[i] = l[i] - abs(i - ze[-1][j])
				if l[i] == 0:
					li.append(i)
		if len(li) == 0:
			break
		else:
			ze.append(li)
	ans = [0] * len(ze)
	cnt = cnt[::-1]
	j = 0
	fin = [0] * m
	for i in range(len(ze)):
		num = len(ze[i])
		while j < 26:
			if cnt[j] >= num:
				ans[i] = 26 - j
				j += 1
				break
			j += 1
	for i in range(len(ans)):
		for j in range(len(ze[i])):
			fin[ze[i][j]] = chr(ans[i] + 96)
	print(''.join(fin))


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

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

def fi():
	return int(input())

def si():
	return list(input().rstrip())

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

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
tt = fi()
while tt > 0:
	tt -= 1
	s = si()
	n = len(s)
	m = fi()
	a = li()
	s.sort(reverse=True)
	t = [0 for i in range(m)]
	i = 0
	vis = {}
	for pp in range(m):
		d = []
		for j in range(m):
			if a[j] == 0 and j not in vis:
				d.append(j)
				vis[j] = 1
		if len(d) > 0:
			while pp > 0 and i < n and (s[i] == s[i - 1]):
				i += 1
			while i < n and s[i:].count(s[i]) < len(d):
				i += 1
		for j in range(len(d)):
			t[d[j]] = s[i]
			i += 1
		for j in d:
			for ii in range(m):
				if a[ii] >= abs(ii - j):
					a[ii] -= abs(ii - j)
	print(''.join(t))


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque

def aise():
	global count
	toprocess = []
	for i in range(m):
		if i not in visited:
			su = 0
			for j in z:
				su += abs(i - j)
			if su == l[i]:
				toprocess.append(i)
				visited.add(i)
	while d[se[-1]] < len(toprocess):
		se.pop()
	x = se.pop()
	for i in toprocess:
		ans[i] = x
		z.append(i)
	count -= len(toprocess)
for _ in range(int(input())):
	s = list(input())
	s.sort()
	d = {}
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	m = int(input())
	l = list(map(int, input().split()))
	ans = ['' for i in range(m)]
	z = l.count(0)
	se = sorted(list(set(s)))
	while d[se[-1]] < z:
		se.pop()
	x = se.pop()
	z = []
	visited = set()
	count = m
	for i in range(m):
		if l[i] == 0:
			ans[i] = x
			z.append(i)
			visited.add(i)
	count -= len(z)
	while count > 0:
		aise()
	print(''.join(ans))


for _ in range(int(input())):
	s = input()
	n = int(input())
	l = list(map(int, input().split()))
	has = [0] * 27
	for i in s:
		has[ord(i) - ord('a') + 1] += 1
	ha = [(i, has[i]) for i in range(1, 27)]
	ha.sort(reverse=True)
	ans = ['' for i in range(n)]
	p = 0
	for i in range(n):
		v = []
		new_p = 0
		for k in range(n):
			if l[k] == 0:
				v.append(k)
				new_p = k
		for j in range(p, 26):
			if ha[j][1] >= len(v):
				p = j + 1
				break
		for k in v:
			ans[k] = chr(ord('a') + ha[p - 1][0] - 1)
			l[k] = -1
		for t in v:
			for k in range(n):
				if l[k] > 0:
					l[k] = l[k] - abs(k - t)
	print(''.join(ans))


def get_encoded(arr, s, m):
	vocab = {}
	for letter in s:
		if letter in vocab:
			vocab[letter] += 1
		else:
			vocab[letter] = 1
	res = [''] * m
	stop_arr = [-1] * m
	while arr != stop_arr:
		imin = []
		for (i, elem) in enumerate(arr):
			if elem == 0:
				imin.append(i)
		letter_count = 0
		while len(imin) > letter_count:
			max_key = max(vocab.keys())
			letter_count = vocab[max_key]
			vocab.pop(max_key)
		for i in imin:
			res[i] = max_key
		for (i, elem) in enumerate(arr):
			if i in imin:
				arr[i] = -1
			elif elem > -1:
				for big_letter in imin:
					arr[i] -= abs(i - big_letter)
	return ''.join(res)
t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	arr = list(map(int, input().split()))
	res = get_encoded(arr, s, m)
	print(res)


t = int(input())
for _ in range(t):
	string = [s for s in input()]
	dic = {}
	arr = []
	for i in string:
		dic[i] = dic.get(i, 0) + 1
	for (i, j) in dic.items():
		arr.append((i, j))
	arr.sort(key=lambda x: x[0])
	n = int(input())
	a = [int(c) for c in input().split()]
	ans = [None for i in range(n)]
	while True:
		zeroindex = []
		zc = 0
		for i in range(n):
			if a[i] == 0:
				zeroindex.append(i)
				zc += 1
		if zc == 0:
			break
		while True:
			pair = arr.pop()
			if pair[1] >= zc:
				break
		for i in zeroindex:
			ans[i] = pair[0]
			a[i] = float('inf')
			for j in range(1, n - i):
				a[i + j] = a[i + j] - j
			for j in range(i + 1):
				a[i - j] = a[i - j] - j
	print(''.join([str(x) for x in ans]))


t = int(input())
for z in range(t):
	st = list(input())
	n = int(input())
	arr = list(map(int, input().split()))
	d = {}
	for i in range(len(st)):
		if st[i] not in d:
			d[st[i]] = 0
		d[st[i]] += 1
	flag = [1 for i in range(n)]
	a = []
	for i in range(n):
		if arr[i] == 0:
			a.append(i)
	(res, res2) = ([], [])
	while len(a) > 0:
		ne = []
		res.append(len(a))
		res2.append(a)
		for i in a:
			flag[i] = 0
		for i in a:
			for j in range(0, i):
				if flag[j] == 1:
					arr[j] -= abs(i - j)
					if arr[j] == 0:
						flag[j] = 0
						ne.append(j)
			for j in range(i + 1, n):
				if flag[j] == 1:
					arr[j] -= abs(i - j)
					if arr[j] == 0:
						flag[j] = 0
						ne.append(j)
		a = ne
	j = 0
	ans = ['a' for i in range(n)]
	for i in range(25, -1, -1):
		c = chr(97 + i)
		if c in d:
			if d[c] >= res[0]:
				for j in res2[0]:
					ans[j] = c
				del res[0]
				del res2[0]
		if len(res) == 0:
			break
	print(''.join(ans))


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from functools import *
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')

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

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

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return (flag, prime)

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

def lcm(a, b):
	return a * b // gcd(a, b)

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None

@bootstrap
def dfs(r):
	vis[r] = 1
	ans[r - 1] = val[r]
	for ch in g[r]:
		if d[ch] > d[r]:
			yield dfs(ch)
			ans[r - 1] = min(ans[r - 1], ans[ch - 1])
	yield None
t = N()
for i in range(t):
	s = input()
	m = N()
	b = RLL()
	n = k = len(b)
	lay = []
	while k:
		res = []
		for i in range(n):
			if b[i] == 0:
				res.append(i)
				b[i] = -1
				k -= 1
		for i in range(n):
			if b[i] > 0:
				for j in res:
					b[i] -= abs(i - j)
		lay.append(res)
	c = Counter(s)
	i = 0
	ans = ['-'] * n
	for ch in sorted(c.keys(), reverse=True):
		if c[ch] >= len(lay[i]):
			for j in lay[i]:
				ans[j] = ch
			i += 1
			if i >= len(lay):
				break
	ans = ''.join(ans)
	print(ans)


import sys, math, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from decimal import Decimal
from fractions import Fraction

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 20
mod = 10 ** 9 + 7
for i in range(int(data())):
	s = data()
	m = int(data())
	b = mdata()
	cnt = m - 1
	l = []
	while cnt != m:
		cnt = 0
		l1 = []
		for i in range(m):
			if b[i] == 0:
				l1.append(i + 1)
				b[i] = -1
			else:
				cnt += 1
		for i in l1:
			for j in range(m):
				if j + 1 < i and b[j] != -1:
					b[j] -= i - j - 1
				elif j + 1 > i and b[j] != -1:
					b[j] -= j + 1 - i
		l.append(l1)
	l.pop()
	l = l[::-1]
	d = dd(int)
	ans = [0] * m
	for i in range(len(s)):
		d[s[i]] += 1
	for i in sorted(d.keys(), reverse=True):
		if d[i] >= len(l[-1]):
			for j in l[-1]:
				ans[j - 1] = i
			l.pop()
		if len(l) == 0:
			break
	out(''.join(ans))


import collections
q = int(input())
for _ in range(q):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ctr_s = list(reversed(sorted(collections.Counter(s).items())))
	ctr_b = list(sorted(collections.Counter(b).items()))
	ans = ['*'] * m
	s_idx = 0
	cnt = 0
	while True:
		if cnt == m:
			break
		zero_idxs = [i for i in range(m) if b[i] == 0]
		while len(zero_idxs) > ctr_s[s_idx][1]:
			s_idx += 1
		for idx in zero_idxs:
			ans[idx] = ctr_s[s_idx][0]
			for i in range(m):
				if b[i] > 0:
					b[i] -= abs(idx - i)
			b[idx] = -1
		s_idx += 1
		cnt += len(zero_idxs)
	print(''.join(ans))


from collections import Counter
for t in range(int(input())):
	st = input()
	tot = len(st)
	m = int(input())
	arr = list(map(int, input().split()))
	sor = sorted(st)
	count = Counter(st)
	final = [''] * m
	while arr.count(-1) != m:
		c = arr.count(0)
		g = []
		for i in range(m):
			if arr[i] == 0:
				g.append(i)
		x = sor[-1]
		if count[x] >= c:
			for i in range(count[x]):
				del sor[-1]
			for i in range(m):
				if arr[i] == 0:
					arr[i] = -1
					final[i] = x
				if arr[i] != -1:
					for j in g:
						arr[i] -= abs(i - j)
		else:
			for i in range(count[x]):
				del sor[-1]
	print(''.join(final))


for i in range(int(input())):
	original = list(input())
	s = sorted(set(original))
	m = int(input())
	b = list(map(int, input().split()))
	ans = [None] * m
	while sum(b) != -m:
		zeros = set()
		for i in range(m):
			if b[i] == 0:
				zeros.add(i)
				b[i] = -1
		while True:
			letra = s.pop()
			if len(zeros) <= original.count(letra):
				for i in zeros:
					ans[i] = letra
				break
		for i in zeros:
			for n in range(m):
				if b[n] != -1:
					b[n] -= abs(i - n)
	print(''.join(ans))


import sys
import math
from collections import defaultdict
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def solve():
	groups = []
	while True:
		pos = []
		for i in range(m):
			if b[i] == 0:
				pos.append(i)
		if not pos:
			break
		groups.append(pos)
		for i in range(m):
			if b[i] == 0:
				b[i] = math.inf
			else:
				for p in pos:
					b[i] -= abs(i - p)
	s1 = sorted(s)
	s_map = defaultdict(int)
	for c in s1:
		s_map[c] += 1
	res = [''] * m
	for g in groups:
		while s_map[s1[-1]] < len(g):
			last = s1[-1]
			while s1 and s1[-1] == last:
				s1.pop()
		last = s1[-1]
		for p in g:
			res[p] = last
		while s1 and s1[-1] == last:
			s1.pop()
	return res
tests = inp()
for t in range(tests):
	s = insr()
	m = inp()
	b = inlt()
	print(''.join(solve()))


def get_ans(s, m, arr):
	ans = [-1 for _ in range(m)]
	for i in range(m):
		if arr[i] == 0:
			ans[i] = 0
	q = 1
	for _ in range(m):
		upd = []
		for curr in range(m):
			if ans[curr] == -1:
				b = 0
				for comp in range(m):
					if ans[comp] > ans[curr]:
						b += abs(comp - curr)
				if b == arr[curr]:
					upd.append(curr)
		for i in upd:
			ans[i] = q
		q += 1
	t = set(s)
	t = sorted(t)
	t.reverse()
	cter = [-1 for _ in range(len(t))]
	for i in range(len(t)):
		q = 0
		for c in s:
			if t[i] == c:
				q += 1
		cter[i] = q
	cter2 = []
	for i in range(len(t)):
		q = 0
		for j in ans:
			if i == j:
				q += 1
		cter2.append(q)
	ret = ''
	c = 0
	while c < len(t):
		if cter[c] < cter2[c]:
			del cter[c]
			del t[c]
		else:
			c += 1
	for i in ans:
		ret = ret + t[i]
	return ret
t = int(input())
anss = []
for _ in range(t):
	s = input()
	m = int(input())
	arr = input().split()
	arr = list(map(int, arr))
	anss.append(get_ans(s, m, arr))
for i in anss:
	print(i)


import os
import sys
from math import *
from collections import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	s = input()
	C = Counter(s)
	s = list(set(s))
	s.sort()
	m = Int()
	a = array()
	ans = [0] * m
	over = set()
	while any(a):
		indices = [i for i in range(m) if not a[i] and i not in over]
		char = s.pop()
		while C[char] < len(indices):
			char = s.pop()
		for i in range(m):
			if not a[i] or i in over:
				continue
			for ind in indices:
				a[i] -= abs(i - ind)
		for i in indices:
			over.add(i)
			ans[i] = char
	indices = [i for i in range(m) if not a[i] and i not in over]
	char = s.pop()
	while C[char] < len(indices):
		char = s.pop()
	for i in range(m):
		if ans[i] == 0:
			ans[i] = char
	print(*ans, sep='')


t = int(input())
for i in range(t):
	D = list(input())
	d = sorted(list(D), reverse=True)
	l = int(input())
	S = list(map(int, input().split()))
	s = sorted(S)
	out = ['x' for x in range(l)]
	counter = 0
	curl = 'x'
	while max(S) > -1:
		ind = []
		while S.count(0) > d.count(d[counter]):
			counter += 1
		for j in range(len(S)):
			if S[j] == 0:
				out[j] = d[counter]
				curl = d[counter]
				S[j] -= 1
				ind.append(j)
		for indd in ind:
			for j in range(len(S)):
				S[j] -= abs(j - indd)
		counter += len(ind)
		try:
			while curl == d[counter]:
				counter += 1
		except:
			pass
	print(''.join(out))


n = int(input())
for _ in range(n):
	s = sorted(input())
	m = len(s)
	input()
	b = list(map(int, input().split()))
	res = ['' for _ in range(len(b))]
	found = 0
	while found < len(b):
		for i in range(len(b)):
			if b[i] != -1:
				min_v = b[i]
				min_i = i
				break
		for (i, x) in enumerate(b):
			if x < min_v and x != -1:
				min_i = i
				min_v = x
		min_indices = []
		for i in range(len(b)):
			if b[i] == min_v:
				min_indices.append(i)
				b[i] = -1
		c = 1
		prev = s.pop()
		while s and c < len(min_indices):
			x = s.pop()
			if x != prev:
				c = 0
			c += 1
			prev = x
		while s and s[-1] == prev:
			s.pop()
		found += len(min_indices)
		for j in min_indices:
			res[j] = prev
			for i in range(len(b)):
				if b[i] != -1:
					b[i] -= abs(i - j)
	print(''.join(res))


import sys
input = sys.stdin.readline
t = int(input())
for r in range(t):
	s = input().strip('\n')
	m = int(input())
	l = list(map(int, input().split()))
	ans = [''] * m
	d = {}
	alphabets = []
	for i in s:
		try:
			d[i] += 1
		except:
			d[i] = 1
	for i in d:
		alphabets.append([i, d[i]])
	alphabets.sort(key=lambda x: (x[0], x[1]), reverse=True)
	total = m
	alphaLength = len(alphabets)
	while total > 0:
		countZero = 0
		for i in range(m):
			if l[i] == 0:
				countZero += 1
		letter = ''
		for i in range(alphaLength):
			if alphabets[i] == -1:
				continue
			if alphabets[i][1] >= countZero:
				letter = alphabets[i][0]
				alphabets[i] = -1
				break
			else:
				alphabets[i] = -1
		total -= countZero
		for i in range(m):
			if l[i] == 0:
				ans[i] = letter
				l[i] = -2
		for i in range(m):
			if l[i] == -1 or l[i] == -2:
				continue
			for j in range(m):
				if l[j] == -2:
					l[i] -= abs(i - j)
		for i in range(m):
			if l[i] == -2:
				ans[i] = letter
				l[i] = -1
	for i in ans:
		print(i, end='')
	print()


t = int(int(input('')))
while t > 0:
	string = input('')
	n = int(input(''))
	b = list(map(int, input().split()))
	l = list(string)
	l.sort()
	string_length = len(l)
	final = []
	finished = []
	for j in range(string_length):
		counter = string.count(l[j])
		if l[j] not in finished:
			final.append((l[j], counter))
			finished.append(l[j])
	final = final[::-1]
	index = 0
	ans = [0] * n
	while 0 in b:
		times = b.count(0)
		minicount = []
		for i in range(1, times + 1):
			for j in range(index, len(final)):
				if final[j][1] >= times:
					index = j
					break
			inserter = b.index(0)
			b[inserter] = -1
			ans[inserter] = final[index][0]
			minicount.append(inserter)
		index += 1
		for x in range(len(b)):
			for y in minicount:
				b[x] -= abs(x - y)
	answer = ''
	print(answer.join(ans))
	t -= 1


letters = 26
for q in range(int(input())):
	s = input()
	m = int(input())
	bs = list(map(int, input().split(' ')))
	vs = [ord(c) - ord('a') for c in s]
	counts = [0] * letters
	for v in vs:
		counts[v] += 1
	eqs = [None] * m
	eqCounts = []
	eqCur = 0
	while True:
		zinds = [i for (i, b) in enumerate(bs) if b == 0]
		for zi in zinds:
			for i in range(m):
				bs[i] -= abs(i - zi)
			bs[zi] -= 1
			eqs[zi] = eqCur
		eqCur += 1
		if len(zinds) == 0:
			break
		eqCounts += [len(zinds)]
	mapping = {}
	let = 0
	for (eq, count) in reversed(list(enumerate(eqCounts))):
		while counts[let] < count:
			let += 1
		mapping[eq] = chr(ord('a') + let)
		let += 1
	print(''.join((mapping[eq] for eq in eqs)))


for _ in range(int(input())):
	s = input()
	n = int(input())
	m = n
	b = list(map(int, input().split()))
	c = [''] * m
	freq = [0] * 26
	i = 25
	for elem in s:
		freq[ord(elem) - ord('a')] += 1
	while n > 0 and i >= 0:
		zero = []
		count = 0
		for j in range(m):
			if b[j] == 0:
				zero.append(j)
				b[j] = -1
				count += 1
		while i >= 0:
			if freq[i] >= count:
				for elem in zero:
					c[elem] = chr(i + ord('a'))
				n -= count
				for j in range(m):
					for elem in zero:
						if b[j] > 0:
							b[j] -= abs(j - elem)
				i -= 1
				break
			else:
				i -= 1
	print(''.join(c))


import sys
input = lambda : sys.stdin.readline().strip()
inp = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	a = str(input())
	(n,) = inp()
	arr = inp()
	d = [0 for i in range(26)]
	for i in a:
		d[ord(i) - ord('a')] += 1
	ans = [''] * n
	i = 25
	c = 0
	while i >= 0 and c != n:
		t = arr.count(0)
		temp = d[i]
		if t > temp:
			i -= 1
		else:
			for j in range(n):
				if arr[j] == 0:
					ans[j] = chr(ord('a') + i)
					arr[j] = -1
					c += 1
			for j in range(n):
				if arr[j] == -1:
					arr[j] -= 1
					for k in range(n):
						if arr[k] != -1:
							arr[k] -= abs(k - j)
			i -= 1
	print(*ans, sep='')


for _ in range(int(input())):
	temp = input()
	char_dict = {}
	for x in temp:
		if x not in char_dict:
			char_dict[x] = 1
		else:
			char_dict[x] += 1
	my_temp = sorted(char_dict.items(), key=lambda x: x[0], reverse=True)
	sorted_temp = []
	for i in my_temp:
		sorted_temp.append(list(i))
	processed = 0
	m = int(input())
	data = list(map(int, input().split()))
	found_index_list = []
	result_result_list = []
	while len(found_index_list) != m:
		min_index_list = []
		min_value = int(1000000000.0)
		for i in range(m):
			if i in found_index_list:
				continue
			now = data[i]
			for found_index in found_index_list:
				now -= abs(i - found_index)
			if min_value == now:
				min_index_list.append(i)
			elif min_value > now:
				min_index_list = [i]
				min_value = now
		count = len(min_index_list)
		while sorted_temp[processed][1] < count:
			processed += 1
		found_index_list += min_index_list
		result_result_list += [sorted_temp[processed][0]] * count
		processed += 1
	result = ['a'] * m
	for i in range(m):
		result[found_index_list[i]] = result_result_list[i]
	print(''.join(result))


def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
entries = inp()
for i in range(entries):
	s = insr()
	z = inp()
	l = inlt()
	s.sort()
	s.reverse()
	char_count = []
	cur_char = s[0]
	count = 0
	for x in s:
		if x != cur_char:
			char_count.append([cur_char, count])
			count = 1
			cur_char = x
		else:
			count += 1
	char_count.append([cur_char, count])
	res = [0] * z
	pos = 0
	ind = []
	while 0 in res:
		zero_pos = []
		for i in range(len(res)):
			if l[i] == 0 and i not in ind:
				zero_pos.append(i)
		while char_count[pos][1] < len(zero_pos):
			pos += 1
		for i in range(len(l)):
			for x in zero_pos:
				l[i] -= abs(i - x)
		for x in zero_pos:
			res[x] = char_count[pos][0]
			ind.append(x)
		pos += 1
	ans = ''
	for x in res:
		ans += x
	print(ans)


from collections import defaultdict
t = int(input())
cr_arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
cr_arr.reverse()
for _ in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	d = defaultdict(int)
	for i in s:
		d[i] += 1
	ans = [0] * m
	c = 0
	while 1:
		ind = []
		for i in range(m):
			if b[i] == 0:
				ind.append(i)
		if ind:
			l = len(ind)
			while cr_arr:
				if d[cr_arr[c]] >= l:
					break
				c += 1
			for i in ind:
				b[i] = -1
				ans[i] = cr_arr[c]
			c += 1
			for i in range(m):
				if b[i] != -1:
					for j in ind:
						b[i] -= abs(i - j)
		else:
			break
	print(''.join(ans))


import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip()
	m = int(input())
	b = list(map(int, input().split()))
	ss = sorted(s, reverse=True)
	i = 0
	ans = [''] * m
	k = 0
	while k != m:
		nulls = []
		for t in range(m):
			if b[t] == 0:
				nulls.append(t)
				b[t] = -1
		z = 0
		while z < len(nulls):
			z = 1
			ccc = True
			while i < len(ss) - 1 and ss[i] == ss[i + 1]:
				ccc = False
				z += 1
				i += 1
			if ccc and len(nulls) != 1:
				i += 1
		for l in nulls:
			ans[l] = ss[i]
		i += 1
		for q in range(m):
			for w in nulls:
				b[q] -= abs(q - w)
		k += len(nulls)
	for i in ans:
		print(i, end='')
	print()


import time, math, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

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

def IO():
	return stdin.readline()

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

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

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count

def solve():
	s = input()
	m = II()
	b = L()
	n = len(s)
	d = {}
	for ele in s:
		d[ele] = d.get(ele, 0) + 1
	d = OrderedDict(sorted(d.items(), reverse=True))
	cnt = 1
	l = [0] * m
	while cnt <= m:
		x = list(b)
		c = 0
		for i in range(m):
			if x[i] == 0 and l[i] == 0:
				c += 1
				for j in range(m):
					if x[j] != 0:
						b[j] -= abs(i - j)
		for ele in d:
			if d[ele] >= c:
				note = ele
				d[ele] = 0
				break
			else:
				d[ele] = 0
		d = OrderedDict(sorted(d.items(), reverse=True))
		for i in range(m):
			if x[i] == 0 and l[i] == 0:
				l[i] = note
		cnt += c
	n = ''
	for ele in l:
		n += ele
	print(n)
t = II()
for i in range(t):
	solve()


q = int(input())
for _ in range(q):
	s = list(input())
	m = int(input())
	b = list(map(int, input().split()))
	numberB = [-1] * m
	determined = 0
	index = 0
	maxIndex = 0
	while True:
		zeros = []
		for i in range(m):
			if numberB[i] == -1 and b[i] == 0:
				zeros.append(i)
		for elem in zeros:
			numberB[elem] = index
			maxIndex = index
		index += 1
		determined += len(zeros)
		if determined >= m:
			break
		for i in range(m):
			if numberB[i] != -1:
				continue
			for elem in zeros:
				b[i] -= abs(i - elem)
	countS = [0] * 26
	for elem in s:
		countS[ord(elem) - ord('a')] += 1
	curLetter = 0
	ans = [''] * m
	for i in range(maxIndex, -1, -1):
		curAdd = []
		for j in range(m):
			if i == numberB[j]:
				curAdd.append(j)
		while countS[curLetter] < len(curAdd):
			curLetter += 1
		for elem in curAdd:
			ans[elem] = chr(curLetter + ord('a'))
		curLetter += 1
	print(''.join(ans))


from collections import deque
q = int(input())
c = []
for i in range(q):
	s = input()
	m = int(input())
	b = [int(u) for u in input().split()]
	v = [0 for u in range(m)]
	d = {}
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	while v.count(0) != 0:
		p = []
		for i in range(m):
			if b[i] == 0:
				p.append(i)
		u = max(d)
		while d[u] < len(p):
			d.pop(u)
			u = max(d)
		for i in range(m):
			if i in p:
				v[i] = u
				b[i] = -1
			else:
				for j in p:
					if b[i] > 0:
						b[i] -= abs(i - j)
		if len(d) != 0:
			d.pop(u)
	c.append(v)
for h in c:
	for i in h:
		print(i, end='')
	print('')


import sys
import math
import operator as op
from functools import reduce
from bisect import *
from collections import OrderedDict
from collections import deque

def read_line():
	return sys.stdin.readline()[:-1]

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

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def read_float_line():
	return [float(v) for v in sys.stdin.readline().split()]

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 index(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return -1

def find_lt(a, x):
	i = bisect_left(a, x)
	if i:
		return i - 1
	return -1

def find_le(a, x):
	i = bisect_right(a, x)
	if i:
		return i - 1
	return -1

def find_gt(a, x):
	i = bisect_right(a, x)
	if i != len(a):
		return i
	return -1

def find_ge(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	return -1

def check(vis):
	f = True
	for i in vis:
		f = f & i
	return f
mod = int(1000000000.0) + 7
mod2 = 998244353
t = read_int()
for i in range(t):
	s = read_line()
	m = read_int()
	b = read_int_line()
	a = list(b)
	ans = [0] * m
	n = len(s)
	x = [s[i] for i in range(n)]
	x.sort(reverse=True)
	el = {}
	for i in s:
		if i in el:
			el[i] += 1
		else:
			el[i] = 1
	vis = [False] * m
	el = OrderedDict(sorted(el.items(), reverse=True))
	k = 0
	while k < m:
		cn = 0
		for j in range(m):
			if b[j] == 0 and ans[j] == 0:
				cn += 1
		char = ''
		for j in el:
			if el[j] >= cn and el[j] > 0:
				char = max(char, j)
		for j in range(m):
			if b[j] == 0 and ans[j] == 0:
				ans[j] = char
				if char in el:
					el[char] -= 1
		e = {}
		for i in el:
			if i < char:
				e[i] = el[i]
		el = e
		temp = list(b)
		for j in range(m):
			if b[j] == 0 and (not vis[j]):
				for i in range(m):
					if b[i] != 0:
						temp[i] -= abs(j - i)
						temp[i] = max(0, temp[i])
				vis[j] = True
		b = temp
		k += 1
	val = ''
	for i in ans:
		val += i
	b1 = [0] * m
	for i in range(m):
		for j in range(m):
			if i != j and val[i] < val[j]:
				b1[i] += abs(i - j)
	assert b1 == a
	print(val)


from collections import defaultdict
q = int(input())
for _ in range(q):
	s = list(input())
	m = int(input())
	B = list(map(int, input().split()))
	t = [0 for i in range(m)]
	uc = sorted(list(set(s)), reverse=True)
	G = []
	for i in uc:
		G.append([i, s.count(i)])
	h = 0
	while h < m:
		i = 0
		c = []
		for i in range(m):
			if B[i] == 0 and t[i] == 0:
				c.append(i)
		v = 0
		for i in range(len(G)):
			if G[i][1] >= len(c):
				v = G[i][0]
				break
		for j in range(i, -1, -1):
			G.pop(j)
		for i in c:
			t[i] = v
			h = h + 1
			for j in range(m):
				B[j] = B[j] - abs(j - i)
	print(*t, sep='')


for _ in range(int(input())):
	S = sorted(input())
	rec = {}
	s = []
	for i in S:
		if rec.get(i, 0) == 0:
			s.append(i)
		rec[i] = rec.get(i, 0) + 1
	m = int(input())
	b = list(map(int, input().split()))
	ans = ['' for i in range(m)]
	while True:
		pos = []
		n = 0
		for i in range(m):
			if b[i] == 0 and ans[i] == '':
				pos.append(i)
				n += 1
		if n == 0:
			break
		t = s.pop()
		while rec[t] < n:
			t = s.pop()
		for i in range(m):
			if b[i] == 0 and ans[i] == '':
				ans[i] = t
			else:
				for j in pos:
					b[i] -= abs(i - j)
	print(''.join(ans))


t = int(input())
for x in range(t):
	s = input()
	s = sorted(s)
	s.reverse()
	n = int(input())
	b = list(map(int, input().split(' ')))
	ch = ['' for i in range(len(b))]
	zeros = b.count(0)
	while zeros != 0:
		idx = []
		for (i, j) in enumerate(b):
			if j == 0:
				idx.append(i)
				b[i] = -1
		while s.count(s[0]) < zeros:
			s.remove(s[0])
		for i in idx:
			ch[i] = s[0]
			for j in range(len(b)):
				b[j] -= abs(i - j)
		zeros = b.count(0)
		add_c = s[0]
		while add_c in s:
			s.remove(add_c)
	print(''.join([i for i in ch]))


import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
alphabets.reverse()

def solve():
	s = si()
	m = ii()
	b = li()
	d = defaultdict(lambda : 0)
	for i in s:
		d[i] += 1
	ui = 0
	ans = ['a'] * m
	while 1:
		minVal = min(b)
		if minVal == float('inf'):
			break
		while b.count(minVal) > d[alphabets[ui]]:
			ui += 1
		tosub = [0] * m
		indexes = []
		for i in range(m):
			if b[i] == minVal:
				indexes.append(i)
				ans[i] = alphabets[ui]
				b[i] = float('inf')
		for i in indexes:
			for j in range(m):
				if j not in indexes:
					tosub[j] += abs(i - j)
		for i in range(m):
			b[i] -= tosub[i]
		ui += 1
	print(''.join(ans))
t = 1
t = int(input())
for _ in range(t):
	solve()


import sys
import math
t = int(input())
while t > 0:
	s = sys.stdin.readline()
	n = int(sys.stdin.readline())
	input = sys.stdin.readline()
	arr = list(map(int, input.split()))
	list_s = []
	for i in range(len(s)):
		list_s.append(s[i])
	list_s.sort()
	ans = str()
	for i in range(n):
		ans += 'a'
	while arr != [-1 for i in range(n)]:
		empty = []
		for i in range(len(arr)):
			if arr[i] == 0:
				empty.append(i)
		while list_s[-1] != list_s[-len(empty)]:
			list_s.pop()
		for i in range(len(empty)):
			x = list_s[-1]
			ans = ans[:empty[i]] + x + ans[empty[i] + 1:]
			list_s.pop()
		while list_s[-1] == x:
			list_s.pop()
		for i in range(len(arr)):
			if arr[i] != 0 and arr[i] != -1:
				for j in empty:
					arr[i] -= abs(i - j)
			elif arr[i] == 0:
				arr[i] = -1
	print(ans)
	t -= 1


import math
t = int(input())
for y in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ch = [0 for i in range(30)]
	am = ch.copy()
	for i in s:
		ch[ord(i) - ord('a')] += 1
	cur = 0
	found = True
	val = [0 for i in range(m + 5)]
	while found:
		found = False
		for i in range(m):
			if b[i] == 0:
				b[i] = -1 - cur
		for i in range(m):
			if b[i] == -1 - cur:
				found = True
				val[i] = cur
				am[cur] += 1
				for j in range(m):
					if b[j] > 0:
						b[j] -= math.fabs(j - i)
		cur += 1
	ans = ['z' for i in range(m)]
	cur = 0
	for i in range(28, -1, -1):
		if am[cur] == 0:
			break
		if ch[i] >= am[cur]:
			for j in range(m):
				if val[j] == cur:
					ans[j] = chr(i + ord('a'))
			cur += 1
	for i in ans:
		print(i, end='')
	print()


from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, itertools, math
sys.setrecursionlimit(10 ** 5)
input = sys.stdin.readline
sqrt = math.sqrt

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

def LF():
	return list(map(float, input().split()))

def LI_():
	return list(map(lambda x: int(x) - 1, input().split()))

def II():
	return int(input())

def IF():
	return float(input())

def S():
	return input().rstrip()

def LS():
	return S().split()

def IR(n):
	res = [None] * n
	for i in range(n):
		res[i] = II()
	return res

def LIR(n):
	res = [None] * n
	for i in range(n):
		res[i] = LI()
	return res

def FR(n):
	res = [None] * n
	for i in range(n):
		res[i] = IF()
	return res

def LIR(n):
	res = [None] * n
	for i in range(n):
		res[i] = IF()
	return res

def LIR_(n):
	res = [None] * n
	for i in range(n):
		res[i] = LI_()
	return res

def SR(n):
	res = [None] * n
	for i in range(n):
		res[i] = S()
	return res

def LSR(n):
	res = [None] * n
	for i in range(n):
		res[i] = LS()
	return res
mod = 1000000007
inf = float('INF')

def solve():
	for _ in range(II()):
		s = S()
		ss = defaultdict(int)
		for si in s:
			ss[si] += 1
		ls = []
		for (key, value) in ss.items():
			ls.append((key, value))
		ls.sort()
		m = II()
		b = LI()
		l = []
		x = 0
		c = defaultdict(int)
		tmp = []
		for i in range(m):
			if b[i] == 0:
				c[i] = 1
				tmp.append(i)
				x += 1
		l.append(tmp)
		while x != m:
			ll = []
			for i in range(m):
				if not c[i]:
					tmp = 0
					for li in l:
						for j in li:
							tmp += abs(i - j)
					if tmp == b[i]:
						ll.append(i)
						x += 1
						c[i] = 1
			l.append(ll)
		ans = ['A'] * m
		cs = defaultdict(int)
		for li in l:
			while 1:
				a = ls.pop()
				if len(li) <= a[1]:
					for i in li:
						ans[i] = a[0]
					break
		print(''.join(ans))
	return
solve()


from collections import Counter
T = int(input())
for t in range(T):
	S = input()
	M = int(input())
	B = [int(_) for _ in input().split()]
	Y = ['' for _ in range(M)]
	expected_scores = [0] * M
	cc = Counter(S)
	for _c in range(ord('z'), ord('a') - 1, -1):
		c = chr(_c)
		if not cc[c]:
			continue
		poss = []
		next_expected_scores = list(expected_scores)
		for pos in range(M):
			if Y[pos] != '':
				continue
			if B[pos] == expected_scores[pos]:
				poss.append(pos)
				for p in range(M):
					next_expected_scores[p] += abs(p - pos)
		if len(poss) <= cc[c]:
			expected_scores = next_expected_scores
			for p in poss:
				Y[p] = c
	print(''.join(Y))


T = int(input())
for i in range(0, T):
	S = str(input())
	m = int(input())
	B = list(map(int, input().split()))
	vis = []
	ans_int = []
	S_int = []
	for j in range(0, m):
		vis.append(0)
		ans_int.append(0)
	for j in range(0, len(S)):
		S_int.append(ord(S[j]))
	S_int.sort()
	S_int.reverse()
	tar = 0
	indi = 0
	while tar < m:
		mark = []
		for j in range(0, m):
			if B[j] == 0 and vis[j] == 0:
				mark.append(j)
				vis[j] = 1
		leng = len(mark)
		for j in range(0, m):
			for k in range(0, leng):
				if vis[j] == 0:
					B[j] -= abs(j - mark[k])
		y = S_int[indi]
		while True:
			x = S_int[indi]
			y = x
			flag = 1
			for k in range(1, leng):
				if S_int[indi + k] != x:
					flag = 0
					break
			if flag == 0:
				indi += 1
			else:
				break
		for j in range(0, leng):
			ans_int[mark[j]] = S_int[indi]
			indi += 1
		while indi < len(S) and S_int[indi] == y:
			indi += 1
		tar += leng
	ans = []
	for k in range(0, m):
		ans.append(chr(ans_int[k]))
	X = ''
	ans = X.join(ans)
	print(ans)


from collections import defaultdict
test = int(input())
while test != 0:
	s = input()
	m = int(input())
	arr = [int(x) for x in input().split()]
	s = list(s)
	s.sort()
	ans = [0] * m
	sumindex = []
	anslen = 0
	while anslen < m:
		for i in range(m):
			if arr[i] == 0 and ans[i] == 0:
				sumindex.append(i)
		numberwanted = len(sumindex)
		x = s.pop()
		numberwanted -= 1
		while numberwanted > 0:
			y = s.pop()
			if x == y:
				numberwanted -= 1
			else:
				x = y
				numberwanted = len(sumindex) - 1
		while len(s) > 1 and s[-1] == x:
			s.pop()
		for i in sumindex:
			ans[i] = x
			anslen += 1
		for i in range(len(arr)):
			for j in sumindex:
				arr[i] -= abs(i - j)
		sumindex = []
	print(*ans, sep='')
	test -= 1


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
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

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())
MOD = 998244353

def solve():
	ans = ''
	S = listStr()
	lets = [0] * 26
	for s in S:
		ind = ord(s) - ord('a')
		lets[ind] += 1
	M = getInt()
	B = getInts()
	B = [[b, i] for (i, b) in enumerate(B)]
	B.sort(reverse=True)
	ans = [''] * M
	while B:
		(min_B, j) = B.pop()
		tmp = [j]
		while B and B[-1][0] == min_B:
			(m, j) = B.pop()
			tmp.append(j)
		req = len(tmp)
		while lets[-1] < req:
			lets.pop()
		let = len(lets) - 1
		lets.pop()
		let = chr(ord('a') + let)
		for j in tmp:
			ans[j] = let
		for i in range(len(B)):
			for j in tmp:
				B[i][0] -= abs(B[i][1] - j)
		B.sort(reverse=True)
	ans = ''.join(ans)
	return ans
for _ in range(getInt()):
	print(solve())


def update(arr, zeros, replacement):
	for i in range(len(arr)):
		if arr[i] == 0:
			arr[i] = replacement
		if isinstance(arr[i], int):
			arr[i] -= sum([abs(i - zero) for zero in zeros])
	return arr

def find(s, num):
	r = s[-1]
	if s.count(r) >= num:
		while s[-1] == r:
			s.pop()
		return (s, r)
	else:
		while s[-1] == r:
			s.pop()
		return find(s, num)
for _ in range(int(input())):
	s = ['*'] + sorted(list(input()))
	n = int(input())
	arr = [int(i) for i in input().split()]
	while n > 0:
		zeros = []
		for (i, x) in enumerate(arr):
			if x == 0:
				zeros.append(i)
		n -= len(zeros)
		(s, replacement) = find(s, len(zeros))
		arr = update(arr, zeros, replacement)
	print(''.join(arr))


from sys import stdout, stdin
input = stdin.readline
for _ in range(int(input())):
	s = list(input().strip())
	m = int(input())
	b = list(map(int, input().split()))
	c = [0 for i in range(26)]
	t = ['0' for i in range(m)]
	for i in s:
		c[ord(i) - 97] += 1
	count = 0
	s.sort()
	while count < m:
		lst = []
		for i in range(m):
			if b[i] == 0:
				lst.append(i)
				b[i] = 2000
		for i in range(len(s) - 1, -1, -1):
			if c[ord(s[i]) - 97] != len(lst):
				c[ord(s[i]) - 97] -= 1
				s.pop()
			else:
				break
		for i in lst:
			t[i] = s[-1]
			s.pop()
		count += len(lst)
		for i in range(m):
			if b[i] != 2000:
				for j in lst:
					b[i] = b[i] - abs(i - j)
	for i in t:
		stdout.write(i)
	stdout.write('\n')


from collections import Counter
for t in range(int(input())):
	s = input()
	n = int(input())
	m = n
	l = [int(j) for j in input().split()]
	ans = [0] * n
	s = list(s)
	d = dict()
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	d = sorted(d.items())[::-1]
	ind = 0
	st_ans = [0] * n
	done = set()
	ct = 0
	while ct < m:
		req_freq = []
		for i in range(n):
			if ans[i] == l[i] and i not in done:
				req_freq.append(i)
				done.add(i)
		for i in range(n):
			for j in req_freq:
				if i not in done:
					ans[i] += abs(i - j)
		while True:
			if d[ind][1] >= len(req_freq):
				break
			else:
				ind += 1
		for j in req_freq:
			st_ans[j] = d[ind][0]
			ct += 1
		ind += 1
	print(''.join(st_ans))


MAX = 100000000
t = int(input())
for tt in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ans = ['c'] * m
	group = list()
	while True:
		pos = list()
		for i in range(m):
			if b[i] == 0:
				pos.append(i)
		if len(pos) == 0:
			break
		else:
			group.append(pos)
		for i in range(m):
			if b[i] == 0:
				b[i] = MAX
			else:
				for j in pos:
					b[i] -= abs(i - j)
	freq = {}
	for char in s:
		if char in freq:
			freq[char] += 1
		else:
			freq[char] = 1
	sort_freq = sorted(freq.items(), key=lambda x: x[0], reverse=True)
	items = iter(sort_freq)
	char = next(items)
	for pos in group:
		while char[1] < len(pos):
			try:
				char = next(items)
			except StopIteration:
				break
		for pp in pos:
			ans[pp] = char[0]
		try:
			char = next(items)
		except StopIteration:
			break
	print(''.join(ans))


from sys import stdin, stdout, setrecursionlimit
for _ in range(int(input())):
	s = input()
	n = int(input())
	a = [int(i) for i in input().split()]
	l = {}
	for x in s:
		if x not in l:
			l[x] = 1
		else:
			l[x] += 1
	s = set(s)
	t = ''
	for x in s:
		t += x
	t = sorted(t, reverse=True)
	ans = [0] * n
	j = 1
	h = {}
	while 0 in ans:
		cur = []
		for i in range(n):
			if a[i] == 0 and ans[i] == 0:
				ans[i] = j
				cur.append(i)
		for i in range(n):
			if ans[i] > 0:
				continue
			for x in cur:
				a[i] -= abs(i - x)
		h[j] = len(cur)
		j += 1
	itog = [0] * n
	curi = 0
	for key in h:
		while l[t[curi]] < h[key]:
			curi += 1
		for i in range(n):
			if ans[i] == key:
				itog[i] = t[curi]
		curi += 1
	for x in itog:
		print(x, end='')
	print()


for test in range(int(input())):
	s = list(input())
	s.sort(reverse=True)
	a = []
	last = s[0]
	count = 1
	for i in range(1, len(s)):
		if s[i] == last:
			count += 1
		else:
			a.append((last, count))
			last = s[i]
			count = 1
	a.append((last, count))
	m = int(input())
	b = list(map(int, input().split()))
	t = [''] * m
	count = -1
	while count < len(a):
		index = []
		count += 1
		for i in range(m):
			if b[i] == 0:
				index.append(i)
				b[i] = -1
		for i in range(m):
			if b[i] >= 0:
				for j in index:
					b[i] -= abs(i - j)
		while count < len(a) and a[count][1] < len(index):
			count += 1
		for i in index:
			t[i] = a[count][0]
	print(''.join(t))


def solve():
	s = list(input())
	m = int(input())
	b = list(map(int, input().split()))
	t = ['-'] * m
	letter_count = dict()
	for l in s:
		if l in letter_count:
			letter_count[l] += 1
		else:
			letter_count[l] = 1
	(used_letters, maximal_position) = (0, 0)
	maximal_letters = sorted(list(set(s)), reverse=True)
	while used_letters < m:
		used_positions = list(filter(lambda x: b[x] == 0, list(range(m))))
		while letter_count[maximal_letters[maximal_position]] < len(used_positions):
			maximal_position += 1
		used_letters += len(used_positions)
		for i in range(m):
			if i in used_positions:
				b[i] = -1
				t[i] = maximal_letters[maximal_position]
			if b[i] == -1:
				continue
			for j in used_positions:
				b[i] -= abs(i - j)
		maximal_position += 1
	return ''.join(t)
for _ in range(int(input())):
	print(solve())


q = int(input())
results = []
for case in range(q):
	s = [c for c in input()]
	s_letters = sorted(list(set(s)))
	m = int(input())
	b = list(map(int, input().split()))
	t = [''] * m
	while sum(b) != -m:
		zeroes = set()
		for i in range(m):
			if b[i] == 0:
				zeroes.add(i)
		while True:
			letter = s_letters.pop()
			if s.count(letter) >= len(zeroes):
				for i in zeroes:
					t[i] = letter
					b[i] = -1
				break
		for n in range(m):
			for i in zeroes:
				if b[n] != -1:
					b[n] -= abs(i - n)
	print(''.join(t))


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def instr():
	return str(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
from collections import Counter

def main():
	t = inp()
	for _ in range(t):
		st = input()[:-1]
		_ = inp()
		b = inlt()
		b = list(enumerate(b))
		results = []
		curr = []
		flat_res = [item for sublist in results for item in sublist]
		while len(flat_res) < len(b):
			for (i, b_i) in b:
				summ = 0
				for idx in flat_res:
					if i == idx:
						summ = -1
						break
					summ += abs(i - idx)
				if summ == b_i:
					curr.append(i)
			results.append(curr)
			curr = []
			flat_res = [item for sublist in results for item in sublist]
		results = results[::-1]
		st = sorted(st)
		counter = Counter(st)
		letters = sorted(counter.items())
		res = ['.'] * len(b)
		p1 = 0
		p2 = 0
		while p1 < len(results) and p2 < len(letters):
			(letter, letter_count) = letters[p2]
			idxs = results[p1]
			if letter_count < len(idxs):
				p2 += 1
			else:
				for i in idxs:
					res[i] = letter
				p1 += 1
				p2 += 1
		print(''.join(res))
main()


def main():
	st = input()
	n = int(input())
	lst = list(map(int, input().split()))
	alph = [0 for i in range(ord('z') - ord('a') + 1)]
	for i in st:
		alph[ord(i) - ord('a')] += 1
	ans = [-1 for i in range(n)]
	for i in range(len(alph) - 1, -1, -1):
		if alph[i] != 0:
			k = anns(ans, lst)
			hw = 0
			for j in k:
				if ans[j] == -1:
					hw += 1
			if hw <= alph[i]:
				for j in anns(ans, lst):
					if ans[j] == -1:
						ans[j] = i
	for i in ans:
		print(chr(i + ord('a')), end='')
	print()

def anns(lst, lnum):
	nm = 0
	lg = 0
	rg = 0
	lstnum = [0 for i in range(len(lst))]
	for i in range(1, len(lst)):
		if lst[i] != -1:
			nm += i
			rg += 1
	if lst[0] != -1:
		lg += 1
	lstnum[0] = nm
	for i in range(1, len(lst)):
		if lst[i] == -1:
			lstnum[i] = lstnum[i - 1] + lg - rg
		else:
			lstnum[i] = lstnum[i - 1] + lg - rg
			lg += 1
			rg -= 1
	ansk = []
	for i in range(len(lst)):
		if lstnum[i] == lnum[i]:
			ansk.append(i)
	return ansk
for t in range(int(input())):
	main()


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	d = dd(int)
	s = input().split()[0]
	n = int(input())
	l = list(map(int, input().split()))
	li = []
	for i in range(n):
		if l[i] == 0:
			li.append(i)
	for i in s:
		d[i] += 1
	di = dd(list)
	ch = []
	for i in range(26):
		c = chr(ord('a') + i)
		if d[c]:
			ch.append(c)
			di[d[c]].append(c)
	j = len(ch) - 1
	res = ['0'] * n
	cou = 0
	while j >= 0 and cou < n:
		while j >= 0 and d[ch[j]] < len(li):
			j -= 1
		for i in li:
			res[i] = ch[j]
			d[ch[j]] = 0
			cou += 1
		li = []
		for k in range(n):
			if res[k] == '0':
				su = 0
				for kk in range(n):
					if res[kk] != '0':
						su += abs(k - kk)
				if su == l[k]:
					li.append(k)
	print(''.join(res))
	t -= 1


t = int(input())
for _ in range(t):
	s = str(input())
	m = int(input())
	b = list(map(int, input().split()))
	d = {}
	for x in s:
		if x in d.keys():
			d[x] += 1
		else:
			d[x] = 1
	keys = list(d.keys())
	keys.sort(reverse=True)
	i = 0
	l = 0
	t = [0] * m
	while l < m:
		z = []
		for j in range(m):
			if b[j] == 0:
				z.append(j)
		lz = len(z)
		k = keys[i]
		while d[k] < lz:
			i += 1
			k = keys[i]
		for j in range(m):
			if j in z:
				t[j] = k
				b[j] = -10
			else:
				for h in z:
					b[j] -= abs(h - j)
		l += lz
		i += 1
	for x in t:
		print(x, end='')
	print()


for _ in range(int(input())):
	alpha = [0] * 26
	s = input()
	for i in s:
		alpha[ord(i) - 97] += 1
	curr = 25
	n = int(input())
	b = list(map(int, input().split()))
	ans = [''] * n
	visited = [False] * n
	com = 0
	while com < n:
		pos = []
		for i in range(n):
			if b[i] == 0 and (not visited[i]):
				visited[i] = True
				com += 1
				pos.append(i)
		posl = len(pos)
		for i in pos:
			for j in range(n):
				if b[j] == 0:
					continue
				b[j] -= abs(i - j)
		while posl > alpha[curr]:
			curr -= 1
		for i in pos:
			ans[i] = chr(97 + curr)
		curr -= 1
	print(''.join(ans))


m = 10 ** 9 + 7
t = int(input())
while t:
	t -= 1
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	fin = sorted(s)
	ans = [''] * m
	while '' in ans:
		new = [index for (index, value) in enumerate(b) if value == 0]
		while fin.count(fin[-1]) < len(new):
			fin = list(filter(lambda x: x != fin[-1], fin))
		for i in new:
			b[i] = -1
			ans[i] = fin[-1]
		fin = list(filter(lambda x: x != fin[-1], fin))
		for i in range(len(b)):
			if b[i] != -1:
				for j in new:
					b[i] -= abs(i - j)
	print(''.join(ans))


def solve(s, m, arr, ans):
	t = [-1] * m
	letters = [0] * 26
	for i in s:
		letters[ord(i) - ord('a')] += 1
	limit = 25
	indices = []
	count = arr.count(0)
	while True:
		index = -1
		for i in range(limit, -1, -1):
			if letters[i] >= count:
				limit = i - 1
				index = i
				break
		if not indices:
			for i in range(m):
				if arr[i] == 0:
					t[i] = chr(ord('a') + index)
					indices.append(i)
		else:
			for i in good:
				t[i] = chr(ord('a') + index)
			indices.extend(good)
		good = []
		for i in range(m):
			if t[i] != -1:
				continue
			count = 0
			for index in indices:
				count += abs(index - i)
			if count == arr[i]:
				good.append(i)
		if not good:
			break
		count = len(good)
	t1 = ''
	for i in t:
		t1 += i
	ans.append(t1)

def main():
	q = int(input())
	ans = []
	for i in range(q):
		s = input()
		m = int(input())
		arr = list(map(int, input().split()))
		solve(s, m, arr, ans)
	for i in ans:
		print(i)
main()


t = int(input())
for _ in range(t):
	list1 = list(input())
	m = int(input())
	list2 = list(map(int, input().strip().split()))
	map1 = dict()
	for val in list1:
		if val in map1:
			map1[val] += 1
		else:
			map1[val] = 1
	ans = []
	res = []
	b = 0
	while 1:
		temp = []
		for i in range(m):
			index = i
			required = 0
			if i in ans:
				continue
			for j in range(len(ans)):
				required += abs(ans[j] - index)
			if list2[index] == required:
				temp.append(index)
		res.append(temp)
		for val in temp:
			ans.append(val)
		if len(ans) == m:
			break
	list3 = sorted(map1)
	list3.reverse()
	output = []
	for i in range(m):
		output.append(-1)
	pointer = 0
	for val in list3:
		if map1[val] >= len(res[pointer]):
			for indices in res[pointer]:
				output[indices] = val
			pointer += 1
			if pointer == len(res):
				break
	for letter in output:
		print(letter, end='')
	print()


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
q = int(input())
for i in range(q):
	s = input()
	s = sorted(s, reverse=True)
	c = Counter(s)
	m = int(input())
	l = []
	b = list(map(int, input().split()))
	visit = [0] * m
	while visit.count(1) != m:
		l1 = []
		for i in range(m):
			if b[i] == 0 and visit[i] == 0:
				l1.append(i)
				visit[i] = 1
		l.append(l1)
		for j in range(m):
			if b[j] != 0:
				for k in l1:
					b[j] -= abs(j - k)
	d = sorted(c.items(), key=lambda x: x[0])
	last = len(d) - 1
	final = [''] * m
	for j in l:
		while True:
			if d[last][1] >= len(j):
				for kk in j:
					final[kk] = d[last][0]
				last -= 1
				break
			last -= 1
	print(''.join(final))


tc = int(input())
for _ in range(tc):
	char = [x for x in input()]
	num = int(input())
	numa = [int(x) for x in input().split()]
	sumcount = [0] * num
	char.sort()
	charpoint = len(char)
	fill = 0
	answer = []
	for i in range(num):
		answer.append('1')
	while fill < num:
		changethistime = []
		for i in range(num):
			if sumcount[i] == numa[i] and answer[i] == '1':
				changethistime.append(i)
		count = 0
		while count < len(changethistime):
			charpoint -= 1
			count = 1
			while charpoint - 1 >= 0 and char[charpoint] == char[charpoint - 1]:
				count += 1
				charpoint -= 1
		for i in changethistime:
			answer[i] = char[charpoint]
			fill += 1
			for j in range(num):
				sumcount[j] += abs(j - i)
	for i in answer:
		print(i, end='')
	print()


import math
for i in range(int(input())):
	a = list(input())
	m = len(a)
	n = int(input())
	b = [int(i) for i in input().split()]
	a.sort(reverse=True)
	A = []
	Ai = []
	I = 0
	for i in range(1, m):
		if a[i] != a[i - 1]:
			A.append(i - I)
			Ai.append(a[i - 1])
			I = i
	A.append(m - I)
	Ai.append(a[-1])
	ans = [0] * n
	for layer in range(len(A)):
		indexes = set()
		if b.count(0) <= A[layer]:
			for i in range(n):
				if b[i] == 0:
					ans[i] = Ai[layer]
					indexes.add(i)
					b[i] = -1
			for i in range(n):
				if b[i] > 0:
					b[i] -= sum((abs(i - j) for j in indexes))
	if 0 not in ans:
		print(''.join(ans))
	else:
		print(ans)


t = int(input())
cnt = 0
while cnt < t:
	cnt += 1
	a = [0] * 26
	for i in input():
		a[ord(i) - 97] += 1
	a.reverse()
	n = int(input())
	res = [' '] * n
	visited = [0] * n
	b = [int(i) for i in input().split()]
	pos = 0
	while True:
		tmp = []
		for (i, elem) in enumerate(b):
			if elem == 0 and visited[i] == 0:
				tmp.append(i)
				visited[i] = 1
		tmp_total = len(tmp)
		if tmp_total == 0:
			break
		for elem in range(pos, 26):
			if a[elem] >= tmp_total:
				for i in tmp:
					res[i] = chr(25 - elem + 97)
				a[elem] = 0
				pos = elem
				break
		for j in range(n):
			if visited[j] == 0:
				for i in tmp:
					b[j] -= abs(j - i)
	print(''.join((i for i in res)))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	tc = int(input())
	for _ in range(tc):
		s = input()
		s = sorted(s, reverse=True)
		m = int(input())
		b = [int(x) for x in input().split()]
		d = {}
		ans = ['.'] * m
		for i in s:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
		od = d
		noit = []
		uc = []
		n0 = 10000000
		while True:
			n0 = 0
			n0i = []
			for i in range(m):
				if b[i] == 0 and i + 1 not in noit:
					n0 += 1
			c = ''
			for i in od:
				if i not in uc and od[i] >= n0:
					c = i
					uc.append(i)
					break
				uc.append(i)
			for i in range(m):
				if b[i] == 0 and i + 1 not in noit:
					ans[i] = c
					n0i.append(i + 1)
					noit.append(i + 1)
			for i in range(m):
				if i + 1 not in noit:
					for j in n0i:
						b[i] -= abs(i + 1 - j)
			if len(noit) == m:
				break
		print(''.join(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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


alp = 'abcdefghijklmnopqrstuvwxyz'
al = {}
for i in range(26):
	al[alp[i]] = i
tt = int(input())
for loop in range(tt):
	s = list(input())
	a = [0] * 26
	for i in s:
		a[al[i]] += 1
	m = int(input())
	b = list(map(int, input().split()))
	ans = [None] * m
	while max(b) >= 0:
		zind = []
		for i in range(m):
			if b[i] == 0:
				b[i] = -1
				zind.append(i)
		for i in range(25, -1, -1):
			if len(zind) > a[i]:
				a[i] = 0
			else:
				for j in zind:
					ans[j] = alp[i]
				a[i] = 0
				break
		for j in zind:
			for i in range(m):
				b[i] -= abs(i - j)
	print(''.join(ans))


def one_case():
	s = input()
	n = int(input())
	a = [int(x) for x in input().split()]
	d = {}
	for x in s:
		d[x] = 1 if not x in d else d[x] + 1
	stack = []
	for (k, v) in sorted(d.items()):
		stack.append((k, v))
	res = ['0' for i in range(n)]
	while True:
		idx = [i for (i, x) in enumerate(a) if x == 0]
		if len(idx) == 0:
			break
		(ch, freq) = stack.pop()
		if freq < len(idx):
			continue
		for i in idx:
			res[i] = ch
		for i in range(n):
			if a[i] < 0:
				continue
			a[i] -= sum([abs(i - j) for j in idx])
		for i in idx:
			a[i] = -1
	print(''.join(res))
t = int(input())
for i in range(t):
	one_case()


from sys import stdin
input = stdin.readline
q = int(input())
for _ in range(q):
	s = list(input().rstrip())
	cnt = [0] * 26
	for c in s:
		cnt[ord(c) - ord('a')] += 1
	m = int(input())
	b = list(map(int, input().split()))
	t = [''] * m
	p = 25
	while any([x != -1 for x in b]):
		b0 = [i for i in range(m) if b[i] == 0]
		for idx in b0:
			b[idx] -= 1
			for j in range(m):
				if b[j] > 0:
					b[j] -= abs(j - idx)
		while cnt[p] < len(b0):
			p -= 1
		for idx in b0:
			t[idx] = chr(p + ord('a'))
		p -= 1
	print(''.join(t))


for _ in range(int(input())):
	s = [i for i in input()]
	m = int(input())
	b = [int(i) for i in input().split()]
	t = ['0'] * m
	general_list = []
	while '0' in t:
		indices = []
		for (ind, el) in enumerate(b):
			if el == 0:
				if ind not in general_list:
					indices.append(ind)
					general_list.append(ind)
		while True:
			maximum = max(s)
			number = s.count(maximum)
			if len(indices) == number:
				break
			else:
				s[s.index(maximum)] = '.'
		for i in range(len(indices)):
			maximum = max(s)
			ind = s.index(maximum)
			t[indices[i]] = maximum
			s[ind] = '.'
			for j in range(m):
				if b[j] != 0:
					b[j] -= abs(j - indices[i])
	print(''.join(t))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
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')
for ik in range(int(input())):
	s = list(input())
	s.sort(reverse=True)
	d = dict()
	for i in range(len(s)):
		if s[i] not in d:
			d.update({s[i]: 1})
		else:
			d[s[i]] += 1
	s = list(set(s))
	s.sort(reverse=True)
	n = int(input())
	ans = [''] * n
	l = list(map(int, input().split()))
	t = 0
	while max(l) > 0:
		e = []
		e1 = l.count(0)
		while e1 > d[s[t]]:
			t += 1
		for i in range(n):
			if l[i] == 0:
				ans[i] = s[t]
				l[i] = -1
				e.append(i)
		for i in e:
			for j in range(i - 1, -1, -1):
				if ans[j] == '':
					l[j] -= i - j
			for j in range(i + 1, n):
				if ans[j] == '':
					l[j] -= j - i
		t += 1
	while l.count(0) > d[s[t]]:
		t += 1
	for i in range(n):
		if ans[i] == '' and l[i] == 0:
			ans[i] = s[t]
	print(*ans, sep='')


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	cnt = [0] * 26
	for i in minp():
		cnt[ord(i) - ord('a')] += 1
	m = mint()
	b = list(mints())
	ans = ['a'] * m
	j = 25
	while True:
		c = b.count(0)
		if c == 0:
			break
		while j >= 0:
			if cnt[j] >= c:
				break
			j -= 1
		p = []
		for i in range(m):
			if b[i] == 0:
				p.append(i)
		for x in p:
			for i in range(m):
				b[i] -= abs(i - x)
			ans[x] = chr(ord('a') + j)
			b[x] += 1000000000
		j -= 1
	print(''.join(ans))
for i in range(mint()):
	solve()


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')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	s = input()
	count = [0] * 26
	for i in s:
		count[ord(i) - 97] += 1
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	indices = []
	for i in range(n):
		if a[i] == 0:
			ans[i] = 1
			indices += [i]
	cur = 25
	letters = []
	ai = ans.count(1)
	while True:
		if count[cur] >= ai:
			letters += [chr(97 + cur)]
			cur -= 1
			break
		else:
			cur -= 1
	for i in range(2, 27):
		for j in range(n):
			if ans[j]:
				continue
			if sum((abs(j - p) for p in indices)) == a[j]:
				ans[j] = i
		for j in range(n):
			if ans[j] == i:
				indices += [j]
		ai = ans.count(i)
		while True:
			if count[cur] >= ai:
				letters += [chr(97 + cur)]
				cur -= 1
				break
			else:
				cur -= 1
	print(''.join((letters[ans[i] - 1] for i in range(n))))


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	arr = sorted(set(s))
	ans = [-1] * m
	while sum(b) != -m:
		inds = set()
		for i in range(m):
			if b[i] == 0:
				inds.add(i)
				b[i] = -1
		while True:
			q = arr.pop()
			if len(inds) <= s.count(q):
				for i in inds:
					ans[i] = q
				else:
					break
		for i in inds:
			for j in range(m):
				if b[j] != -1:
					b[j] -= abs(i - j)
	print(''.join(ans))


import sys
import io, os
input = sys.stdin.readline

def checker(ind):
	for i in range(ind, -1, -1):
		if alpha[i] >= tmp:
			ind = i - 1
			break
	for j in tmpcount:
		ans[j] = chr(i + 97)
	return ind

def checker1(ii, bi):
	ans = 0
	for i in count:
		ans += abs(i - ii)
	if ans == bi:
		return True
	return False
q = int(input())
for ii in range(q):
	s = [i for i in input() if i != '\n']
	m = int(input())
	b = [int(i) for i in input().split()]
	ans = [0] * m
	alpha = [0] * 26
	for i in s:
		alpha[ord(i) - 97] += 1
	(count, visited) = ([], 0)
	visited2 = [0] * m
	ind = 25
	for j in range(m):
		(tmp, tmpcount) = (0, [])
		for i in range(m):
			if checker1(i, b[i]):
				if visited2[i] == 0:
					visited2[i] = 1
					tmp += 1
					tmpcount.append(i)
		ind = checker(ind)
		visited += tmp
		count += tmpcount
	print(''.join(map(str, ans)))


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = [int(x) for x in input().split()]
	indice_done = []
	i = 0
	ip = []
	if len(indice_done) == 0:
		temp = []
		for i in range(m):
			if b[i] == 0:
				indice_done.append(i)
				temp.append(i)
		ip.append(temp)
	while len(indice_done) != m:
		temp = []
		for j in range(m):
			if j not in indice_done:
				sm = 0
				for k in indice_done:
					sm += abs(j - k)
				if sm == b[j]:
					temp.append(j)
		indice_done.extend(temp)
		ip.append(temp)
	ans = [-1 for i in range(m)]
	nl = sorted(list(set(s)))
	d = {}
	for i in s:
		if i not in d.keys():
			d[i] = 1
		else:
			d[i] += 1
	si = 0
	for i in range(-1, -len(ip) - 1, -1):
		tl = len(ip[i])
		for j in range(si, len(nl)):
			if d[nl[j]] >= tl:
				for k in ip[i]:
					ans[k] = nl[j]
				si = j + 1
				break
	print(''.join(ans))


from sys import stdin, stdout
import math
input = stdin.readline

def print(x='', end='\n'):
	stdout.write(str(x) + end)

def solve():
	s = list(input())
	n = int(input())
	l = list(map(int, input().split()))
	grps = []
	while True:
		idx = []
		for i in range(n):
			if l[i] == 0:
				idx.append(i)
		if not idx:
			break
		grps.append(idx)
		for i in range(n):
			if l[i] == 0:
				l[i] = 10 ** 5
			else:
				for j in idx:
					l[i] -= abs(i - j)
	d = {}
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	d = [[k, v] for (k, v) in d.items()]
	d.sort(key=lambda x: x[0], reverse=True)
	j = 0
	ans = [0] * n
	for i in grps:
		while len(i) > d[j][1]:
			j += 1
		for k in i:
			ans[k] = d[j][0]
		j += 1
	print(''.join(ans))
test = 1
test = int(input())
for __ in range(test):
	solve()


inp = lambda : map(int, input().split(' '))
(n,) = inp()
for _ in range(n):
	arr = input()
	(m,) = inp()
	b = list(inp())
	index = set([i for i in range(m)])
	new_zero = []
	counts = [0] * 26
	for i in arr:
		counts[ord(i) - ord('a')] += 1
	end = 25
	res = [' ' for i in range(m)]
	while len(index) > 0:
		old_zero = new_zero
		new_zero = []
		for idx in index:
			for j in old_zero:
				b[idx] -= abs(idx - j)
			if b[idx] == 0:
				new_zero.append(idx)
		while counts[end] < len(new_zero):
			end -= 1
		for i in new_zero:
			res[i] = chr(ord('a') + end)
			index.remove(i)
		end -= 1
	res_str = ''.join(res)
	print(res_str)


for i in range(int(input())):
	s = input()
	m = int(input())
	b = [int(num) for num in input().split()]
	(p, sum) = ([], 0)
	while sum < m:
		x = []
		for i in range(m):
			if b[i] == 0:
				x.append(i)
				b[i] = 1227
				sum = sum + 1
		p.append(x)
		for i in range(len(x)):
			for j in range(m):
				b[j] = b[j] - abs(x[i] - j)
	s = sorted(list(s))
	(i, r, b) = (0, -1, ['#'] * m)
	while i < len(p):
		if len(p[i]) <= s.count(s[r]):
			for j in range(len(p[i])):
				b[p[i][j]] = s[r]
			r = r - s.count(s[r])
			i = i + 1
		else:
			r = r - s.count(s[r])
	print(''.join(b))


from collections import defaultdict
t = int(input())
for _ in range(t):
	d = defaultdict(int)
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	for i in s:
		d[i] += 1
	a = list(s)
	sea = list(set(a))
	sea.sort()
	b1 = [b[i] for i in range(m)]
	ans = [' ' for _ in range(m)]
	j = 1
	f = True
	while f and j <= len(sea):
		x = 1
		c = 0
		for i in range(m):
			if b[i] == 0:
				c += 1
		while j <= len(sea) and d[sea[-j]] < c:
			j += 1
		if j > len(sea):
			break
		for i in range(m):
			if b[i] == 0:
				b1[i] = -1
				x = 0
				ans[i] = sea[-j]
				for k in range(m):
					if b1[k] > 0:
						b1[k] -= abs(i - k)
		b = [b1[vf] for vf in range(m)]
		if x == 1:
			f = False
		j += 1
	print(''.join(ans))


import sys
q = int(sys.stdin.readline())
ans_arr = []
for i in range(q):
	s = sys.stdin.readline().strip()
	m = int(sys.stdin.readline())
	b = [int(j) for j in sys.stdin.readline().split()]
	arr = []
	freq = [0] * 26
	for g in range(len(s)):
		arr.append(s[g])
		freq[ord(s[g]) - 97] += 1
	arr.sort()
	ans = []
	for g in range(m):
		ans.append('a')
	ptr = len(arr) - 1
	d_idx = {}
	d_ch = {}
	for sol in range(m):
		ind = -2
		ctr = 0
		for e in range(m):
			if b[e] == 0 and e not in d_idx:
				if ind == -2:
					ind = e
				ctr += 1
		num = ord(arr[ptr]) - 97
		while freq[num] < ctr:
			for g in range(freq[num]):
				ptr -= 1
			num = ord(arr[ptr]) - 97
		d_idx[ind] = 1
		ans[ind] = arr[ptr]
		if arr[ptr] not in d_ch:
			d_ch[arr[ptr]] = 1
		else:
			d_ch[arr[ptr]] += 1
		if ctr == 1 and freq[num] - d_ch[arr[ptr]] > 0:
			for g in range(freq[num] - d_ch[arr[ptr]]):
				ptr -= 1
		ptr -= 1
		for g in range(m):
			if b[g] != 0:
				b[g] = b[g] - abs(g - ind)
	answer = ''
	for h in range(m):
		answer += ans[h]
	ans_arr.append(answer)
print('\n'.join(ans_arr))


from sys import stdin
from collections import defaultdict
input = stdin.readline
t = int(input())
for _ in range(t):
	s = input().rstrip()
	m = int(input())
	b = list(map(int, input().rstrip().split(' ')))
	d = defaultdict(lambda : 0)
	out = [0] * m
	for ele in s:
		d[ele] += 1
	d = list(d.items())
	d = sorted(d, key=lambda x: x[0], reverse=True)
	current = 0
	done = 0
	while done < m:
		idx0s = []
		for i in range(m):
			if b[i] == 0:
				idx0s.append(i)
		while len(idx0s) > d[current][1]:
			current += 1
		for ele in idx0s:
			out[ele] = d[current][0]
		for i in range(m):
			for ele in idx0s:
				if i != ele:
					b[i] -= abs(i - ele)
				else:
					b[i] = 9999
		done += len(idx0s)
		current += 1
	print(''.join(out))


from collections import defaultdict
T = int(input())
for _ in range(T):
	A = input()
	D = defaultdict(int)
	for a in A:
		D[a] += 1
	N = int(input())
	B = list(map(int, input().split()))
	decided = set()
	ans_l = []
	ans_c = []
	while len(ans_l) < N:
		cnt = 0
		poss = []
		for i in range(N):
			if i in decided:
				continue
			if sum([abs(i - j) for j in decided]) == B[i]:
				cnt += 1
				poss.append(i)
		ans_l.append(cnt)
		ans_c.append(poss)
		for p in poss:
			decided.add(p)
	ans = [None] * N
	idx = 0
	for key in sorted(D.keys(), reverse=True):
		if idx >= len(ans_l):
			break
		val = D[key]
		if ans_l[idx] <= val:
			for p in ans_c[idx]:
				ans[p] = key
			idx += 1
	print(''.join(map(str, ans)))


def help():
	stri = list(input())
	m = int(input())
	arr = list(map(int, input().split(' ')))
	order = []
	ele = []
	done = 0
	greater = [False] * 100
	for i in range(m):
		if arr[i] == 0:
			ele.append(i)
			greater[i] = True
			done += 1
	order.append(ele)
	while True:
		if done == m:
			break
		newele = []
		for i in range(m):
			if greater[i]:
				continue
			sumi = 0
			for j in range(m):
				if greater[j]:
					sumi += abs(i - j)
			if sumi == arr[i]:
				newele.append(i)
		order.append(newele[:])
		for i in newele:
			greater[i] = True
			done += 1
	dicti = {}
	for i in range(len(stri)):
		dicti[stri[i]] = dicti.get(stri[i], 0) + 1
	sortedkey = sorted(dicti.keys(), reverse=True)
	ordered_ind = 0
	final_stri = [''] * m
	done = 0
	for i in sortedkey:
		if done == m:
			break
		if dicti[i] >= len(order[ordered_ind]):
			for j in order[ordered_ind]:
				final_stri[j] = i
				done += 1
			ordered_ind += 1
	print(*final_stri, sep='')
for _ in range(int(input())):
	help()


from string import ascii_lowercase as letters
for _ in range(int(input())):
	s = input()
	occur = {}
	for i in s:
		occur[i] = occur.get(i, 0) + 1
	m = int(input())
	b = list(map(int, input().split()))
	ans = [''] * m
	indices = []
	while True:
		for i in range(m):
			if b[i] == 0:
				indices.append(i)
				b[i] = -1
		if len(indices) == 0:
			break
		for letter in reversed(letters):
			if letter in occur and occur[letter] >= len(indices):
				for i in indices:
					ans[i] += letter
				del occur[letter]
				break
			if letter in occur:
				del occur[letter]
		for i in range(m):
			for j in range(len(indices)):
				b[i] = b[i] - abs(i - indices[j])
		indices = []
	p = ''
	for i in ans:
		p += i
	print(p)


from collections import defaultdict
q = int(input())
result = None

def set_char(bs, line_cnt, line_chars, max_c, use_max):
	neg = 0
	zero_idxs = []
	for (kdx, val) in enumerate(bs):
		if val == 0:
			zero_idxs.append(kdx)
		if val < 0:
			neg += 1
	if neg == len(bs):
		return True
	for c in reversed(line_chars):
		if use_max and c >= max_c:
			continue
		if len(zero_idxs) <= line_cnt[c]:
			line_cnt_c = line_cnt[c]
			line_cnt[c] = 0
			new_bs = []
			for (kdx, val) in enumerate(bs):
				if val == 0:
					new_bs.append(-1)
				else:
					new_bs.append(val - sum((abs(kdx - jdx) for jdx in zero_idxs)))
			inner_res = set_char(new_bs, line_cnt, line_chars, c, True)
			line_cnt[c] += line_cnt_c
			if inner_res:
				for kdx in zero_idxs:
					result[kdx] = c
				return True
	return False
for idx in range(q):
	line = input().strip()
	m = int(input())
	bs = list(map(int, input().strip().split(' ')))
	result = [None for _ in bs]
	line = list(sorted(line))
	line_cnt = defaultdict(int)
	for out_c in line:
		line_cnt[out_c] += 1
	line_chars = list(sorted(list(set(line))))
	res = set_char(bs, line_cnt, line_chars, 'z', False)
	assert res
	print(''.join(result))


from __future__ import division, print_function
import os
import sys, math
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	Test = int(input())
	while Test:
		Test -= 1
		s = input()
		n = int(input())
		b = list(map(int, input().split()))
		a = [0] * 26
		for c in s:
			a[ord(c) - ord('a')] += 1
		ans = ['!'] * n
		last_char = chr(ord('z') + 1)
		while True:
			if b == [-1] * n:
				break
			zeros = []
			for i in range(n):
				if b[i] == 0:
					zeros.append(i)
			cur = '!'
			from string import ascii_lowercase
			for c in ascii_lowercase:
				if ord(last_char) <= ord(c):
					break
				if a[ord(c) - ord('a')] >= len(zeros):
					cur = c
			last_char = cur
			for val in zeros:
				ans[val] = cur
			for i in range(n):
				if b[i] > 0:
					for j in range(len(zeros)):
						b[i] -= abs(i - zeros[j])
				else:
					b[i] = -1
		for val in ans:
			print(val, end='')
		print('\n', end='')
	return None
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
import math
from collections import *

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

def get_list():
	return list(get_ints())

def printspx(*args):
	return print(*args, end='')

def printsp(*args):
	return print(*args, end=' ')
MODPRIME = int(1000000000.0 + 7)
BABYMODPR = 998244353
MAXN = int(100000.0)
for _testcases_ in range(int(input())):
	s = input()
	m = int(input())
	li = get_list()
	d = Counter(s)
	d = sorted(d.items(), reverse=True)
	ans = [-1] * m
	temp = m
	while temp:
		se = set()
		for i in range(m):
			if li[i] == 0:
				li[i] = -1
				se.add(i)
		ind = 0
		while ind < len(d):
			if d[ind][1] >= len(se):
				for j in se:
					ans[j] = d[ind][0]
				break
			ind += 1
		try:
			d = d[ind + 1:]
		except:
			d = []
		for el in se:
			for index in range(m):
				if li[index] != -1:
					li[index] -= abs(index - el)
		temp -= len(se)
	print(''.join(ans))


import math
from collections import Counter
from io import BytesIO, IOBase
import sys
import os

def Iint():
	return int(input())

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

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

def Plist(li, s=' '):
	print(s.join(map(str, li)))

def main():
	t = Iint()
	for _ in range(t):
		s = input()
		sl = len(s)
		s = sorted(Counter(s).most_common())
		m = Iint()
		b = Ilist()
		new_string = [0] * m
		Q = [i for (i, bi) in enumerate(b) if bi == 0]
		while len(Q):
			if len(Q) <= s[-1][1]:
				alp = s[-1][0]
				newQ = []
				for qi in Q:
					new_string[qi] = alp
					for i in range(m):
						if b[i] != 0:
							b[i] -= abs(i - qi)
							if b[i] == 0:
								newQ.append(i)
				s.pop()
				Q = newQ
			else:
				s.pop()
		Plist(new_string, '')
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))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

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

def li():
	return [int(i) for i in input().split()]

def ls():
	return [i for i in input().split()]

def fun():
	for i in vis:
		if i == -1:
			return 1
	return 0
for t in range(ii()):
	t += 1
	s = input()
	f = [0 for i in range(26)]
	n = len(s)
	m = ii()
	b = li()
	for i in s:
		f[ord(i) - 97] += 1
	vis = [-1 for i in range(m)]
	z = 0
	ind = 25
	while fun():
		store = []
		z += 1
		lol = []
		for i in range(m):
			if b[i] == 0 and vis[i] == -1:
				store.append(i)
				lol.append(i)
		x = -1
		for i in range(ind, -1, -1):
			if f[i] >= len(lol):
				x = i
				break
		ind = x - 1
		f[x] -= len(lol)
		for i in lol:
			vis[i] = x
		for i in range(m):
			if b[i] != 0:
				for j in store:
					if b[i] >= abs(i - j):
						b[i] -= abs(i - j)
	s = ''
	for i in vis:
		s += chr(i + 97)
	print(s)


t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	arr = [int(i) for i in input().split()]
	a = 'abcdefghijklmnopqrstuvwxyz'
	dic = {}
	for i in range(26):
		dic[a[i]] = 0
	for i in range(len(s)):
		dic[s[i]] += 1
	ans = ['' for i in range(m)]
	l = 25
	while True:
		c = 0
		boo = True
		for i in range(m):
			if arr[i] == 0:
				c += 1
				boo = False
		if boo:
			break
		ind = []
		for i in range(l, -1, -1):
			if dic[a[i]] >= c:
				for j in range(m):
					if arr[j] == 0:
						ind.append(j + 1)
						arr[j] = -1
						ans[j] = a[i]
				l = i - 1
				break
		for i in range(m):
			temp = 0
			for j in ind:
				temp = temp + abs(i + 1 - j)
			if arr[i] > 0:
				arr[i] -= temp
	print(''.join(ans))


t = int(input())
ans = []
for _ in range(t):
	s = list(input())
	x = sorted(set(s))
	n = int(input())
	l = list(map(int, input().split()))
	z = [0] * n
	while l != [-1] * n:
		c = 0
		for i in range(n):
			if l[i] == 0:
				c += 1
		while True:
			q = x.pop()
			if c <= s.count(q):
				break
		y = []
		for i in range(n):
			if l[i] == 0:
				z[i] = q
				y.append(i)
				l[i] = -1
		for i in range(n):
			if l[i] != -1:
				su = 0
				for j in y:
					su += abs(i - j)
				l[i] = l[i] - su
	ans.append(''.join(z))
print('\n'.join(ans))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
inf = 10 ** 20
mod = 10 ** 9 + 7

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

def II():
	return int(input())

def LS():
	return list(input().split())

def S():
	return input()

def solve():
	s = list(S())
	num_cnts = collections.Counter(s)
	s = list(set(s))
	m = II()
	a_list = LI()
	s.sort()
	j = 0
	cnts = 0
	ans = ['' for _ in range(m)]
	kkk = len(s) - 1
	while cnts < m:
		d = collections.deque()
		for (ci, c) in enumerate(a_list):
			if c == 0:
				d.append(ci)
		while len(d) > num_cnts[s[kkk]]:
			kkk -= 1
		while d:
			max_i = d.pop()
			for j in range(m):
				a_list[j] -= abs(max_i - j)
			a_list[max_i] -= 1
			ans[max_i] = s[kkk]
			cnts += 1
			if cnts == m:
				return ans
		kkk -= 1
	return ['miss']

def main():
	t = II()
	res = list()
	for _ in range(t):
		ans = solve()
		res.append(ans)
	for ans in res:
		print(''.join(ans))
	return 0
main()


for mda in range(int(input())):
	s = input()
	d = dict()
	for x in s:
		if d.get(x) == None:
			d[x] = 1
		else:
			d[x] += 1
	n = int(input())
	a = list(map(int, input().split()))
	tt = [''] * n
	used = [False] * len(s)
	t = 0
	while t != n:
		zero = []
		for i in range(n):
			if a[i] == 0:
				zero.append(i)
				a[i] = -1
		ch = ''
		for x in d.keys():
			if d[x] >= len(zero):
				if ch == '':
					ch = x
				elif ord(ch) < ord(x):
					ch = x
		for x in d.keys():
			if ord(x) >= ord(ch):
				d[x] = 0
		for i in range(n):
			if a[i] != -1:
				for x in zero:
					a[i] -= abs(i - x)
		for x in zero:
			tt[x] = ch
		t += len(zero)
	for x in tt:
		print(x, end='')
	print()


def test():
	s = list(input())
	occ = {}
	for i in range(len(s)):
		if occ.get(s[i]) == None:
			occ[s[i]] = 1
		else:
			occ[s[i]] += 1
	vals = [(i, occ[i]) for i in occ]
	vals.sort()
	m = int(input())
	a = list(map(int, input().split()))
	ans = ['*' for i in range(m)]
	while m:
		(alphabet, occurs) = vals.pop()
		if a.count(0) <= occurs:
			m -= a.count(0)
			pos = []
			for j in range(len(a)):
				if a[j] == 0:
					pos.append(j)
					a[j] = -1
			for j in range(len(a)):
				for k in pos:
					a[j] -= abs(k - j)
			for k in pos:
				ans[k] = alphabet
	final = ''
	for i in ans:
		final += i
	print(final)
for t in range(int(input())):
	test()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class SegmentTree1:

	def __init__(self, data, default=9999999, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	s = list(input())
	s.sort(reverse=True)
	d = dict()
	for i in range(len(s)):
		if s[i] not in d:
			d.update({s[i]: 1})
		else:
			d[s[i]] += 1
	s = list(set(s))
	s.sort(reverse=True)
	n = int(input())
	ans = [''] * n
	l = list(map(int, input().split()))
	t = 0
	while max(l) > 0:
		e = []
		e1 = l.count(0)
		while e1 > d[s[t]]:
			t += 1
		for i in range(n):
			if l[i] == 0:
				ans[i] = s[t]
				l[i] = -1
				e.append(i)
		for i in e:
			for j in range(i - 1, -1, -1):
				if ans[j] == '':
					l[j] -= i - j
			for j in range(i + 1, n):
				if ans[j] == '':
					l[j] -= j - i
		t += 1
	while l.count(0) > d[s[t]]:
		t += 1
	for i in range(n):
		if ans[i] == '' and l[i] == 0:
			ans[i] = s[t]
	print(*ans, sep='')


def solve(line, bees):
	line = sorted(line, reverse=True)
	line2 = []
	quant = []
	for i in line:
		if i not in line2:
			line2.append(i)
			quant.append(1)
		else:
			quant[len(quant) - 1] += 1
	line = line2
	del line2
	B = len(bees)
	result_old = [None] * B
	result_new = [None] * B
	while filled(result_new) == False:
		to_edit = []
		for i in range(B):
			if value(result_old, i) == bees[i] and result_old[i] == None:
				to_edit.append(i)
		if len(to_edit) <= quant[0]:
			for i in to_edit:
				result_new[i] = line[0]
		result_old = result_new.copy()
		line.pop(0)
		quant.pop(0)
	return ''.join(result_old)

def filled(result):
	for i in result:
		if i == None:
			return False
	return True

def value(line, p):
	result = 0
	for i in range(len(line)):
		if line[i] != None:
			result += abs(i - p)
	return result
N = int(input())
result = []
for i in range(N):
	line = input()
	m = int(input())
	bees = [int(x) for x in input().split()]
	result.append(solve(line, bees))
for i in result:
	print(i)


import sys
for _ in range(int(sys.stdin.readline().rstrip())):
	s = sys.stdin.readline().rstrip()
	n = int(sys.stdin.readline().rstrip())
	b = list(map(int, sys.stdin.readline().rstrip().split()))
	s = list(s)
	s.sort(reverse=True)
	re = ['0'] * n
	re_cnt = 0
	while True:
		if re_cnt == n:
			break
		zero_cnt = 0
		zero_target = []
		for i in range(n):
			if b[i] == 0:
				zero_cnt += 1
				zero_target.append(i)
		x = 0
		while True:
			word_cnt = 0
			target = s[x]
			last = 0
			for i in range(x, len(s)):
				if s[i] == target:
					word_cnt += 1
				else:
					last = i
					break
			if word_cnt >= zero_cnt:
				break
			else:
				x = last
		for i in zero_target:
			re[i] = target
			for j in range(n):
				if b[j] > 0:
					b[j] -= abs(j - i)
			b[i] = -1
			re_cnt += 1
		while True:
			if len(s) == 0:
				break
			if target <= s[0]:
				s.remove(s[0])
			else:
				break
	for i in re:
		print(i, end='')
	print()


import sys
inp = [x for x in sys.stdin.read().split()]
ii = 0
ttt = int(inp[ii])
ii += 1
for _ in range(ttt):
	(s, m) = (inp[ii], int(inp[ii + 1]))
	ii += 2
	b = [int(x) for x in inp[ii:ii + m]]
	ii += m
	cnt = [0] * 26
	for c in s:
		cnt[ord(c) - ord('a')] += 1
	res = [-1] * m
	for c in range(25, -1, -1):
		cur_ind = []
		for i in range(m):
			if res[i] == -1:
				cur_sum = 0
				for j in range(m):
					if res[j] != -1:
						cur_sum += abs(i - j)
				if cur_sum == b[i]:
					cur_ind.append(i)
		if len(cur_ind) <= cnt[c]:
			for i in cur_ind:
				res[i] = c
	print(''.join((chr(c + ord('a')) for c in res)))


from collections import Counter
for _ in range(int(input())):
	s = list(input())
	m = int(input())
	barr = list(map(int, input().split()))
	barr = [(i, x) for (i, x) in enumerate(barr)]
	dct = Counter(s)
	s = list(set(s))
	s.sort()
	t = [None for _ in range(m)]
	while m:
		i0s = list(map(lambda o: o[0], filter(lambda o: not o[1], barr)))
		c = s.pop()
		while dct[c] < len(i0s):
			c = s.pop()
		for i in i0s:
			t[i] = c
			barr[i] = (i, -1)
			m -= 1
		for (j, x) in barr:
			if x > 0:
				sm = 0
				for i in i0s:
					sm += abs(j - i)
				barr[j] = (j, barr[j][1] - sm)
	print(''.join(t))


from collections import defaultdict

def read_list():
	return list(map(int, input().strip().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))
N = int(input())
for _ in range(N):
	s = input()
	n = int(input())
	b = read_list()
	dic = [0] * 26
	for c in s:
		dic[ord(c) - ord('a')] += 1
	now = 25
	state = [0] * n
	big = set()
	count = 0
	res = ['0'] * n
	tmp = b.count(0)
	count += tmp
	while dic[now] < tmp:
		now -= 1
	dic[now] -= tmp
	c = chr(ord('a') + now)
	last = 0
	for _ in range(tmp):
		find = b.index(0, last)
		res[find] = c
		last = find + 1
		big.add(find)
	for i in range(n):
		if i not in big:
			for bign in big:
				state[i] += abs(bign - i)
	now -= 1
	while count < n:
		this = []
		for i in range(n):
			if i not in big and state[i] == b[i]:
				this.append(i)
		l = len(this)
		while dic[now] < l:
			now -= 1
		c = chr(ord('a') + now)
		for i in this:
			big.add(i)
			res[i] = c
		for i in range(n):
			if i not in big:
				for bign in this:
					state[i] += abs(bign - i)
		count += l
		now -= 1
	print(''.join(map(str, res)))


for _ in range(int(input())):
	s = sorted(input())
	m = int(input())
	ans = ['' for i in range(m)]
	b = list(map(int, input().split()))
	freq = [0 for i in range(26)]
	for i in s:
		freq[ord(i) - ord('a')] += 1
	ind = []
	k = 25
	for i in range(m):
		if b[i] == 0:
			ind.append(i)
	z = m
	while z > 0:
		x = len(ind)
		while freq[k] < x:
			k -= 1
		for i in range(m):
			if b[i] == 0 and ans[i] == '':
				ans[i] = chr(ord('a') + k)
				z -= 1
		k -= 1
		nin = []
		for i in range(m):
			if b[i] != 0:
				for j in ind:
					b[i] -= abs(i - j)
				if b[i] == 0:
					nin.append(i)
		ind = nin.copy()
	print(''.join(ans))


def answer(s, m, B):
	d = {}
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	l = list(d.keys())
	l.sort()
	w = [0] * (m + 1)
	count1 = 0
	while count1 < m:
		tmp = []
		for i in range(m):
			if B[i] == 0:
				tmp.append(i + 1)
				B[i] = -1
		count1 += len(tmp)
		for i in range(m):
			if B[i] != -1:
				c = 0
				for j in tmp:
					c += abs(j - i - 1)
				B[i] -= c
		for i in range(len(l) - 1, -1, -1):
			if d[l[i]] >= len(tmp):
				for j in tmp:
					w[j] = l[i]
				l = l[:i]
				break
	return ''.join(w[1:])
t = int(input())
for i in range(t):
	n = input()
	m = int(input())
	B = list(map(int, input().split()))
	print(answer(n, m, B))


for _ in range(int(input())):
	s = list(input())
	s.sort()
	m = int(input())
	a = list(map(int, input().split()))
	while a.count(0):
		qani = []
		for i in range(m):
			if a[i] == 0:
				qani.append(i)
		while s.count(s[-1]) < len(qani):
			while len(s) > 1 and s[-1] == s[-2]:
				s.pop()
			s.pop()
		now = s[-1]
		while len(s) and s[-1] == now:
			s.pop()
		for i in qani:
			a[i] = now
		for i in range(m):
			for x in qani:
				try:
					a[i] -= abs(i - x)
				except:
					pass
	print(''.join(a))


import collections
import os
import sys
from io import BytesIO, IOBase
import math

def main():
	t = int(input())
	for _ in range(t):
		s = input()
		m = int(input())
		B = list(map(int, input().split()))
		freq = collections.Counter(s)
		ans = ['.'] * m
		ch = 'z'
		chv = ord(ch)
		while True:
			zeros = []
			for (i, v) in enumerate(B):
				if v == 0:
					B[i] = -1
					zeros.append(i)
			if len(zeros) == 0:
				break
			while chv >= 97:
				if freq[chr(chv)] >= len(zeros):
					break
				chv -= 1
			for i in zeros:
				ans[i] = chr(chv)
			for i in range(m):
				if ans[i] == '.':
					for y in zeros:
						B[i] -= abs(i - y)
			zeros.clear()
			chv -= 1
		print(''.join(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

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

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
from collections import Counter
t = iinput()
for _ in range(t):
	s = list(input())
	m = iinput()
	b = rlinput()
	S = sorted(list(Counter(s).items()), key=lambda x: x[0])
	t = [None for i in range(m)]
	count = 0
	visited = [False] * m
	while count < m:
		index = []
		for i in range(m):
			if b[i] == 0 and (not visited[i]):
				index.append(i)
				visited[i] = True
		while True:
			cur = S.pop()
			if cur[1] >= len(index):
				break
		for idx in index:
			t[idx] = cur[0]
			count += 1
		for i in range(m):
			if not visited[i]:
				for idx in index:
					b[i] -= abs(i - idx)
	print(''.join(t))


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		s = input()
		n = int(input())
		a = [int(x) for x in input().split()]
		ga = [0] * 26
		for x in s:
			ga[ord(x) - ord('a')] += 1
		ans = [-1] * n
		for cur in reversed(range(26)):
			if ga[cur] == 0:
				continue
			b = [0] * n
			(cnt, c) = (0, 0)
			for i in range(n):
				b[i] += cnt
				if ans[i] >= 0:
					c += 1
				cnt += c
			(cnt, c) = (0, 0)
			for i in reversed(range(n)):
				b[i] += cnt
				if ans[i] >= 0:
					c += 1
				cnt += c
			d = []
			for i in range(n):
				if b[i] == a[i] and ans[i] == -1:
					d.append(i)
			if len(d) > ga[cur]:
				continue
			for x in d:
				ans[x] = cur
		print(''.join((chr(x + ord('a')) for x in 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()


t = int(input())
for _ in range(t):
	freq = {}
	a = input()
	for ax in a:
		freq[ax] = freq.get(ax, 0) + 1
	a = sorted(set(a), reverse=True)
	bl = int(input())
	b = list(map(int, input().split()))
	l = []
	li = 0
	while li < bl:
		sm = []
		for bi in range(bl):
			if b[bi] == 0:
				sm.append(bi)
				b[bi] = -1
		for bi in range(bl):
			if b[bi] != -1:
				dis = 0
				for x in sm:
					dis += abs(bi - x)
				b[bi] -= dis
		l.append(sm)
		li += len(sm)
	ans = ['a' for _ in range(bl)]
	ai = 0
	for lx in l:
		while freq[a[ai]] < len(lx):
			ai += 1
		for ii in lx:
			ans[ii] = a[ai]
		ai += 1
	print(''.join(ans))


nt = int(input())
while nt > 0:
	nt -= 1
	s = input()
	n = int(input())
	a = []
	occurance = {}
	store = set()
	for x in s:
		store.add(x)
		if x in occurance:
			occurance[x] += 1
		else:
			occurance[x] = 1
	store = sorted(store, reverse=True)
	final = []
	position_of_zero = []
	num0 = 0
	a = list(map(int, input().split()))
	for i in range(0, n):
		final.append(0)
		if a[i] == 0:
			num0 += 1
			position_of_zero.append(i)
	for i in range(0, len(store)):
		if occurance[store[i]] >= num0:
			for q in position_of_zero:
				final[q] = store[i]
			store = store[i + 1:]
			break
	changer = []
	while True:
		if len(position_of_zero) == n:
			break
		changer.clear()
		num0 = 0
		for i in range(0, n):
			if type(final[i]) == str:
				continue
			else:
				final[i] = 0
				for k in position_of_zero:
					final[i] += abs(k - i)
				if final[i] == a[i]:
					num0 += 1
					changer.append(i)
		for j in range(0, len(store)):
			if occurance[store[j]] >= num0:
				for q in changer:
					final[q] = store[j]
				store = store[j + 1:]
				position_of_zero.extend(changer)
				break
	for z in final:
		print(z, end='')
	print()


t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	slist = []
	for i in range(len(s)):
		slist.append(s[i])
	slist.sort()
	slist.reverse()
	slist2 = []
	slist2.append([slist[0], 1])
	for i in range(1, len(s)):
		if slist2[-1][0] == slist[i]:
			slist2[-1][1] += 1
		else:
			slist2.append([slist[i], 1])
	pointer = 0
	done = [0] * m
	ans = [0] * m
	while sum(done) < m:
		zeros = []
		for i in range(m):
			if b[i] == 0 and done[i] == 0:
				zeros.append(i)
		num = len(zeros)
		while slist2[pointer][1] < num:
			pointer += 1
		for i in zeros:
			done[i] = 1
			ans[i] = slist2[pointer][0]
			for j in range(m):
				b[j] -= abs(i - j)
		pointer += 1
	print(''.join(ans))


letters = 'abcdefghijklmnopqrstuvwxyz'
T = int(input())

def min_index(bs):
	min_b = 2000
	min_is = []
	for (i, b) in enumerate(bs):
		if b == None:
			continue
		if b == min_b:
			min_is.append(i)
		if b < min_b:
			min_b = b
			min_is = [i]
	for i in min_is:
		bs[i] = None
	return (min_is, min_b)

def max_letter(letter_dict, many):
	for l in letters[::-1]:
		if letter_dict[l] >= many:
			letter_dict[l] = 0
			return l
		letter_dict[l] = 0
for t in range(T):
	letter_dict = dict()
	for l in letters:
		letter_dict[l] = 0
	s = input()
	for a in s:
		letter_dict[a] += 1
	m = int(input())
	ans = list(range(m))
	bs = list((int(b) for b in input().split()))
	while True:
		(min_is, min_b) = min_index(bs)
		if len(min_is) == 0:
			break
		a = max_letter(letter_dict, len(min_is))
		for i in min_is:
			ans[i] = a
			for (j, b) in enumerate(bs):
				if b is not None:
					bs[j] -= abs(j - i)
	for a in ans:
		print(a, end='')
	print()


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def main():
	for _ in range(int(input())):
		s = sorted(input())
		m = int(input())
		ans = ['' for i in range(m)]
		b = list(map(int, input().split()))
		freq = [0 for i in range(26)]
		for i in s:
			freq[ord(i) - ord('a')] += 1
		ind = []
		k = 25
		for i in range(m):
			if b[i] == 0:
				ind.append(i)
		z = m
		while z > 0:
			x = len(ind)
			while freq[k] < x:
				k -= 1
			for i in range(m):
				if b[i] == 0 and ans[i] == '':
					ans[i] = chr(ord('a') + k)
					z -= 1
			k -= 1
			nin = []
			for i in range(m):
				if b[i] != 0:
					for j in ind:
						b[i] -= abs(i - j)
					if b[i] == 0:
						nin.append(i)
			ind = nin.copy()
		print(''.join(ans))
main()


import collections
for _ in range(int(input())):
	s = input()
	c = collections.Counter(s)
	sor = sorted(list(c))
	n = int(input())
	v = list(map(int, input().split()))
	q = []
	ans = []
	for (i, x) in enumerate(v):
		if x == 0:
			q.append(i)
			v[i] = -1
	ans = [0] * len(v)
	while len(q) != 0:
		while c[sor[-1]] < len(q):
			sor.pop()
		for x in q:
			ans[x] = sor[-1]
		sor.pop()
		tmp = []
		for (i, x) in enumerate(v):
			if x == -1:
				continue
			for location in q:
				v[i] -= abs(location - i)
			if v[i] == 0:
				v[i] = -1
				tmp.append(i)
		q = tmp
	print(''.join(ans))


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	C = defaultdict(int)
	for c in s:
		C[c] += 1
	s = sorted(C.items())
	m = int(input())
	l = list(map(int, input().split()))
	know = set()
	ans = ['#'] * m
	while len(know) < m:
		cur = []
		for i in range(m):
			if l[i] == 0:
				know.add(i)
				cur.append(i)
		while s[-1][1] < len(cur):
			s.pop()
		for i in cur:
			l[i] = 10 ** 9
			ans[i] = s[-1][0]
			for j in range(m):
				l[j] -= abs(i - j)
		s.pop()
	print(''.join(ans))


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		s = sys.stdin.readline().strip()
		n = int(input())
		nums = list(map(int, sys.stdin.readline().split()))
		if n == 1:
			print(s[0])
			continue
		numsSorted = [[nums[i], i] for i in range(n)]
		numsSorted.sort()
		numsSorted = list(reversed(numsSorted))
		strDict = {}
		for i in s:
			if i not in strDict:
				strDict[i] = 1
			else:
				strDict[i] += 1
		usedPos = []
		sList = [i for i in s]
		sList.sort()
		ans = [None] * n

		def backtracking(_ans: [int], _sList: [str], _usedPos: [int]) -> [str]:
			if len(_usedPos) == n:
				return _ans
			while _sList:
				_temp = _sList.pop()
				for i in range(n):
					if _ans[i] != None:
						continue
					sumVal = 0
					for j in range(len(_usedPos)):
						if _ans[_usedPos[j]] != _temp:
							sumVal += abs(i - _usedPos[j])
					if sumVal == nums[i]:
						_ans[i] = _temp
						_usedPos.append(i)
						tempAns = backtracking(_ans[:], _sList[:], _usedPos)
						if tempAns:
							return tempAns
						_ans[i] = None
						_usedPos.pop()
						break
			return []
		realAns = backtracking(ans, sList, usedPos)
		ans = ''
		for i in realAns:
			ans += i
		print(ans)
	return
main()


from collections import deque
q = int(input())

def find_zero_idx():
	(val, no) = ([], 0)
	for i in range(m):
		if arr[i] == 0:
			val.append(i)
			arr[i] = 100000.0
			no += 1
	return (val, no)

def find_char(count, freq):
	for i in range(25, -1, -1):
		if freq[i]:
			if freq[i] >= count:
				alphabet = chr(i + 97)
				freq[i] = -1
				return alphabet
			else:
				freq[i] = -1

def solve():
	freq = list(bytearray(26))
	for c in s:
		idx = ord(c) - 97
		freq[idx] += 1
	for i in range(26):
		if freq[i] == 0:
			freq[i] = -1
	ans = [None for i in range(m)]
	filled = 0
	while True:
		(zero_idx, total_zero) = find_zero_idx()
		character = find_char(total_zero, freq)
		if total_zero == 0:
			break
		for idx in zero_idx:
			ans[idx] = character
			filled += 1
		for i in range(m):
			if ans[i] == None:
				for idx in zero_idx:
					arr[i] -= abs(i - idx)
	return ''.join(ans)
for _ in range(q):
	s = list(input())
	m = int(input())
	arr = list(map(int, input().split()))
	ans = solve()
	print(ans)


T = int(input())
for _ in range(T):
	s = input()
	m = int(input())
	b = [int(s) for s in input().split()]
	count = [0] * 26
	for c in s:
		count[ord(c) - 97] += 1
	res = [''] * m
	p = 0
	while p < m:
		zeros = []
		for i in range(m):
			if b[i] == 0:
				zeros.append(i)
		for i in range(25, -1, -1):
			if count[i] >= len(zeros):
				c = chr(i + 97)
				count[i] = 0
				break
			else:
				count[i] = 0
		for zero in zeros:
			res[zero] = c
			b[zero] = -1
			for i in range(m):
				b[i] -= abs(i - zero)
		p += len(zeros)
	print(''.join(res))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	S = input().strip()
	m = int(input())
	B = list(map(int, input().split()))
	LIST = [0] * 26
	for s in S:
		LIST[ord(s) - 97] += 1
	ANS = [0] * m
	ind = 25
	while max(B) >= 0:
		L = []
		for i in range(m):
			if B[i] == 0:
				L.append(i)
				B[i] = -1
		LEN = len(L)
		while LIST[ind] < LEN:
			ind -= 1
		for l in L:
			ANS[l] = ind
		ind -= 1
		for l in L:
			for i in range(m):
				B[i] -= abs(i - l)
	print(''.join([chr(a + 97) for a in ANS]))


import io
import os
from collections import Counter, defaultdict, deque

def solve(S, M, B):
	letterFreq = Counter(S)
	letters = sorted(letterFreq.keys())
	T = [None for i in range(M)]
	done = 0
	while done != M:
		zeroes = [i for (i, b) in enumerate(B) if b == 0]
		while letterFreq[letters[-1]] < len(zeroes):
			letters.pop()
		for i in zeroes:
			T[i] = letters[-1]
			done += 1
			B[i] = None
		letters.pop()
		for i in zeroes:
			for j in range(M):
				if B[j] is not None:
					B[j] -= abs(i - j)
	return ''.join(T)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
Q = int(input())
for q in range(Q):
	S = input().decode().rstrip()
	(M,) = [int(x) for x in input().split()]
	B = [int(x) for x in input().split()]
	ans = solve(S, M, B)
	print(ans)


def find_zeros(ss):
	re = []
	for sss in range(len(ss)):
		if ss[sss] == 0:
			re.append(sss)
	return re
for q in range(int(input())):
	s = input()
	m = int(input())
	d = dict()
	cur_value = m
	b = list(map(int, input().split()))
	times = []
	while len(d) != m:
		zeros = find_zeros(b)
		for z in zeros:
			b[z] = -1
			d[z] = cur_value
		times = [len(zeros)] + times
		cur_value -= 1
		for i in range(m):
			if b[i] != -1:
				b[i] -= sum([abs(z - i) for z in zeros])
	sd = sorted(s) + ['A']
	s_list = []
	cur_c = sd[0]
	counter = 0
	ab_list = []
	for i in sd:
		if i == cur_c:
			counter += 1
		else:
			ab_list.append(cur_c)
			cur_c = i
			s_list.append(counter)
			counter = 1
	start = 100
	l = len(times)
	abc_list = []
	for i in times:
		while s_list[0] < i:
			s_list = s_list[1:]
			ab_list = ab_list[1:]
		abc_list.append(ab_list[0])
		s_list = s_list[1:]
		ab_list = ab_list[1:]
	ans = ['0'] * m
	for key in range(m):
		ans[key] = abc_list[d[key] - m + l - 1]
	print(''.join(ans))


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	m = int(input())
	l = list(map(int, input().split()))
	arr = set()
	d = defaultdict(int)
	for i in s:
		arr.add(i)
		d[i] += 1
	arr = sorted(list(arr), reverse=True)
	new_s = [''] * m
	j = 0
	count = 1
	while count > 0:
		add = []
		count = 0
		for i in range(m):
			if l[i] == 0:
				add.append(i)
				count += 1
		if count == 0:
			break
		while d[arr[j]] < count:
			j += 1
		for i in add:
			new_s[i] = arr[j]
			l[i] = -1
		for i in range(m):
			if l[i] > 0:
				for e in add:
					l[i] -= abs(e - i)
		j += 1
	print(''.join(new_s))


from collections import deque
from operator import itemgetter
from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for _ in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(s, m, b):
	buckets = {}
	for item in s:
		if item not in buckets:
			buckets[item] = 0
		buckets[item] += 1
	thing_to_sort = [[key, buckets[key]] for key in buckets]
	letters = deque(sorted(thing_to_sort, key=itemgetter(0)))
	result = [None] * len(b)
	indices = []
	visited = set()
	while len(indices) < m:
		this_time = []
		for (i, code) in enumerate(b):
			look_for = 0
			for index in indices:
				look_for += abs(i - index)
			if look_for == code and i not in visited:
				this_time.append(i)
				visited.add(i)
		assert len(this_time) > 0
		curr = letters.pop()
		while curr[1] < len(this_time):
			curr = letters.pop()
		for item in this_time:
			result[item] = curr[0]
		indices += this_time
	return ''.join(result)
for i in tests():
	s = str_in()
	m = int_in()
	b = arr_in()
	out(solve(s, m, b))


import sys

def calculate(prevWordList: list, finalWordDistances: list):
	prevWordChars = getSortedCharsFromWord(prevWordList)
	finalWordReverseSortedChars = getReverseSortedCharsFromDistances(finalWordDistances)
	finalWordChars = getFinalWordChars(prevWordChars, finalWordReverseSortedChars)
	return getOutput(finalWordChars)

def getReverseSortedCharsFromDistances(wordCharDistances: list):
	output = {}
	toBeSearchedPositions = {idx: distance for (idx, distance) in enumerate(wordCharDistances)}
	while len(toBeSearchedPositions) > 0:
		recentlyKnownPositionIndexes = []
		for (posIdx, distance) in toBeSearchedPositions.items():
			if distance == 0:
				recentlyKnownPositionIndexes.append(posIdx)
		output[len(output)] = recentlyKnownPositionIndexes
		for index in recentlyKnownPositionIndexes:
			del toBeSearchedPositions[index]
		for recentlyKnownPositionIndex in recentlyKnownPositionIndexes:
			for posIdx in toBeSearchedPositions:
				toBeSearchedPositions[posIdx] -= abs(posIdx - recentlyKnownPositionIndex)
	return output

def getSortedCharsFromWord(wordList: list):
	output = {}
	for word in wordList:
		value = ord(word)
		if value in output:
			output[value] += 1
		else:
			output[value] = 1
	return {k: output[k] for k in sorted(output.keys())}

def getFinalWordChars(prevWordCharsCount: dict, finalWordReversedChars: dict):
	output = {}
	finalWordCurrentIdx = 0
	reversedPrevWordCharsCount = [[k, prevWordCharsCount[k]] for k in reversed(list(prevWordCharsCount.keys()))]
	for prevWordChar in reversedPrevWordCharsCount:
		if finalWordCurrentIdx >= len(finalWordReversedChars):
			break
		finalWordCharOccurrences = finalWordReversedChars[finalWordCurrentIdx]
		if prevWordChar[1] >= len(finalWordCharOccurrences):
			for occurrenceIdx in finalWordCharOccurrences:
				output[occurrenceIdx] = prevWordChar[0]
			finalWordCurrentIdx += 1
	return output

def getOutput(finalWordChars):
	output = []
	for charIdx in sorted(finalWordChars.keys()):
		output.append(chr(finalWordChars[charIdx]))
	return ''.join(output)

def getInput():
	prevWordList = list(sys.stdin.readline().rstrip())
	sys.stdin.readline()
	finalWordDistances = list(map(int, sys.stdin.readline().rstrip().split()))
	return (prevWordList, finalWordDistances)
inputs = []
numOfInput = sys.stdin.readline()
for inputIndex in range(0, int(numOfInput)):
	inputs.append(getInput())
for lineInput in inputs:
	result = calculate(*lineInput)
	print(result)


import sys
from collections import Counter

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

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

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

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

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	S = input()
	M = len(S)
	N = INT()
	A = LIST()
	cur = []
	for (i, a) in enumerate(A):
		if a == 0:
			cur.append(i)
	li = []
	while cur:
		li.append(cur)
		nxt = []
		for i in cur:
			j = i + 1
			while j < N:
				A[j] -= j - i
				if A[j] == 0:
					nxt.append(j)
				j += 1
			j = i - 1
			while j >= 0:
				A[j] -= i - j
				if A[j] == 0:
					nxt.append(j)
				j -= 1
		cur = nxt
	C = sorted(Counter(S).items(), reverse=True)
	ans = [''] * N
	i = 0
	for (k, v) in C:
		if len(li[i]) > v:
			continue
		for j in li[i]:
			ans[j] = k
		i += 1
		if i >= len(li):
			break
	print(''.join(ans))


from sys import stdin
input = stdin.readline

def main():
	test = int(input())
	for _ in range(test):
		l = list(input().strip())
		ss = list(set(l))
		ss.sort(reverse=True)
		m = int(input())
		b = [int(i) for i in input().split(' ')]
		s = ['' for i in range(m)]
		t = 0
		val = [0 for i in range(m)]
		while t < len(ss):
			ll = []
			for i in range(m):
				if b[i] == val[i]:
					ll.append(i)
			p = ss[t]
			while t < len(ss):
				p = ss[t]
				c = l.count(p)
				t += 1
				if c >= len(ll):
					break
			for i in ll:
				s[i] = p
			for i in range(m):
				if i not in ll and val[i] != -1:
					for j in range(len(ll)):
						val[i] += abs(i - ll[j])
				else:
					val[i] = -1
		print(''.join(s))
main()


from sys import stdin
from bisect import bisect_left
from collections import Counter

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

def sinput():
	return input()

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

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

def bs(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	else:
		return -1
t = iinput()
while t:
	t -= 1
	s = sinput()
	m = iinput()
	b = linput()
	d = Counter(s)
	ts = [0] * m
	alpha = 26
	while True:
		temp = []
		for i in range(m):
			if b[i] == 0 and ts[i] == 0:
				ts[i] = alpha
				temp.append(i)
		alpha -= 1
		for i in temp:
			sub = 1
			for j in range(i + 1, m):
				if b[j] != 0:
					b[j] -= sub
				sub += 1
			sub = 1
			for j in range(i - 1, -1, -1):
				if b[j] != 0:
					b[j] -= sub
				sub += 1
		if 0 not in ts:
			break
	mn = min(ts)
	for i in range(m):
		ts[i] -= mn
	d = list(d.items())
	d.sort()
	j = 0
	mx = max(ts)
	for c in range(0, mx + 1):
		cnt = ts.count(c)
		for e in range(j, len(d)):
			if d[e][1] >= cnt:
				for k in range(m):
					if ts[k] == c:
						ts[k] = d[e][0]
				j = e + 1
				break
	print(''.join(ts))


from functools import cmp_to_key
from collections import deque
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
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')
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def ii():
	return int(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

def sli():
	return list(map(str, inp().split()))

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		if self.size[a] < self.size[b]:
			(a, b) = (b, a)
		self.num_sets -= 1
		self.parent[b] = a
		self.size[a] += self.size[b]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)

def custom_sort(lista):

	def cmp(x, y):
		if x + y > y + x:
			return 1
		else:
			return -1
	return sorted(lista, key=cmp_to_key(cmp))
MOD = 10 ** 9 + 7
maxN = 10 ** 5
FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def coeffBinom(n, k):
	if n < k:
		return 0
	return divide(FACT[n], multiply(FACT[k], FACT[n - k]))

def primes(N):
	smallest_prime = [1] * (N + 1)
	prime = []
	smallest_prime[0] = 0
	smallest_prime[1] = 0
	for i in range(2, N + 1):
		if smallest_prime[i] == 1:
			prime.append(i)
			smallest_prime[i] = i
		j = 0
		while j < len(prime) and i * prime[j] <= N:
			smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i])
			j += 1
	return (prime, smallest_prime)

def gcd(a, b):
	a = abs(a)
	b = abs(b)
	(s, t, r) = (0, 1, b)
	(old_s, old_t, old_r) = (1, 0, a)
	while r != 0:
		quotient = old_r // r
		(old_r, r) = (r, old_r - quotient * r)
		(old_s, s) = (s, old_s - quotient * s)
		(old_t, t) = (t, old_t - quotient * t)
	return (old_r, old_s, old_t)

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def create_edges(m, unweighted=0):
	edges = list()
	if unweighted:
		for i in range(m):
			edges.append(li(lag=-1))
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			edges.append([w, x, y])
	return edges

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def connected(graph, n):
	v = dfs(graph, n, 0)
	for el in v:
		if el == -1:
			return False
	return True

def topological(graph, n):
	indegree = [0] * n
	for el in range(n):
		for child in graph[el]:
			indegree[child] += 1
	s = deque()
	for el in range(n):
		if indegree[el] == 0:
			s.append(el)
	order = []
	while s:
		el = s.popleft()
		order.append(el)
		for child in graph[el]:
			indegree[child] -= 1
			if indegree[child] == 0:
				s.append(child)
	if n == len(order):
		return (False, order)
	else:
		return (True, [])

def bipartite(graph, n):
	color = [-1] * n
	color[0] = 0
	s = [0]
	while s:
		el = s.pop()
		for child in graph[el]:
			if color[child] == color[el]:
				return False
			if color[child] == -1:
				s.append(child)
			color[child] = 1 - color[el]
	return True

def dijkstra(graph, n, A):
	dist = [float('inf') for i in range(n)]
	prev = [-1 for i in range(n)]
	dist[A] = 0
	pq = []
	heappush(pq, [0, A])
	while pq:
		[d_v, v] = heappop(pq)
		if d_v != dist[v]:
			continue
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
				prev[to] = v
				heappush(pq, [dist[to], to])
	return (dist, prev)

def dijkstra_0_1(graph, n, A):
	dist = [float('inf') for i in range(n)]
	dist[A] = 0
	p = deque()
	p.append(A)
	while p:
		v = p.popleft()
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
			if w == 1:
				q.append(to)
			else:
				q.appendleft(to)
	return dist

def floyd_warshall(graph, n):
	dist = [[float('inf') for _ in range(n)] for _ in range(n)]
	for i in range(n):
		dist[i][i] = 0
		for (child, d) in graph[i]:
			dist[i][child] = d
			dist[child][i] = d
	for k in range(n):
		for i in range(n):
			for j in range(j):
				dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
	return dist

def minimum_spanning_tree(edges, n):
	edges = sorted(edges)
	union_find = UnionFind(n)
	used_edges = list()
	for (w, x, y) in edges:
		if union_find.find(x) != union_find.find(y):
			union_find.merge(x, y)
			used_edges.append([w, x, y])
	return used_edges

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def finding_ancestors(parent, queries, n):
	steps = int(ceil(log(n, 2)))
	ancestors = [[-1 for i in range(n)] for j in range(steps)]
	ancestors[0] = parent
	for i in range(1, steps):
		for node in range(n):
			if ancestors[i - 1][node] != -1:
				ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]]
	result = []
	for (node, k) in queries:
		ans = node
		if k >= n:
			ans = -1
		i = 0
		while k > 0 and ans != -1:
			if k % 2:
				ans = ancestors[i][ans]
			k = k // 2
			i += 1
		result.append(ans)
	return result

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def nearest_from_the_left_smaller_elements(arr):
	n = len(arr)
	res = [-1] * n
	s = []
	for (i, el) in enumerate(arr):
		while s and s[-1] >= el:
			s.pop()
		if s:
			res[i] = s[-1]
		s.append(el)
	return res

def sliding_window_minimum(arr, k):
	res = []
	q = deque()
	for (i, el) in enumerate(arr):
		while q and arr[q[-1]] >= el:
			q.pop()
		q.append(i)
		while q and q[0] <= i - k:
			q.popleft()
		if i >= k - 1:
			res.append(arr[q[0]])
	return res

def meno(a, idx):
	for i in range(len(a)):
		a[i] -= abs(i - idx)
	return a

def find_zeri(a):
	idx = list()
	for i in range(len(a)):
		if a[i] == 0:
			idx.append(i)
	return idx

def find_lettere(s):
	res = [0 for i in range(26)]
	for i in range(len(s)):
		res[ord(s[i]) - ord('a')] += 1
	return res
for test in range(ii()):
	s = str(inp())
	n = ii()
	a = li()
	t = ['' for i in range(n)]
	lett = find_lettere(s)
	l = 25
	count = 0
	while count < n:
		idx = find_zeri(a)
		count += len(idx)
		while l >= 0 and lett[l] < len(idx):
			l -= 1
		for i in idx:
			t[i] = chr(l + ord('a'))
			a = meno(a, i)
			a[i] = -1
		l -= 1
	print_list(t, '')


import sys

def rs():
	return sys.stdin.readline().rstrip()

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

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(s, m, b):
	n = len(s)
	ss = sorted([si for si in s], reverse=True)
	t = [''] * m
	ci = 0
	not_taken = [i for i in range(m)]
	for _ in range(m):
		cnt = 0
		tt = set()
		for j in range(m):
			if t[j] == '' and b[j] == 0:
				tt.add(j)
				not_taken.remove(j)
				cnt += 1
		if cnt == 0:
			break
		while True:
			k = 0
			while k < cnt and ci + k < n and (ss[ci + k] == ss[ci]):
				k += 1
			if k == cnt:
				break
			else:
				ci += k
		for j in tt:
			t[j] = ss[ci]
		k = 0
		while ci + k < n and ss[ci + k] == ss[ci]:
			k += 1
		ci += k
		for j in not_taken:
			for k in tt:
				b[j] -= abs(j - k)
	return ''.join(t)

def main():
	for _ in range(ri()):
		s = rs()
		m = ri()
		b = ria()
		ws(solve(s, m, b))
main()


for _ in range(int(input())):
	st = list(input())
	m = int(input())
	ar = list(map(int, input().split()))
	li = [0] * m
	ans = [0] * m
	se = set({})
	level = 1
	while li != ar:
		tem = set({})
		for i in range(m):
			if not i in se:
				if ar[i] == li[i]:
					se.add(i)
					tem.add(i)
					ans[i] = level
		for i in tem:
			for j in range(m):
				if not j in se:
					li[j] += abs(j - i)
		level += 1
	for i in range(m):
		if ans[i] == 0:
			ans[i] = level
	dic = {}
	for i in range(m):
		if ans[i] in dic:
			dic[ans[i]] += 1
		else:
			dic[ans[i]] = 1
	fre = []
	se = set({})
	tem = 'abcdefghijklmnopqrstuvwxyz'
	tem = tem[::-1]
	st.sort(reverse=True)
	for i in st:
		if not i in se:
			se.add(i)
			fre.append(1)
		else:
			fre[-1] += 1
	dic1 = {}
	j = 0
	for i in range(level):
		while fre[j] < dic[i + 1]:
			j += 1
		dic1[i + 1] = j
		j += 1
	st = list(set(st))
	st.sort(reverse=True)
	for i in range(m):
		ans[i] = st[dic1[ans[i]]]
	print(''.join(ans))


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

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

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math
from collections import deque
import collections

def main():
	tc = ri()
	for _ in range(tc):
		s = rs()
		s = sorted(s, reverse=True)
		m = ri()
		b = ria()
		d = {}
		ans = ['.'] * m
		for i in s:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
		od = d
		noit = []
		uc = []
		n0 = 10000000
		while True:
			n0 = 0
			n0i = []
			for i in range(m):
				if b[i] == 0 and i + 1 not in noit:
					n0 += 1
			c = ''
			for i in od:
				if i not in uc and od[i] >= n0:
					c = i
					uc.append(i)
					break
				uc.append(i)
			for i in range(m):
				if b[i] == 0 and i + 1 not in noit:
					ans[i] = c
					n0i.append(i + 1)
					noit.append(i + 1)
			for i in range(m):
				if i + 1 not in noit:
					for j in n0i:
						b[i] -= abs(i + 1 - j)
			if len(noit) == m:
				break
		ws(''.join(ans))

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	B = [int(b) for b in input().split()]
	ans = ['?'] * m
	L = [0] * 26
	for i in range(len(s)):
		L[ord(s[i]) - 97] += 1
	i = 25
	while i >= 0:
		temp = []
		if L[i] == 0:
			i -= 1
			continue
		if B.count(0) > L[i]:
			i -= 1
			continue
		for j in range(m):
			if B[j] == 0:
				ans[j] = chr(i + 97)
				B[j] = -1
				temp.append(j)
		for j in range(m):
			if B[j] == -1:
				continue
			for k in temp:
				B[j] -= abs(j - k)
		i -= 1
	print(''.join(ans))


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	s = sorted(list(inp()))[::-1]
	m = int(inp())
	b = lis()
	cnt = {}
	for i in range(0, len(s)):
		if cnt.get(s[i]) == None:
			cnt[s[i]] = 1
		else:
			cnt[s[i]] += 1
	index = 0
	ans = [0] * m
	count = 0
	while count != m:
		temp = []
		for j in range(0, m):
			if b[j] == 0:
				temp.append(j)
				b[j] = -1
		while cnt[s[index]] < len(temp):
			index += 1
		for j in range(len(temp)):
			ans[temp[j]] = s[index]
		count += len(temp)
		for j in range(0, m):
			if b[j] != -1:
				for l in range(len(temp)):
					b[j] -= abs(j - temp[l])
		index += cnt[s[index]]
	lol = ''
	for i in range(0, m):
		lol += ans[i]
	print(lol)
testcase(int(inp()))


def noX(ans):
	for i in ans:
		if i == 'X':
			return False
	return True

def updateArr(bArr, updatedThisTime):
	for i in range(0, len(bArr)):
		if bArr[i] != 0 or i not in updatedThisTime:
			continue
		subValue = 1
		j = i + 1
		while j < len(bArr):
			if bArr[j] == 0:
				j += 1
				subValue += 1
				continue
			bArr[j] = bArr[j] - subValue
			j += 1
			subValue += 1
		subValue = 1
		j = i - 1
		while j >= 0:
			if bArr[j] == 0:
				j = j - 1
				subValue += 1
				continue
			bArr[j] = bArr[j] - subValue
			j = j - 1
			subValue += 1
for _ in range(int(input())):
	s = list(input())
	s.sort(reverse=True)
	di = {}
	for i in s:
		di[i] = di.get(i, 0) + 1
	n = int(input())
	liStr = input().split()
	bArr = []
	for i in liStr:
		bArr.append(int(i))
	ans = []
	for i in range(len(bArr)):
		ans.append('X')
	start = 0
	sNoDup = []
	dup = set()
	for i in s:
		if i not in dup:
			dup.add(i)
			sNoDup.append(i)
	while not noX(ans):
		updatedThisTime = set()
		newAddCtr = 0
		for i in range(len(bArr)):
			if bArr[i] == 0 and ans[i] == 'X':
				newAddCtr += 1
				updatedThisTime.add(i)
		while di[sNoDup[start]] < newAddCtr:
			start += 1
		for i in range(0, len(bArr)):
			if bArr[i] == 0 and ans[i] == 'X':
				ans[i] = sNoDup[start]
		updateArr(bArr, updatedThisTime)
		start += 1
	for p in ans:
		print(p, end='')
	print()


t = int(input())
for i in range(t):
	s = input()
	b = []
	d = dict()
	for j in s:
		if j in d.keys():
			d[j] += 1
		else:
			b.append(j)
			d[j] = 1
	b.sort(reverse=True)
	n = int(input())
	a = list(map(int, input().split()))
	c = ['a'] * n
	m = 1
	f = dict()
	p = 0
	while m <= n:
		j = 0
		k = []
		while j < n:
			if a[j] == 0 and j not in f.keys():
				f[j] = 1
				k.append(j)
			j += 1
		while p < len(b):
			if d[b[p]] < len(k):
				p += 1
			else:
				for i in k:
					c[i] = b[p]
				p += 1
				break
		j = 0
		while j < n:
			if j not in f.keys():
				for i in k:
					a[j] += -abs(i - j)
			j += 1
		m += len(k)
	print(''.join(c))


for _ in range(int(input())):
	s = input()
	s = sorted(list(s), reverse=True)
	m = int(input())
	arr = list(map(int, input().split()))
	si = 0
	flag = [0] * m
	ans = [''] * m
	while sum(flag) != m:
		back = []
		for i in range(m):
			if arr[i] == 0 and flag[i] == 0:
				back.append(i)
		while si < len(s) and s[si] != s[si + len(back) - 1]:
			si += 1
		for c in back:
			ans[c] = s[si]
			flag[c] = 1
		k = s[si]
		while si < len(s) and s[si] == k:
			si += 1
		for i in range(m):
			if flag[i] == 0:
				for j in back:
					arr[i] -= abs(i - j)
	print(''.join(ans))


from sys import stdin
input = lambda : stdin.readline().strip()
char = [chr(i) for i in range(97, 123)]
CHAR = [chr(i) for i in range(65, 91)]
mp = lambda : list(map(int, input().split()))
INT = lambda : int(input())
rn = lambda : range(INT())
from math import ceil, sqrt, factorial, gcd
for _ in rn():
	l = input()
	h = len(l)
	n = INT()
	b = mp()
	d = {}
	for j1 in l:
		if j1 in d:
			d[j1] += 1
		else:
			d[j1] = 1
	l = sorted(set(l))
	while len(l) > 0:
		zero_c = []
		for i1 in range(n):
			if type(b[i1]) == int and b[i1] == 0:
				zero_c.append(i1)
		k = l.pop()
		while len(zero_c) > d[k]:
			k = l.pop()
		for i in range(n):
			if type(b[i]) == int and b[i] == 0:
				b[i] = k
			elif type(b[i]) == int and b[i] != 0:
				sm = 0
				for j in zero_c:
					sm += abs(i - j)
				b[i] = b[i] - sm
	print(''.join(b))


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')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

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

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

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		s = list(input())
		m = N()
		arr = RLL()
		indarr = [(v, i) for (i, v) in enumerate(arr)]
		dic = {v: i for (i, v) in enumerate(arr)}
		cs = list(Counter(s).items())
		cs.sort()
		sm = []
		res = ['' for _ in range(m)]
		pt = len(cs) - 1
		for i in range(m):
			if pt < 0:
				break
			new = []
			for j in range(m):
				if res[j] != '':
					continue
				(nowv, nowi) = indarr[j]
				cal = 0
				for num in sm:
					cal += abs(j + 1 - num)
				if cal == nowv:
					new.append(nowi + 1)
			while pt >= 0 and len(new) > cs[pt][1]:
				pt -= 1
			if pt < 0:
				break
			for k in new:
				res[k - 1] = cs[pt][0]
			pt -= 1
			sm.extend(new)
		print(''.join(res))
main()


def know_new(l):
	place = []
	for i in range(len(l)):
		if l[i] == 0:
			place.append(i)
	for i in range(len(b)):
		if b[i] != 0 and b[i] != -1:
			for j in range(len(place)):
				b[i] -= abs(i - place[j])
	for e in range(len(place) - 1, -1, -1):
		b[place[e]] = -1
	save.append(place)
	return len(place)
t = int(input())
for x in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	a = [0 for i in range(26)]
	for i in range(len(s)):
		a[ord(s[i:i + 1]) - ord('a')] += 1
	arr = []
	save = []
	while b != [-1 for zxc in range(len(b))]:
		arr.append(know_new(b))
	j = 25
	i = 0
	ans = [0 for el in range(len(b))]
	while i < len(arr) and j > -1:
		if a[j] >= arr[i]:
			for element in save[i]:
				ans[element] = chr(ord('a') + j)
			i += 1
		j -= 1
	print(''.join(map(str, ans)))


q = int(input())
for i in range(q):
	s = str(input())
	m = int(input())
	arr = list(map(int, input().split()))
	num = sorted(s)
	lis = [0] * 26
	ans = [0] * m
	for j in range(len(s)):
		lis[ord(num[j]) - 97] += 1
	count1 = arr.count(0)
	index = 25
	while count1 != 0:
		for j in range(index + 1):
			if lis[index] >= count1:
				lis[index] = 0
				break
			index -= 1
		array = []
		for j in range(m):
			if arr[j] == 0:
				array.append(j)
				arr[j] = -1
				ans[j] = chr(index + 97)
		index -= 1
		l = len(array)
		for k in range(l):
			for j in range(m):
				if arr[j] > 0:
					arr[j] -= abs(j - array[k])
		count1 = arr.count(0)
	answer = ''
	for j in ans:
		answer += j
	print(answer)


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for _ in range(int(input())):
	q = input()
	w = int(input())
	e = list(map(int, input().split()))
	r = sorted(q)[::-1]
	p = {r[0]: 1}
	for i in range(1, len(q)):
		if r[i] == r[i - 1]:
			p[r[i]] += 1
		else:
			p[r[i]] = 1
	t = [None] * w
	x = list(p)
	o = 0
	for z in list(p):
		l = []
		for i in range(w):
			k = 0
			if t[i] == None:
				for j in range(w):
					if t[j] != None and t[j]:
						k += abs(j - i)
				if e[i] == k:
					l.append(i)
		if p[z] >= len(l):
			for i in l:
				t[i] = z
	print(''.join(t))


from sys import stdin
for _ in range(int(input())):
	a = input()
	m = int(input())
	(*b,) = map(int, input().split())
	cnt = [a.count(chr(i + 97)) for i in range(26)]
	idx = []
	p = 25
	ans = [0] * m
	while len(idx) < m:
		tmp = [sum((abs(i - j) for j in idx)) for i in range(m)]
		c = [i for i in range(m) if not idx.count(i) and b[i] == tmp[i]]
		while cnt[p] < len(c):
			p -= 1
		for i in c:
			ans[i] = chr(p + 97)
		idx = idx + c
		p -= 1
	print(''.join(ans))


t = int(input())

def process_array(b):
	partial_sum = [0 for i in range(len(b))]
	placement = [0 for i in range(len(b))]
	for i in range(len(b)):
		matches = [j for j in range(len(b)) if b[j] == partial_sum[j]]
		if len(matches) == 0:
			break
		for m in matches:
			partial_sum[m] = -1
			placement[m] = i
		for j in range(len(b)):
			if partial_sum[j] >= 0:
				for m in matches:
					partial_sum[j] += abs(j - m)
	return placement
for i in range(t):
	s = input()
	m = int(input())
	b = [int(x) for x in input().split(' ')]
	placement = process_array(b)
	dic = {}
	for ss in range(len(s)):
		if s[ss] not in dic:
			dic[s[ss]] = 1
		else:
			dic[s[ss]] += 1
	d_k = list(dic.keys())
	d_k = sorted(d_k, reverse=True)
	b_d = {}
	for bb in placement:
		if bb not in b_d:
			b_d[bb] = 1
		else:
			b_d[bb] += 1
	b_k = list(b_d.keys())
	b_k = sorted(b_k)
	count_list = [b_d[x] for x in b_k]
	ans_k = []
	d_iter = 0
	for c in count_list:
		while dic[d_k[d_iter]] < c:
			d_iter += 1
		ans_k.append(d_k[d_iter])
		d_iter += 1
	ans = [0 for j in range(len(placement))]
	for j in range(len(ans)):
		ans[j] = ans_k[placement[j]]
	print(''.join(ans))


def prog():
	for _ in range(int(input())):
		s = list(input().strip())
		m = int(input())
		b = list(map(int, input().split()))
		s.sort(reverse=True)
		most = []
		prev = 'asdf'
		for val in s:
			if val != prev:
				prev = val
				most.append([1, val])
			else:
				most[-1][0] += 1
		idx = 0
		output = [0] * m
		placed = 0
		while placed != m:
			zeros = []
			for i in range(m):
				if b[i] == 0:
					zeros.append(i)
			placed += len(zeros)
			for i in zeros:
				b[i] = -1
			while most[idx][0] < len(zeros):
				idx += 1
			for i in zeros:
				output[i] = most[idx][1]
				for j in range(m):
					if b[j] != -1:
						b[j] -= abs(i - j)
			idx += 1
		print(''.join(output))
prog()


from collections import defaultdict
from collections import Counter

def change(List):
	d = dict(Counter(List))
	res = []
	for (key, item) in d.items():
		res.append((key, item))
	res.sort()
	return res

def solve():
	s = list(input())
	s = change(s)
	alpha = list('abcdefghijklmnopqrstuvwxyz')
	alpha.sort(reverse=True)
	m = int(input())
	zero_list = []
	visited = [False] * m
	ans = ['1'] * m
	a = list(map(int, input().split()))
	for i in range(m):
		if a[i] == 0:
			zero_list.append(i)
	while zero_list:
		target = []
		while zero_list:
			x = zero_list.pop()
			visited[x] = True
			target.append(x)
		zerocnt = len(target)
		while s[-1][1] < zerocnt:
			s.pop()
		(String, cnt) = s.pop()
		for x in target:
			ans[x] = String
			for j in range(m):
				if visited[j] == False:
					a[j] -= abs(x - j)
		for io in range(m):
			if a[io] == 0 and visited[io] == False:
				zero_list.append(io)
	print(''.join(ans))

def main():
	t = int(input())
	for i in range(t):
		solve()
	return
main()


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split(' ')))
	ans = [''] * m
	dic = {}
	for i in range(len(s)):
		if s[i] in dic.keys():
			dic[s[i]] += 1
		else:
			dic[s[i]] = 1
	sorted_array = []
	for i in dic.keys():
		sorted_array.append(i)
	sorted_array.sort()
	last_allowed = len(sorted_array) - 1
	while True:
		indexes = []
		for i in range(len(b)):
			if b[i] == 0:
				indexes.append(i)
		if indexes == []:
			break
		alphabet = ''
		while True:
			if dic[sorted_array[last_allowed]] >= len(indexes):
				alphabet = sorted_array[last_allowed]
				last_allowed -= 1
				break
			else:
				last_allowed -= 1
		for i in indexes:
			ans[i] = alphabet
			b[i] = -1
			c = 1
			for j in range(i - 1, -1, -1):
				b[j] -= c
				c += 1
			c = 1
			for j in range(i + 1, len(b)):
				b[j] -= c
				c += 1
	answer = ''
	for i in ans:
		answer += i
	print(answer)


from collections import Counter
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
REV_ALPHA = 'abcdefghijklmnopqrstuvwxyz'[::-1]

def ans(M, S):
	letters = [None] * len(M)
	counter = 0
	while sum([m for m in M if m is not None]) > 0:
		next_M = M[:]
		for _ in range(M.count(0)):
			i = M.index(0)
			letters[i] = REV_ALPHA[counter]
			for j in range(len(M)):
				if next_M[j] is not None and next_M[j] > 0:
					next_M[j] -= abs(i - j)
			M[i] = None
			next_M[i] = None
		counter += 1
		M = next_M
	for i in range(len(M)):
		if letters[i] is None:
			letters[i] = REV_ALPHA[counter]
	freqs = Counter(letters)
	target = []
	for a in ALPHA:
		if freqs[a] > 0:
			target += [freqs[a]]
	freqs = Counter(S)
	source = []
	sourcemap = []
	for a in ALPHA:
		if freqs[a] > 0:
			source += [freqs[a]]
			sourcemap += [a]
	indexes = []
	i = 0
	for j in target:
		while source[i] < j:
			i += 1
		indexes += [i]
		i += 1
	matchedsource = []
	for i in indexes:
		matchedsource += sourcemap[i]
	matchedletters = sorted(list(set(letters)))
	assert len(matchedletters) == len(matchedsource)
	translate = dict()
	for (l, s) in zip(matchedletters, matchedsource):
		translate[l] = s
	return ''.join((translate[l] for l in letters))
T = int(input())
for t in range(T):
	S = input()
	input()
	M = input().split(' ')
	M = [int(x) for x in M]
	print(ans(M, S))


def process():
	string = input().strip()
	n = int(input())
	vals = list(map(int, input().split(' ')))
	ans = [None for _ in range(len(vals))]
	counts = [0 for _ in range(26)]
	cur = 26
	for elem in string:
		counts[ord(elem) - ord('a')] += 1
	while not all(ans):
		zeros = [i for (i, val) in enumerate(vals) if val == 0]
		zero_count = len(zeros)
		for i in range(cur - 1, -1, -1):
			if counts[i] >= zero_count:
				for (j, elem) in enumerate(vals):
					if elem == 0:
						ans[j] = chr(ord('a') + i)
				for (j, elem) in enumerate(vals):
					if vals[j] == 0:
						vals[j] = -1
					else:
						vals[j] -= sum((abs(j - x) for x in zeros))
				cur = i
				break
	print(''.join(ans))
t = int(input())
for _ in range(t):
	process()


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
import io, os
input = sys.stdin.readline
from bisect import *
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().strip().split()))
rls = lambda : list(map(str, input().split()))
t = int(input())
for _ in range(0, t):
	s = input().strip()
	n = int(input().strip())
	m = n
	b = rl()
	ans = [0] * n
	left = [0] * n
	mark = [0] * n
	d = defaultdict(lambda : 0)
	for i in s:
		d[ord(i) - 97] += 1
	total = 0
	x = 25
	while 1:
		s1 = 0
		a = []
		for i in range(0, n):
			if mark[i] == 0 and b[i] == 0:
				a.append(i)
				s1 = s1 + 1
				total += 1
		for j in range(x, -1, -1):
			if d[j] >= s1:
				x = j - 1
				char = chr(97 + j)
				d[j] = -1
				break
		for i in a:
			ans[i] = char
			mark[i] = 1
		for i in range(0, n):
			if mark[i] == 0:
				s2 = 0
				for j in a:
					s2 = s2 + abs(i - j)
				b[i] = b[i] - s2
		if total == m:
			break
	print(''.join(ans))


q = int(input())
for _ in range(q):
	s = list(input())
	m = int(input())
	b = list(map(int, input().split()))
	n = len(s)
	alphcnt = [0] * 26
	for i in s:
		alphcnt[122 - ord(i)] += 1
	now = [0] * m
	cnt = 0
	u = []
	for _ in range(26):
		end = []
		for i in range(m):
			if b[i] == now[i]:
				cnt += 1
				end.append(i)
		if not end:
			break
		for j in end:
			for i in range(m):
				now[i] += abs(i - j)
			now[j] = 114514
		u.append(end)
	ans = ['?'] * m
	i = 0
	for v in u:
		l = len(v)
		while not alphcnt[i] >= l:
			i += 1
		for j in v:
			ans[j] = chr(122 - i)
		i += 1
	ans = ''.join(ans)
	print(ans)


q = int(input())
from collections import Counter
for _ in range(q):
	s = Counter(input())
	m = int(input())
	b = list(map(int, input().split()))
	t = ['' for i in range(m)]
	if m == 1:
		print(list(s.keys())[0])
		continue
	i = b.index(0)
	i = [b.index(0)]
	while 0 in b[i[-1] + 1:]:
		i.append(b.index(0, i[-1] + 1))
	c = max(s.keys())
	while s[c] < len(i):
		del s[c]
		c = max(s.keys())
	for j in i:
		t[j] = c
	del s[c]
	while len(i) != len(t):
		i2 = []
		for (j, k) in enumerate(b):
			if t[j] == '' and k == sum([abs(l - j) for l in i]):
				i2.append(j)
		c = max(s.keys())
		while s[c] < len(i2):
			del s[c]
			c = max(s.keys())
		for j in i2:
			t[j] = c
		del s[c]
		i.extend(i2)
	print(''.join(t))


for p in range(int(input())):
	s = list(input())
	m = int(input())
	a = list(map(int, input().split()))
	s.sort()
	s.reverse()
	se = sorted(list(set(s)))[::-1]
	t = []
	j = 0
	while len(t) != m:
		l = []
		for i in range(m):
			if a[i] == 0:
				a[i] = -1
				l.append(i)
		while True:
			if s.count(se[j]) >= len(l):
				for k in range(len(l)):
					t.append([l[k], se[j]])
					for y in range(m):
						a[y] -= abs(l[k] - y)
				j += 1
				break
			j += 1
	t.sort()
	ans = ''
	for i in range(m):
		ans += t[i][1]
	print(ans)


testcases = int(input())
for testcase in range(testcases):
	strs = input()
	temparr = []
	for i in strs:
		temparr.append(str(i))
	characc = temparr[:]
	tempset = set(temparr)
	charac = list(tempset)
	charac = sorted(charac)
	charac = charac[::-1]
	charfreq = {}
	for i in characc:
		if i not in charfreq:
			charfreq[i] = 1
		else:
			charfreq[i] += 1
	newlen = int(input())
	ans = [''] * newlen
	temparr = input()
	temparr = temparr.split()
	numberarr = []
	for i in temparr:
		numberarr.append(int(i))
	numlen = len(numberarr)
	numberofzero = []
	for (i, j) in enumerate(numberarr):
		if j == 0:
			numberofzero.append(i)
	indexnum = 0
	while len(numberofzero):
		charr = charac[indexnum]
		while len(numberofzero) > charfreq[charr]:
			indexnum += 1
			charr = charac[indexnum]
		for i in numberofzero:
			ans[i] = charac[indexnum]
			numberarr[i] -= 1
		indexnum += 1
		for index in numberofzero:
			times = 1
			indexdec = index - 1
			indexinc = index + 1
			while indexdec >= 0:
				numberarr[indexdec] -= times
				times += 1
				indexdec -= 1
			times = 1
			while indexinc < numlen:
				numberarr[indexinc] -= times
				times += 1
				indexinc += 1
		numberofzero = []
		for (i, j) in enumerate(numberarr):
			if j == 0:
				numberofzero.append(i)
	print(''.join(ans))


test_case = int(input())
for _ in range(test_case):
	st = input()
	n = int(input())
	arr = list(map(int, input().split()))
	x = sorted(set(st))
	final = [None] * len(arr)
	while arr.count(-1) != len(arr):
		zeros = []
		for i in range(len(arr)):
			if arr[i] == 0:
				zeros.append(i)
				arr[i] = -1
		while True:
			val = x.pop()
			if len(zeros) <= st.count(val):
				for i in zeros:
					final[i] = val
				break
		for i in zeros:
			for j in range(len(arr)):
				if arr[j] != -1:
					arr[j] -= abs(i - j)
	for i in final:
		print(i, end='')
	print()


q = int(input())
for q in range(0, q):
	s = input()
	m = int(input())
	b = [int(x) for x in input().split()]
	count = [0 for i in range(0, 26)]
	for ch in s:
		count[ord(ch) - ord('a')] += 1
	k = 25
	ans = ['a' for i in range(0, m)]
	okay = -1
	while k >= 0:
		c = []
		for i in range(0, m):
			if b[i] == 0:
				c.append(i)
				b[i] = okay
		d = len(c)
		while count[k] < d:
			k -= 1
		for i in range(0, m):
			if b[i] > 0:
				for j in c:
					b[i] -= abs(i - j)
			elif b[i] == okay:
				ans[i] = chr(ord('a') + k)
		k -= 1
		okay -= 1
	for all in ans:
		print(all, end='')
	print('')


def solve(s, m, b):
	f = [0] * 26
	for c in s:
		f[ord(c) - ord('a')] += 1
	sol = [-1] * m

	def _solve(xx):
		for x in range(xx, -1, -1):
			indices = []
			for i in range(m):
				if sol[i] == -1:
					hm = 0
					for j in range(m):
						if sol[j] != -1:
							hm += abs(i - j)
					if hm == b[i]:
						indices.append(i)
			if f[x] >= len(indices):
				for i in indices:
					sol[i] = x
					f[x] -= 1
				if all((c != -1 for c in sol)) or _solve(x - 1):
					return True
				for i in indices:
					sol[i] = -1
					f[x] += 1
		return False
	_solve(25)
	return ''.join((chr(ord('a') + x) for x in sol))
t = int(input())
for _ in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	print(solve(s, m, b))


from collections import Counter
for nt in range(int(input())):
	s = list(input())
	c = Counter(s)
	s = list(set(s))
	n = len(s)
	s.sort(reverse=True)
	m = int(input())
	b = list(map(int, input().split()))
	j = 0
	ans = [-1] * m
	while b.count(-1) != m:
		x = b.count(0)
		while x > c[s[j]]:
			j += 1
		ind = []
		for i in range(m):
			if b[i] == 0:
				ans[i] = s[j]
				b[i] = -1
				ind.append(i)
		for i in range(m):
			if b[i] > 0:
				for k in ind:
					b[i] -= abs(k - i)
		j += 1
	print(''.join(map(str, ans)))


for _ in range(int(input())):
	S = input()
	N = int(input())
	B = list(map(int, input().split()))
	counts = {}
	levels = []
	for i in range(len(S)):
		if S[i] in counts:
			counts[S[i]] += 1
		else:
			counts[S[i]] = 1
	pos = []
	currlevel = []
	for i in range(N):
		if B[i] == 0:
			currlevel.append(i)
			pos.append(i)
	levels.append(currlevel)
	while len(pos) < N:
		counter = 0
		currlevel = []
		for i in pos:
			counter += i
		sub = len(pos)
		for i in range(N):
			if i in pos:
				sub -= 2
				counter -= sub
			elif counter == B[i]:
				currlevel.append(i)
				counter -= sub
			else:
				counter -= sub
		if len(currlevel) > 0:
			pos.extend(currlevel)
			levels.append(currlevel)
	tocheck = [0] * N
	for i in range(len(levels)):
		for j in levels[i]:
			tocheck[j] = i + 1
	alpha = list(counts.keys())
	alpha.sort(reverse=True)
	keyl = 0
	finans = [0] * N
	for i in range(1, len(levels) + 1):
		while True:
			if counts[alpha[keyl]] >= len(levels[i - 1]):
				for j in range(len(tocheck)):
					if j in levels[i - 1]:
						finans[j] = alpha[keyl]
				keyl += 1
				break
			else:
				keyl += 1
	s = ''
	for i in finans:
		s += i
	print(s)


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	ans = [None] * m
	a = list(reversed(sorted(s)))
	i = 0
	while i < len(a):
		pos = []
		cnt = 0
		for j in range(m):
			if b[j] == 0 and ans[j] is None:
				cnt += 1
				pos.append(j)
		for j in range(i, len(a)):
			l = len(set(a[j:j + cnt]))
			if l == 1:
				i = j
				break
		for j in range(cnt):
			ans[pos[j]] = a[i]
			i += 1
		for j in range(m):
			for k in pos:
				if j == k:
					continue
				b[j] -= abs(k - j)
		if i < len(a):
			while a[i] == a[i - 1] and i < len(a) - 1:
				i += 1
		ok = True
		for j in ans:
			if j is None:
				ok = False
		if ok:
			break
	print(''.join(ans))


production = True
import sys, math

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = next_line.split()
		elif input_format == 4:
			formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
		elif input_format == 5:
			formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 1:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$')
		print(*args)

def y(s):
	t = []
	for (i, j) in enumerate(s):
		if j == 0:
			t.append(i)
	return t

def solve():
	s = [ord(x) - 97 for x in input(10) if x != '\n']
	m = input(11)
	b = input(1)
	freq = [0] * 26
	for i in s:
		freq[i] += 1
	o = []
	k = y(b)
	log(b)
	log(k)
	while k:
		u = sum(k)
		r = set(k)
		for (i, j) in enumerate(b):
			if i not in r:
				for q in k:
					b[i] -= abs(q - i)
		o.append(k)
		for i in k:
			b[i] = -1
		k = y(b)
		log(b)
		log(o)
	d = 25
	v = [''] * m
	log(freq)
	for i in o:
		for j in range(d, -1, -1):
			if len(i) <= freq[j]:
				for q in i:
					v[q] = chr(j + 97)
				d = j - 1
				break
	log(' ')
	out(''.join(v))
	return
for i in range(input(11)):
	solve()


import sys
input = sys.stdin.readline
from collections import *
from bisect import *
q = int(input())
for _ in range(q):
	s = input()[:-1]
	alpha = list(set(s))
	alpha.sort(reverse=True)
	cnt = Counter(s)
	m = int(input())
	b = list(map(int, input().split()))
	ans = [''] * m
	fills = 0
	alp_idx = 0
	while True:
		fill = []
		for i in range(m):
			if ans[i] == '':
				c = 0
				for j in range(m):
					if ans[j] != '':
						c += abs(i - j)
				if b[i] == c:
					fill.append(i)
		while True:
			if len(fill) > cnt[alpha[alp_idx]]:
				alp_idx += 1
			else:
				break
		for i in fill:
			ans[i] = alpha[alp_idx]
			fills += 1
		alp_idx += 1
		if fills == m:
			break
	print(''.join(ans))


import sys
input = sys.stdin.readline
from math import log2, log, ceil

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return res

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	while x != link[x]:
		x = link[x]
	return x

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)
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')
from collections import Counter
for _ in range(int(input())):
	s = input()
	c = Counter(s)
	s = list(set(s))
	n = len(s)
	s.sort(reverse=True)
	m = int(input())
	b = list(map(int, input().split()))
	j = 0
	ans = [-1] * m
	while b.count(-1) != m:
		x = b.count(0)
		while c[s[j]] < x:
			j += 1
		ind = []
		for i in range(m):
			if b[i] == 0:
				ans[i] = s[j]
				b[i] = -1
				ind.append(i)
		for i in range(m):
			if b[i] > 0:
				for k in ind:
					b[i] -= abs(k - i)
		j += 1
	print(''.join(ans))


from collections import Counter
for _ in range(int(input())):
	g = sorted(Counter(input()).items())
	m = int(input())
	b = list(map(int, input().split()))
	ans = [' '] * m
	while 1:
		inds = []
		for i in range(m):
			if b[i] == 0:
				inds.append(i)
				b[i] = -1
		if not inds:
			break
		while 1:
			(letter, v) = g.pop(-1)
			if v >= len(inds):
				break
		for i in inds:
			ans[i] = letter
		for i in range(m):
			if b[i] != -1:
				s = 0
				for j in inds:
					s += abs(i - j)
				b[i] -= s
	print(''.join(ans))


for _ in range(int(input())):
	s = list(input().strip())
	m = int(input())
	ans = [None] * m
	B = list(map(int, input().split()))
	s.sort(reverse=True)
	scnt = []
	cnt = 1
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			cnt += 1
		else:
			scnt.append(cnt)
			cnt = 1
	scnt.append(cnt)
	vis = [True] * m
	si = j = 0
	curr = [bi for bi in range(m) if B[bi] == 0]
	while len(curr):
		while scnt[si] < len(curr):
			j += scnt[si]
			si += 1
		for bi in curr:
			vis[bi] = False
			ans[bi] = s[j]
			for bii in range(m):
				B[bii] -= abs(bi - bii)
		j += scnt[si]
		si += 1
		curr = [bi for bi in range(m) if B[bi] == 0 and vis[bi]]
	print(''.join(ans))


from collections import Counter

def main():
	T = int(input())
	for _ in range(T):
		S = input()
		M = int(input())
		b = list(map(int, input().split()))
		t = [''] * M
		S = sorted(list(S), reverse=True)
		d = Counter(S)
		start = 0
		ch = ''
		while t.count('') > 0:
			pos = []
			countZero = 0
			for i in range(M):
				if b[i] == 0 and t[i] == '':
					countZero += 1
			for i in range(start, len(S)):
				if d[S[i]] >= countZero and S[i] != ch:
					start = i
					ch = S[i]
					break
			for i in range(M):
				if b[i] == 0 and t[i] == '':
					t[i] = S[start]
					pos.append(i)
					d[S[start]] -= 1
					start += 1
			for i in range(M):
				if b[i] != 0:
					for j in pos:
						b[i] -= abs(i - j)
		print(''.join(t))
main()


def letter_to_ind(c):
	return ord(c) - ord('a')

def ind_to_letter(ind):
	return chr(ind + ord('a'))
N = int(input())
for q in range(N):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	count = [0 for i in range(26)]
	for x in s:
		count[letter_to_ind(x)] += 1
	ret = [None for i in range(len(b))]
	cur_ind = letter_to_ind('z')
	countb = len(b)
	while countb > 0:
		zeros = 0
		for x in b:
			if x == 0:
				zeros += 1
		ind = cur_ind
		while count[ind] < zeros:
			ind -= 1
		newb = [b[i] for i in range(len(b))]
		for i in range(len(b)):
			if b[i] == 0:
				newb[i] = -1
				ret[i] = ind_to_letter(ind)
				for j in range(len(b)):
					if newb[j] > 0:
						newb[j] -= max(i - j, j - i)
				countb -= 1
		b = newb
		cur_ind = ind - 1
	ret = ''.join(ret)
	print(ret)


from collections import *
import sys

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
t = ri()
for _ in range(t):
	s = sorted(input())
	m = ri()
	b = rl()
	cnt = Counter(s)
	t = ['0'] * m
	test = m
	while test > 0:
		cnt0 = Counter(b)
		letter = s[-1]
		while cnt[letter] < cnt0[0]:
			s = s[:len(s) - cnt[letter]]
			letter = s[-1]
		s = s[:len(s) - cnt[letter]]
		max_positions = []
		for j in range(m):
			if b[j] == 0:
				t[j] = letter
				max_positions.append(j)
		for j in range(m):
			if b[j] != 0:
				b[j] -= sum([abs(j - k) for k in max_positions])
			else:
				b[j] = -1
		test = test - cnt0[0]
	print(''.join(t))


from collections import defaultdict
letters = list(reversed([chr(x) for x in range(ord('a'), ord('z') + 1)]))
t = int(input())
for case in range(t):
	s = input()
	n = len(s)
	letter_count = defaultdict(int)
	for l in s:
		letter_count[l] += 1
	m = int(input())
	b = list(map(int, input().split()))
	visited = [0] * m
	counter = 0
	i = 0
	output = ['a'] * m
	while counter < m:
		zeros = []
		for j in range(m):
			if not visited[j] and b[j] == 0:
				visited[j] = 1
				zeros.append(j)
				counter += 1
		while i <= 26 and letter_count[letters[i]] < len(zeros):
			i += 1
		for j in zeros:
			output[j] = letters[i]
		for j in range(m):
			for k in zeros:
				b[j] -= abs(j - k)
		i += 1
	print(''.join(output))


from sys import stdin
input = stdin.readline
from collections import Counter, deque
for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	c = Counter(s)
	cs = deque(sorted(c)[::-1])
	ans = [''] * m
	while True:
		zeroID = []
		for (i, ele) in enumerate(b):
			if ele == 0:
				zeroID.append(i)
				b[i] = None
		if zeroID == []:
			break
		while cs:
			if c[cs[0]] >= len(zeroID):
				for i in zeroID:
					ans[i] = cs[0]
				cs.popleft()
				break
			cs.popleft()
		for i in range(len(b)):
			if b[i]:
				for j in zeroID:
					b[i] -= abs(i - j)
	print(''.join(ans))


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def main():
	for _ in range(int(input())):
		s = sorted(input())
		m = int(input())
		ans = ['' for i in range(m)]
		b = list(map(int, input().split()))
		freq = [0 for i in range(26)]
		for i in s:
			freq[ord(i) - ord('a')] += 1
		ind = []
		k = 25
		for i in range(m):
			if b[i] == 0:
				ind.append(i)
		z = m
		while z > 0:
			x = len(ind)
			while freq[k] < x:
				k -= 1
			for i in range(m):
				if b[i] == 0 and ans[i] == '':
					ans[i] = chr(ord('a') + k)
					z -= 1
			k -= 1
			nin = []
			for i in range(m):
				if b[i] != 0:
					for j in ind:
						b[i] -= abs(i - j)
					if b[i] == 0:
						nin.append(i)
			ind = nin.copy()
		print(''.join(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()


from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

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

def si():
	return input()

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def solve():
	for _ in range(ii()):
		s = si()
		m = ii()
		a = li()
		f = [0] * 26
		c = 'a'
		ans = ['0'] * m
		for i in s:
			f[bo(i)] += 1
		s = list(set(s))
		s.sort(reverse=True)
		x = []
		for i in range(m):
			if a[i] == 0:
				x.append(i)
				a[i] = -1
		c = 0
		n = len(s)
		for i in range(n):
			if f[bo(s[i])] >= len(x):
				for j in x:
					ans[j] = s[i]
				c = i + 1
				break
		while 1:
			x1 = [0] * m
			for i in range(m):
				for j in x:
					x1[i] += abs(i - j)
			x2 = []
			for i in range(m):
				if a[i] == x1[i]:
					x2.append(i)
					a[i] = -1
			for i in range(c, n):
				if f[bo(s[i])] >= len(x2):
					for j in x2:
						ans[j] = s[i]
						x.append(j)
					c = i + 1
					break
			if '0' not in ans:
				break
		print(''.join(ans))
solve()


from sys import stdin, stdout

def task_on_the_board(s, m, b):
	cha = [0 for i in range(26)]
	for c in s:
		cha[ord(c) - ord('a')] += 1
	k = 25
	res = [' ' for i in range(m)]
	cnt = 0
	prea = []
	while cnt != m:
		cura = []
		for i in range(len(b)):
			if res[i] == ' ' and b[i] == cal(prea, i):
				cura.append(i)
		while cha[k] < len(cura):
			k -= 1
		for i in cura:
			prea.append(i)
			res[i] = chr(97 + k)
		cnt += len(cura)
		k -= 1
	return res

def cal(prea, i):
	r = 0
	for p in prea:
		r += abs(p - i)
	return r
q = int(stdin.readline())
for i in range(q):
	s = stdin.readline().strip()
	m = int(stdin.readline())
	b = list(map(int, stdin.readline().split()))
	stdout.write(''.join(task_on_the_board(s, m, b)) + '\n')


T = int(input())
for _ in range(T):
	S = input()
	M = int(input())
	B = list(map(int, input().split()))
	Alpha = {}
	for elt in S:
		try:
			Alpha[elt] += 1
		except KeyError:
			Alpha[elt] = 1
	Alpha = list(Alpha.items())
	Alpha.sort(key=lambda x: x[0])
	ans = [None] * M
	Done = 0
	while Done < M:
		Zeros = []
		Count = 0
		for (i, elt) in enumerate(B):
			if elt == 0:
				Zeros += (i,)
				Count += 1
		toRemove = 0
		for (letter, count) in Alpha[::-1]:
			toRemove -= 1
			if count >= Count:
				for i in Zeros:
					ans[i] = letter
				Done += Count
				break
		del Alpha[toRemove:]
		for elt in Zeros:
			for i in range(len(B)):
				if i == elt:
					B[i] = -1
				else:
					B[i] -= abs(i - elt)
	print(''.join(ans))


def posx(lenb, i):
	ans = i * (i + 1) // 2
	r = lenb - i - 1
	ans += r * (r + 1) // 2

def solve1(b, lenb):
	ans = [-1 for i in range(lenb)]
	curnum = 0
	others = set(range(lenb))
	while len(others) > 0:
		indm = []
		for i in others:
			if b[i] == 0:
				indm.append(i)
		for el in indm:
			others.remove(el)
		for el in indm:
			ans[el] = curnum
			for ext in others:
				b[ext] -= abs(el - ext)
		curnum += 1
	ans = [curnum - i - 1 for i in ans]
	return ans

def sorter(l):
	dic = {}
	for el in l:
		if el in dic:
			dic[el] += 1
		else:
			dic[el] = 1
	val = list(dic.keys())
	val.sort()
	ls = [dic[i] for i in val]
	return (val, ls)

def solve2(ordt, s):
	(valt, lst) = sorter(ordt)
	(vals, lss) = sorter(s)
	indmap = [0 for i in range(len(lst))]
	j = 0
	for i in range(len(lst)):
		while lss[j] < lst[i]:
			j += 1
		indmap[i] = j
		j += 1
	ans = [vals[indmap[i]] for i in ordt]
	return ''.join(ans)
t = int(input())
for test in range(t):
	s = list(input())
	m = int(input())
	b = [int(i) for i in input().split()]
	ordt = solve1(b, m)
	print(solve2(ordt, s))


import sys
input = sys.stdin.readline
from collections import Counter as cc
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	s = list(input().strip())
	k = cc(s)
	(n,) = I()
	l = I()
	r = len(s) - n
	t = [''] * n
	p = sorted(k.keys(), reverse=True)
	ix = 0
	while max(l) >= 0:
		v = []
		for i in range(n):
			if l[i] == 0:
				v.append(i)
		while len(v) > k[p[ix]]:
			ix += 1
		for i in v:
			t[i] = p[ix]
			l[i] = -1
		for i in range(n):
			if l[i] != -1:
				for j in v:
					l[i] -= abs(i - j)
		ix += 1
	print(''.join(t))


for tt in range(int(input())):
	s = [i for i in input()]
	n = int(input())
	a = list(map(int, input().split()))
	cnt = [0] * 26
	for i in s:
		cnt[ord(i) - 97] += 1
	pq = []
	for i in range(26):
		if cnt[i] != 0:
			pq.append((chr(i + 97), cnt[i]))
	ans = [''] * n
	zCount = a.count(0)
	inds = []
	left = n
	while pq[-1][1] < zCount:
		pq.pop()
	for i in range(n):
		if a[i] == 0:
			left -= 1
			inds.append(i + 1)
			ans[i] = pq[-1][0]
	pq.pop()
	while left:
		check = []
		for i in range(n):
			if ans[i] != '':
				continue
			this = 0
			for j in inds:
				this += abs(j - (i + 1))
			if this == a[i]:
				check.append(i)
		while pq[-1][1] < len(check):
			pq.pop()
		for i in check:
			ans[i] = pq[-1][0]
			left -= 1
			inds.append(i + 1)
		pq.pop()
	print(''.join(ans))


t = int(input())
for tt in range(t):
	s = input()
	m = int(input())
	b = list(map(int, input().split(' ')))
	letters = [-1] * m
	lid = 0
	pos_of_all_bigger_elements = []

	def b_expected(i):
		global pos_of_all_bigger_elements
		q = 0
		for apos in pos_of_all_bigger_elements:
			q += abs(apos - i)
		return q

	def is_complete():
		global letters
		for x in letters:
			if x == -1:
				return False
		return True
	while True:
		new_pos = []
		for i in range(m):
			if letters[i] != -1:
				continue
			if b_expected(i) == b[i]:
				letters[i] = lid
				new_pos.append(i)
		pos_of_all_bigger_elements.extend(new_pos)
		lid += 1
		if is_complete():
			break
	lid_max = int(lid)
	position_of = []
	for i in range(lid):
		position_of.append([])
	for i in range(len(letters)):
		position_of[letters[i]].append(i)
	gvn_ltrs = []
	for x in s:
		gvn_ltrs.append(x)
	gvn_ltrs.sort()
	gvn_ltrs.reverse()
	set_of_letters = sorted(list(set(gvn_ltrs)))
	set_of_letters.reverse()
	dict_of_letters = {}
	for x in set_of_letters:
		dict_of_letters[x] = 0
	for x in gvn_ltrs:
		dict_of_letters[x] += 1
	lid = 0
	for x in set_of_letters:
		if dict_of_letters[x] >= len(position_of[lid]):
			for i in range(len(letters)):
				if letters[i] == lid:
					letters[i] = x
			lid += 1
			if lid == lid_max:
				break
	ans = ''
	for i in range(len(letters)):
		ans += letters[i]
	print(ans)


import sys
input = sys.stdin.readline
from math import ceil, floor, factorial

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(10000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	s = input().strip()
	n = int(input())
	a = int_array()
	z_count = 0
	order = []
	elivs = []
	while z_count != n:
		this = []
		for i in range(n):
			if a[i] == 0:
				z_count += 1
				a[i] = -1
				this.append(i)
		elivs.append(this)
		for i in range(n):
			if a[i] > 0:
				for j in this:
					a[i] -= abs(i - j)
	alps = sorted(list(set(list(s))))
	dick = {i: s.count(i) for i in alps}
	ans = [''] * n
	for i in elivs:
		while len(i) > dick.get(alps[-1], 0):
			alps.pop()
		for j in i:
			ans[j] = alps[-1]
		alps.pop()
	print(''.join(ans))


import sys
import math as mt
t = int(input())
for __ in range(t):
	s = input()
	l = [0] * 27
	for i in range(len(s)):
		l[ord(s[i]) - 97] += 1
	m = int(input())
	b = list(map(int, input().split()))
	ans = [-1] * m
	cnt = 0
	for i in range(m):
		if b[i] == 0:
			cnt += 1
	for i in range(26, -1, -1):
		if l[i] >= cnt:
			ind = i
			break
	cnt1 = 0
	for i in range(m):
		if b[i] == 0:
			ans[i] = chr(ind + 97)
			cnt1 += 1
	while cnt1 < m:
		index = []
		for i in range(m):
			ch = 0
			if ans[i] == -1:
				for j in range(m):
					if ans[j] != -1:
						ch += abs(i - j)
				if b[i] == ch:
					index.append(i)
		for j in range(ind - 1, -1, -1):
			if l[j] >= len(index):
				ind1 = j
				break
		ind = ind1
		for i in index:
			ans[i] = chr(ind + 97)
			cnt1 += 1
	print(*ans, sep='')


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')
testcases = int(input())
for j in range(testcases):
	list1 = [ord(k) for k in input()]
	list1.sort()
	real = [list1[0]]
	reps = [1]
	for s in range(1, len(list1)):
		if list1[s] == real[-1]:
			reps[len(real) - 1] += 1
		else:
			real.append(list1[s])
			reps.append(1)
	m = int(input())
	vals = list(map(int, input().split()))
	outy = [0] * len(vals)
	n = len(vals)
	for s in range(len(real)):
		zeros = []
		for b in range(n):
			if vals[b] == 0:
				zeros.append(b)
				vals[b] = 'x'
		maxsofar = -1
		for b in range(len(real) - 1, -1, -1):
			if reps[b] >= len(zeros):
				maxsofar = real.pop()
				reps.pop()
				break
			else:
				real.pop()
				reps.pop()
		if maxsofar > -1:
			for b in range(len(zeros)):
				outy[zeros[b]] = maxsofar
		for b in range(len(zeros)):
			ind = zeros[b]
			for i in range(n):
				if vals[i] != 'x':
					if vals[i] > 0:
						vals[i] -= abs(ind - i)
	outy = [chr(k) for k in outy]
	print(''.join(outy))


for _ in range(int(input())):
	s = input()
	m = int(input())
	b = list(map(int, input().split()))
	alph = [0] * 26
	n = len(s)
	ans = [''] * m
	for i in range(n):
		alph[ord(s[i]) - 97] += 1
	ind = 25
	while b.count(0) != 0:
		zero = b.count(0)
		while True:
			if alph[ind] >= zero:
				alph[ind] = 0
				break
			ind -= 1
		cur = []
		for i in range(m):
			if b[i] == 0:
				ans[i] = chr(97 + ind)
				cur.append(i)
				b[i] = -1
		for i in range(m):
			if b[i] != -1:
				for j in cur:
					b[i] -= abs(i - j)
	print(''.join(ans))


import sys
import collections
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		S = input().strip()
		M = int(input())
		B = [int(x) for x in input().split()]
		c = collections.Counter(S)
		ans = [''] * M
		ans_rank = [-1] * M
		current = 0
		while sum(B) != -M:
			zero = []
			for i in range(M):
				if B[i] == 0:
					zero.append(i + 1)
					B[i] = -1
					ans_rank[i] = current
			current += 1
			for i in range(M):
				if B[i] == -1:
					continue
				for z in zero:
					B[i] -= abs(i + 1 - z)
		for i in range(M):
			if ans_rank[i] == -1:
				ans_rank[i] = current
		c_rank = collections.Counter(ans_rank)
		ma = max(ans_rank)
		c_s = 26
		for i in range(ma + 1):
			ccr = c_rank[i]
			while c[chr(ord('a') + c_s)] < ccr:
				c_s -= 1
			for j in range(M):
				if ans_rank[j] == i:
					ans[j] = chr(ord('a') + c_s)
			c_s -= 1
		print(''.join(ans))
main()


from collections import Counter
q = int(input())
for _ in range(q):
	s = sorted(Counter(input()).items(), reverse=True)
	m = int(input())
	b = list(map(int, input().split()))
	idx = 0
	ans = [''] * m
	k = [0] * m
	while 1:
		cnt = 0
		f = 1
		for i in range(m):
			if k[i] == 0 and b[i] == 0:
				k[i] = 1
				cnt += 1
				f = 0
		if f:
			break
		while s[idx][1] < cnt:
			idx += 1
		for i in range(m):
			if k[i] == 1:
				k[i] = 2
				ans[i] = s[idx][0]
				for j in range(i + 1, m):
					if k[j] == 0:
						b[j] -= j - i
				for j in range(i):
					if k[j] == 0:
						b[j] -= i - j
		idx += 1
	print(''.join(ans))


import sys
import math
input = sys.stdin.readline
from functools import cmp_to_key

def pi():
	return int(input())

def pl():
	return int(input(), 16)

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

def ts():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
mod = 1000000007
f = []

def fact(n, m):
	global f
	f = [1 for i in range(n + 1)]
	f[0] = 1
	for i in range(1, n + 1):
		f[i] = f[i - 1] * i % m

def fast_mod_exp(a, b, m):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b = b >> 1
	return res

def inverseMod(n, m):
	return fast_mod_exp(n, m - 2, m)

def ncr(n, r, m):
	if r == 0:
		return 1
	return f[n] * inverseMod(f[n - r], m) % m * inverseMod(f[r], m) % m

def main():
	D()

def dfs(root, v, sub, parent):
	st = [root]
	while len(st) > 0:
		node = st.pop()
		for i in range(len(v[node])):
			if v[node][i] != node:
				st.append(v[node][i])

def X():
	try:
		t = pi()
		while t:
			t -= 1
			n = pi()
			v = [[] for i in range(n)]
			for i in range(n - 1):
				[x, y] = ti()
				v[x - 1].append(y - 1)
				v[y - 1].append(x - 1)
			m = pi()
			p = ti()
			e = [0 for i in range(n - 1)]
			sub = [0 for i in range(n)]
			dfs(0, v, sub, -1)
			for i in range(1, n):
				e[i - 1] = sub[i] * (n - sub[i])
			if len(p) < n - 1:
				while len(p) < n - 1:
					p.append(1)
			p = sorted(p)
			if len(p) > n - 1:
				x = 1
				for i in range(n - 2, len(p)):
					x = x * p[i]
				while len(p) > n - 2:
					p.pop()
				p.append(x)
			e = sorted(e)
			res = 0
			for i in range(n - 1):
				res = (res + p[i] * e[i]) % mod
			print(res)
	except:
		print(sys.exc_info())

def cmp(a, b):
	if a > b:
		return -1
	if a < b:
		return 1
	return 0

def cmpObj(a, b):
	if a[1] > b[1]:
		return 1
	if a[1] < b[1]:
		return -1
	return 0

def setCounts(b, index):
	for i in range(index, -1, -1):
		if b[i] != 0:
			b[i] -= index - i
	for i in range(index, len(b)):
		if b[i] != 0:
			b[i] -= i - index

def D():
	q = pi()
	while q:
		q -= 1
		(s, m, b) = (ts(), pi(), ti())
		s = sorted(s, key=cmp_to_key(cmp))
		bp = [[] for i in range(m)]
		for i in range(m):
			bp[i] = [i, b[i]]
		count = [0 for i in range(26)]
		for i in range(len(s)):
			count[ord(s[i]) - ord('a')] += 1
		t = ['' for i in range(m)]
		res = 0
		p = 0
		while res < m:
			z = 0
			for i in range(m):
				if b[i] == 0:
					z += 1
			while p < len(s) and count[ord(s[p]) - ord('a')] < z:
				p += 1
			indexes = []
			for i in range(m):
				if b[i] == 0 and p < len(s):
					b[i] = -1
					t[i] = s[p]
					p += 1
					indexes.append(i)
					res += 1
			while p < len(s) - 1 and s[p] == s[p - 1]:
				p += 1
			for i in range(len(indexes)):
				setCounts(b, indexes[i])
		print(*t, sep='')
main()


def checker(s, brr):
	temp = [0 for i in range(len(s))]
	for i in range(len(s)):
		for j in range(len(s)):
			if s[j] > s[i]:
				temp[i] += abs(j - i)
	print(temp)
	print(brr)
for _ in range(int(input())):
	arr = list(map(str, input()))
	m = int(input())
	brr = list(map(int, input().split()))
	col = brr[:]
	vis = [False for i in range(m)]
	ans = ['' for i in range(m)]
	mp = [0 for i in range(26)]
	all_visited = 0
	for i in arr:
		x = ord(i) - ord('a')
		mp[x] += 1
	q = []
	for i in range(m):
		if brr[i] == 0:
			q.append(i)
	prev = 30
	while True:
		start = -1
		x = len(q)
		for i in range(26):
			if x <= mp[i] and i < prev:
				start = max(start, i)
		mp[start] = 0
		prev = start
		start = chr(97 + start)
		for i in q:
			ans[i] = start
			brr[i] = 0
			vis[i] = True
			all_visited += 1
		for i in q:
			cnt = 1
			for j in range(i + 1, len(brr)):
				if vis[j] == False:
					brr[j] -= cnt
				cnt += 1
			cnt = 1
			for j in range(i - 1, -1, -1):
				if vis[j] == False:
					brr[j] -= cnt
				cnt += 1
		q = []
		for i in range(len(brr)):
			if brr[i] == 0 and vis[i] == False:
				q.append(i)
		if all_visited == m:
			break
	p = ''
	for i in ans:
		p += i
	print(p)


from sys import stdin
for case in range(int(stdin.readline())):
	s = sorted(list(stdin.readline().strip()))
	m = int(stdin.readline())
	d = [int(x) for x in stdin.readline().split()]
	sC = [1]
	stuff = [s[0]]
	for x in range(1, len(s)):
		if s[x] != s[x - 1]:
			sC.append(1)
			stuff.append(s[x])
		else:
			sC[-1] += 1
	visited = [False for x in d]
	inds = []
	newS = [-1 for x in d]
	for x in range(len(sC)):
		newInds = []
		for y in range(len(d)):
			if not visited[y]:
				totalD = 0
				for z in inds:
					totalD += abs(z - y)
				if d[y] == totalD:
					visited[y] = True
					newInds.append(y)
					newS[y] = x
		inds += newInds
	nsC = [0 for x in range(max(newS) + 1)]
	for x in newS:
		nsC[x] += 1
	sC.reverse()
	stuff.reverse()
	d = {}
	scInd = 0
	for (i, x) in enumerate(nsC):
		while True:
			if sC[scInd] >= x:
				d[i] = stuff[scInd]
				scInd += 1
				break
			scInd += 1
	streeng = ''
	for x in newS:
		streeng += d[x]
	print(streeng)


for _ in range(int(input())):
	s = input()
	n = int(input())
	arr = list(map(int, input().split()))
	qu = list((0 for _ in range(30)))
	for i in s:
		qu[ord(i) - ord('a')] += 1
	ind = 29
	ans = list(('0' for i in range(len(arr))))
	pop = 0
	while pop != len(arr):
		k = 0
		for i in arr:
			if i == 0:
				k += 1
		for i in range(ind, -1, -1):
			if qu[i] >= k:
				ind = i
				break
		kek = list()
		for i in range(len(arr)):
			if arr[i] == 0:
				arr[i] = -1
				ans[i] = chr(ind + ord('a'))
				pop += 1
				kek.append(i)
		for j in range(len(arr)):
			if arr[j] != 0:
				for i in kek:
					arr[j] -= abs(i - j)
		ind -= 1
	print(*ans, sep='')


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(S, M, B):
	wc = collections.Counter(S)
	S = list(sorted(set(S), reverse=True))
	C = ['' for _ in range(M)]
	si = 0
	while True:
		fill = [i for i in range(M) if B[i] == 0]
		if not fill:
			break
		while wc[S[si]] < len(fill):
			si += 1
		for i in fill:
			C[i] = S[si]
			B[i] = -1
		for i in range(M):
			B[i] -= sum([abs(i - j) for j in fill])
		si += 1
	return ''.join(C)
T = int(input())
ans = []
for ti in range(T):
	S = list(input())
	M = int(input())
	B = [int(x) for x in input().split()]
	ans.append(solve(S, M, B))
print('\n'.join(ans))


import string
q = int(input())
for case in range(q):
	s = input()
	freq = dict()
	for c in s:
		if c not in freq:
			freq[c] = 1
		else:
			freq[c] = freq[c] + 1
	m = int(input())
	t = [0] * m
	remain = m
	al = list(string.ascii_lowercase)
	highest = 25
	b = list(map(int, input().split(' ')))
	while remain > 0:
		zero_index = []
		for i in range(m):
			if b[i] == 0:
				zero_index.append(i)
				b[i] = -1
		for i in range(m):
			if b[i] != -1:
				for zero in zero_index:
					b[i] -= abs(i - zero)
		length = len(zero_index)
		remain -= length
		for c in range(highest, -1, -1):
			if al[c] in freq and freq[al[c]] >= length:
				highest = c - 1
				for zero in zero_index:
					t[zero] = al[c]
				break
	print(''.join(t))


import sys
input = sys.stdin.readline
RI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
rw = lambda : input().strip().split()
from collections import defaultdict as df
t = int(input().strip())
for _ in range(t):
	l = list(input().strip())
	d = df(int)
	for i in l:
		d[i] += 1
	m = int(input().strip())
	b = RI()
	t = [0] * m
	cur = 'z'
	done = df(int)
	for i in range(50):
		temp = []
		cnt = 0
		for j in range(m):
			if b[j] == 0 and done[j] == 0:
				temp.append(j)
				cnt += 1
		while d[cur] < cnt:
			cur = chr(ord(cur) - 1)
		for j in temp:
			t[j] = cur
			done[j] = 1
		for j in range(m):
			if done[j] == 0:
				for k in temp:
					b[j] -= abs(j - k)
		cur = chr(ord(cur) - 1)
	print(''.join(t))


a1 = 'abcdefghijklmnopqrstuvwxyz'
d = {}
ka = {}
k = 0
for i in a1:
	d[i] = k
	k += 1
k = 0
i = 0
while k <= 25:
	ka[k] = a1[i]
	k += 1
	i += 1
for _ in range(int(input())):
	s = input()
	n = int(input())
	a = list(map(int, input().split()))
	c = [0] * 26
	b = ['*'] * n
	for i in s:
		c[d[i]] += 1
	ch = 25
	while 1:
		z = []
		for i in range(len(a)):
			if a[i] == 0:
				z.append(i)
				a[i] = -1
		if len(z) == 0:
			break
		while ch >= 0 and c[ch] < len(z):
			ch -= 1
		for i in z:
			b[i] = ka[ch]
		for i in range(n):
			if b[i] == '*':
				for pos in z:
					a[i] -= abs(pos - i)
		ch -= 1
	print(''.join(b))


from collections import Counter
from string import ascii_lowercase as lt
for _ in range(int(input())):
	cou = Counter(input())
	m = int(input())
	arr = list(map(int, input().split()))
	lst = [0] * m
	j = 25
	tot = m
	while tot:
		x = 0
		for ind in range(m):
			if lst[ind] != 0:
				continue
			ans = 0
			for (ind1, val1) in enumerate(lst):
				if val1 != 0 and val1 != 1:
					ans += abs(ind1 - ind)
			if ans == arr[ind]:
				lst[ind] = 1
				x += 1
				tot -= 1
		while cou[lt[j]] < x:
			j -= 1
		for i in range(m):
			if lst[i] == 1:
				lst[i] = lt[j]
		j -= 1
	print(''.join(lst))


q = int(input())

def helper(inputS, m, inputB):
	s = inputS.copy()
	b = inputB.copy()
	processed = set()
	result = [-1 for x in b]
	while -1 in result:
		indices = [i for i in range(m) if b[i] == 0 and i not in processed]
		numZeros = len(indices)
		while len(set(s[-numZeros:])) != 1:
			s.pop()
		usedLetter = s[-1]
		for idx in indices:
			result[idx] = s[-1]
			s.pop()
			for j in reversed(range(idx)):
				if b[j] != 0:
					b[j] -= abs(idx - j)
			for j in range(idx + 1, m):
				if b[j] != 0:
					b[j] -= abs(idx - j)
			processed.add(idx)
		curIndex = len(s) - 1
		while curIndex >= 0 and s[curIndex] == usedLetter:
			s.pop()
			curIndex -= 1
	return ''.join(result)
for _ in range(q):
	s = list(input())
	m = int(input())
	b = [int(x) for x in input().split()]
	s.sort()
	result = helper(s, m, b)
	print(result)


from sys import stdin
from math import inf
from functools import reduce
from collections import defaultdict, Counter
input = stdin.readline
put = lambda : list(map(int, input().split()))
mod = int(1000000000.0 + 7)
(q,) = put()
for _ in range(q):
	t = input().strip()
	s = Counter(list(t))
	t = sorted(list(set(t)))
	(n,) = put()
	ans = [''] * n
	l = put()
	while sum(l) != -n:
		c = t.pop()
		m = l.count(0)
		r = []
		for i in range(n):
			if l[i] == 0:
				r.append(i)
		while s[c] < m:
			c = t.pop()
		for i in r:
			l[i] = -1
			ans[i] = c
		for i in range(n):
			for j in r:
				if l[i] > 0:
					l[i] -= abs(i - j)
	print(''.join(ans))


for _ in range(int(input())):
	f = [0] * 26
	s = input().strip()
	m = int(input())
	b = list(map(int, input().split()))
	for i in s:
		f[ord(i) - 97] += 1
	n = len(s)
	ans = ['.'] * m
	c = 122
	while 1:
		z = []
		for i in range(0, m):
			if b[i] == 0:
				z.append(i)
		if len(z) == 0:
			break
		while f[c - 97] < len(z) and c >= 97:
			c -= 1
		for i in z:
			ans[i] = chr(c)
			b[i] = -1
		for i in range(0, m):
			if ans[i] == '.':
				for j in z:
					b[i] -= abs(i - j)
		c -= 1
	print(''.join((str(a) for a in ans)))


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(l()[0]):
	s = input()
	m = l()[0]
	b = l()
	s = list(s)
	s.sort()
	n = len(s)
	A = ['.' for i in range(m)]
	while '.' in A:
		temp = []
		while b.count(0) > s.count(s[-1]):
			del s[-1]
		while s.count(s[-1]) > b.count(0):
			del s[-1]
		for i in range(m):
			if b[i] == 0:
				A[i] = s[-1]
				del s[-1]
				b[i] = -1
				temp.append(i)
		for i in range(m):
			if i not in temp and b[i] > 0:
				for ele in temp:
					b[i] -= abs(i - ele)
	print(''.join(A))


from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	s = list(input())
	n = int(input())
	ar = list(map(int, input().split()))
	s.sort()
	h = [0] * 26
	for i in range(len(s)):
		h[ord(s[i]) - 97] += 1
	ans = [''] * n
	p = 25
	for i in range(n):
		c = ar.count(0)
		if c > 0:
			cr = ''
			for j in range(p, -1, -1):
				if h[j] >= c:
					cr = chr(j + 97)
					p = j - 1
					break
			for j in range(n):
				if ar[j] == 0:
					ans[j] = cr
			ind = []
			for j in range(n):
				if ar[j] == 0:
					ind.append(j)
			for j in range(n):
				if ar[j] > 0:
					for k in range(len(ind)):
						ar[j] -= abs(ind[k] - j)
			for j in range(n):
				if ans[j] != '':
					ar[j] = -1
	print(''.join(ans))


def fill(ans, s, arr, n):
	if s == []:
		for i in ans:
			if i == -1:
				return '-1'
		return ''.join(ans)
	i = s[0]
	for j in range(n):
		if ans[j] != -1:
			continue
		chk = 0
		for k in range(n):
			if k != j and ans[k] != -1 and (ans[k] > i):
				chk += abs(k - j)
		if chk == arr[j]:
			ans[j] = i
			x = fill(ans, s[1:], arr, n)
			if x == '-1':
				ans[j] = -1
			else:
				return x
	return fill(ans, s[1:], arr, n)
t = int(input())
for i in range(t):
	s = list(input())
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [-1] * n
	s = sorted(s, reverse=True)
	ans = fill(ans, s, arr, n)
	print(ans)


A = ord('a')

def main():
	s = input()
	m = int(input())
	b = []
	for obj in input().split():
		b.append(int(obj))
	d = [0] * 26
	for char in s:
		d[ord(char) - A] += 1
	count_0 = m
	x = 25
	ans = ['-'] * m
	while count_0 != 0:
		a = []
		for i in range(m):
			if b[i] == 0:
				b[i] = -1
				a.append(i)
		L = len(a)
		while L > d[x]:
			x -= 1
		char = chr(x + A)
		for i in a:
			ans[i] = char
		for i in range(m):
			if b[i] == -1:
				continue
			sum_l = 0
			for num in a:
				sum_l += abs(num - i)
			b[i] -= sum_l
		count_0 -= L
		x -= 1
	print(*ans, sep='')
q = int(input())
for _ in range(q):
	main()


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	s = list(sys.stdin.readline().strip())
	m = int(sys.stdin.readline())
	b = list(map(int, sys.stdin.readline().split()))
	result = ['0'] * m
	list_count = [0] * 26
	for l in s:
		list_count[ord(l) - 97] += 1
	a = 25
	while True:
		list_zero = []
		numz = 0
		for i in range(m):
			if b[i] == 0:
				list_zero.append(i)
				numz += 1
		if not numz:
			break
		for a in range(a, -1, -1):
			if list_count[a] >= numz:
				list_count[a] = 0
				break
		word = chr(97 + a)
		for i in range(m):
			if b[i] > 0:
				for j in list_zero:
					b[i] -= abs(i - j)
		for i in list_zero:
			result[i] = word
			b[i] = -1
	print(''.join(result))


t = int(input())
from collections import Counter

def countZeros(arr):
	toReturn = []
	for i in range(len(arr)):
		if arr[i] == 0:
			toReturn.append(i)
	return toReturn
for _ in range(t):
	s = [var for var in input()]
	m = int(input())
	b = [int(var) for var in input().split()]
	(newS, toPrint) = ([], [0 for _ in range(m)])
	for (char, freq) in Counter(s).items():
		newS.append([char, freq])
	newS.sort(key=lambda x: x[0])
	zeros = countZeros(b)
	while len(zeros) != 0 and len(newS) != 0:
		if len(zeros) <= newS[-1][-1]:
			for idx in range(m):
				if b[idx] == 0:
					b[idx] = newS[-1][0]
				elif type(b[idx]) == int:
					for zeroIdx in zeros:
						b[idx] -= abs(idx - zeroIdx)
			zeros = countZeros(b)
		newS.pop()
	cnt = 0
	for var in b:
		if type(var) == int:
			cnt += 1
	if cnt == 0:
		print(''.join(b))
	else:
		print(-1)


T = int(input())
while T > 0:
	s = input()
	m = int(input())
	arr = list(map(int, input().split()))
	count = [0] * 26
	for i in range(len(s)):
		count[ord(s[i]) - ord('a')] += 1
	index = 25
	res = ['0'] * m
	queue = []
	for i in range(m):
		if arr[i] == 0:
			queue.append(i)
	while queue:
		le = len(queue)
		while count[index] < le:
			index -= 1
		ch = chr(ord('a') + index)
		index -= 1
		while le > 0:
			le -= 1
			tmp = queue.pop(0)
			res[tmp] = ch
			dis = 1
			while tmp - dis >= 0 or tmp + dis < m:
				if tmp - dis >= 0:
					arr[tmp - dis] -= dis
					if arr[tmp - dis] == 0:
						queue.append(tmp - dis)
				if tmp + dis < m:
					arr[tmp + dis] -= dis
					if arr[tmp + dis] == 0:
						queue.append(tmp + dis)
				dis += 1
	print(''.join(res))
	T -= 1


import sys
read = lambda : sys.stdin.readline()
T = int(read())
for t in range(T):
	s = read()
	m = int(read())
	b = list(map(int, read().split()))
	s = sorted(s, reverse=True)
	result = [None for i in range(m)]
	si = 0
	while True:
		indx = []
		num0 = 0
		for i in range(m):
			if result[i] == None and b[i] == 0:
				indx.append(i)
				num0 += 1
		if num0 == 0:
			break
		while s[si:].count(s[si]) < num0:
			si += s[si:].count(s[si])
		for i in indx:
			result[i] = s[si]
		for i in range(m):
			if result[i] == None:
				for j in indx:
					b[i] -= abs(i - j)
		si += s[si:].count(s[si])
	print(''.join(result))


import os
inp = os.read(0, int(10000000.0)).split()
inp_pos = -1

def cin():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos]
T = int(cin())
res = []
while T:
	T -= 1
	s = sorted(list(cin().decode()))
	n = int(cin())
	a = [int(cin()) for i in range(n)]
	while a.count(0) and s:
		while s and s.count(s[-1]) < a.count(0):
			cur = s[-1]
			while s and s[-1] == cur:
				s.pop()
		if s:
			cur = s[-1]
			a = [cur if x == 0 else x for x in a]
			while s and s[-1] == cur:
				s.pop()
			for j in range(n):
				if not str(a[j]).isalpha():
					for i in range(n):
						if a[i] == cur:
							a[j] -= abs(i - j)
	res.append(''.join(a).encode())
os.write(1, '\n'.encode().join(res))


import sys
input = sys.stdin.readline
from collections import Counter
for _ in range(int(input())):
	s = input().rstrip()
	m = int(input())
	B = list(map(int, input().split()))
	t = [None] * m
	used = []
	have = sorted(Counter(s).items(), reverse=True)
	I = 0
	free = m
	while free:
		need = []
		for i in range(m):
			if t[i] is None:
				diff = 0
				for j in used:
					diff += abs(i - j)
				if diff == B[i]:
					need.append(i)
		while have[I][1] < len(need):
			I += 1
		for i in need:
			t[i] = have[I][0]
			used.append(i)
		I += 1
		free -= len(need)
	assert all((v is not None for v in t))
	print(''.join(t))


T = int(input())
for _ in range(T):
	a = [0] * 26
	for i in input().strip():
		a[ord(i) - ord('a')] += 1
	n = int(input())
	b = list(map(int, input().split()))
	s = [-1] * n
	x = 26
	while s.count(-1) > 0:
		(x, y) = (x - 1, b.count(0))
		while a[x] < y:
			x -= 1
		for i in range(n):
			if b[i] == 0:
				s[i] = x
		for i in range(n):
			if s[i] == x:
				b[i] = -1
				for j in range(n):
					if b[j] > 0:
						b[j] -= abs(i - j)
	print(''.join((chr(i + ord('a')) for i in s)))


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

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

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	os = list(input())
	s = sorted(set(os))
	m = iinput()
	a = rlinput()
	visited = [False] * m
	ans = [''] * m
	while not all(visited):
		zero = []
		for i in range(m):
			if a[i] == 0 and (not visited[i]):
				zero.append(i)
				visited[i] = True
		while True:
			large = s.pop()
			if len(zero) <= os.count(large):
				for i in zero:
					ans[i] = large
				break
		for i in zero:
			for j in range(m):
				if not visited[j]:
					a[j] -= abs(i - j)
	print(''.join(ans))


from collections import defaultdict
t = int(input())
for i in range(t):
	s = input()
	n = int(input())
	b = list(map(int, input().split()))
	groups = []
	while True:
		pos = []
		for i in range(n):
			if b[i] == 0:
				pos.append(i)
		if pos == []:
			break
		groups.append(pos)
		for i in range(n):
			if b[i] == 0:
				b[i] = float('inf')
			else:
				for pp in pos:
					b[i] = b[i] - abs(i - pp)
	cnt = defaultdict(int)
	for i in s:
		cnt[i] += 1
	ans = ['?' for i in range(n)]
	keys = sorted(cnt, reverse=True)
	j = 0
	for g in groups:
		while cnt[keys[j]] < len(g):
			j += 1
		for pp in g:
			ans[pp] = keys[j]
		j += 1
	print(''.join(ans))