Sereja and Number Division 2

All submissions for this problem are available.
Read problems statements in Mandarin Chinese and Russian.
Sereja has an integer number A that doesn't contain zeroes in its decimal form.
Also he has N integers B[1], B[2], ..., B[N].
Let us first define function f for a number A as follows.
.
Now he has to reorder the digits of A such that f(A) is minimum.
Please help him in finding most optimal A.
Input
 First line contain a single integer T denoting number of test cases. Then T tests follow.
 First line of each test case contains an integer A.
 Next line contains an integer N.
 Next line contains N integers B[1], B[2], ..., B[N].
Output
For each test case, output optimal value of A after reordering digits in a single line.
Constraints
Example
Input: 2 123 2 2 3 123457 1 10 Output: 312 754312
Scoring
Let Y denotes your score for the problem. Y is defined as sum of f(optimal A)) for all test cases.
You objective is to make Y as small as possible.
Tests generation Plan
Test set contains five official test cases.
During the contest, your solution will be tested only on the first test. After the end of contest, it will be rejudged on the full test set.
Length of number A is generated randomly. All digits of it are also chosen randomly.
In all test cases N is equal to 100.
To generate array B, first we chose an integer R between 1 and 10^{6} inclusive. Note that R is
not randomly generated, it will be manually selected.
Then all elements of array B are chosen in range 1..R randomly.
Author:  sereja 
Tester:  shiplu 
Editorial  http://discuss.codechef.com/problems/SEAND2 
Tags  challenge, jan15, sereja 
Date Added:  10092014 
Time Limit:  5 sec 
Source Limit:  50000 Bytes 
Languages:  C, CPP14, JAVA, PYTH, PYTH 3.5, PYPY, CS2, PAS fpc, PAS gpc, RUBY, PHP, GO, NODEJS, HASK, SCALA, D, PERL, FORT, WSPC, ADA, CAML, ICK, BF, ASM, CLPS, PRLG, ICON, SCM qobi, PIKE, ST, NICE, LUA, BASH, NEM, LISP sbcl, LISP clisp, SCM guile, JS, ERL, TCL, PERL6, TEXT, SCM chicken, CLOJ, FS 
Comments
 Please login at the top to post a comment.
SUCCESSFUL SUBMISSIONS
Fetching successful submissions
HELP
If you are still having problems, see a sample solution here. 