We are to compute the maximum possible volume of a tetrahedron formed by selecting up to 6 sticks (edges) to form a tetrahedron's 6 edges. A tetrahedron has 6 edges: three edges from one vertex? Actually a tetrahedron is a triangular pyramid with 4 faces. It has 6 edges. The edges can be grouped into opposite edges (pairs that don't share a vertex) etc. But any set of six positive numbers can be the edge lengths of a tetrahedron if and only if they satisfy certain triangle inequalities for each face, and also the Cayley-Menger determinant >0. But here we have a set of sticks lengths; we can choose any 6 sticks (not necessarily distinct lengths) from the given N sticks (with N up to 15) to form the edges. And we can also choose fewer than 6? No, rule (1): he need not use all given sticks, but he must form a tetrahedral vessel. So he can select a subset of sticks (presumably exactly 6 sticks, because a tetrahedron has 6 edges). However rule (1) says "he need not use all of the given sticks", meaning he can choose a subset. But he cannot combine sticks to make longer edges, he must use each stick as an edge individually. So we need to select 6 sticks from the N to assign as the 6 edges of a tetrahedron. And we want to maximize the volume.
Given that N is at most 15, we can brute-force all subsets of 6 sticks (C(15,6)=5005, small). For each subset, we need to consider all possible permutations (assignments to edges) to see if they can form a valid tetrahedron and compute volume. However 6! = 720 permutations per subset, total combos: 5005 * 720 = ~3.6 million, which is fine. But we might be able to prune or use combinatorial enumeration with symmetry to reduce. But with N <= 15, 3.6 million is okay. However we also need to compute the volume via Cayley-Menger determinant: For tetrahedron with edges a,b,c,d,e,f, where usual labeling: suppose vertices A, B, C, D. Edges: AB = a, AC = b, AD = c, BC = d, BD = e, CD = f. Volume = sqrt( CM / 288 ), where CM is the Cayley-Menger determinant:
CM = |0 1 1 1 1|
|1 0 a^2 b^2 c^2|
|1 a^2 0 d^2 e^2|
|1 b^2 d^2 0 f^2|
|1 c^2 e^2 f^2 0|
But we can also compute using formula:
288 V^2 =
a^2 b^2 c^2
- a^2 e^2 f^2
- b^2 d^2 f^2
- c^2 d^2 e^2
- a^2 b^2 d^2
- a^2 c^2 e^2
- b^2 c^2 f^2
- d^2 e^2 f^2
- a^2 d^2 f^2? Wait I need the correct expression.
Actually the Cayley-Menger determinant for tetrahedron reduces to:
288 V^2 =
a^2 b^2 c^2
- a^2 e^2 f^2
- b^2 d^2 f^2
- c^2 d^2 e^2
- a^2 d^2 (a^2? No.
Let me derive properly. There is known formula by Tartaglia:
V^2 = (1/288) * |
0 1 1 1 1
1 0 a^2 b^2 c^2
1 a^2 0 d^2 e^2
1 b^2 d^2 0 f^2
1 c^2 e^2 f^2 0
|.
We can compute numerically.
Alternatively, we can compute using edge lengths via the Cayley-Menger determinant function.
Given that we have many permutations, we need a fast check for validity: For tetrahedron to be non-degenerate (positive volume), the Cayley-Menger determinant must be positive. Also triangle inequalities for each face must hold? Actually if the determinant is positive, then it's a valid tetrahedron (non-degenerate) and the triangle inequalities for faces are necessary but not sufficient? Actually for a set of six lengths to form a tetrahedron, they must satisfy that each face's triangle inequality holds (strictly, else volume zero) and also the strict positivity of the Cayley-Menger determinant. But in practice, checking determinant > epsilon is enough.
But we can also reduce computational complexity by noting that the volume depends on the assignment of edges to pairs. Because the tetrahedron has a specific structure: edges correspond to vertices. If we permute edges arbitrarily, the set of lengths assigned to the six edges must satisfy the constraints. Since the sticks are indistinguishable aside from length, we need to consider all assignments.
However, with 6 sticks, there may be duplicates, which reduces distinct permutations. But still worst-case 720.
But maybe we can use combinatorial assignment by considering the graph of tetrahedron. The tetrahedron is complete graph K4. Its edges can be labeled, but we can think of the six values. Since K4 is edge-transitive? Actually it's symmetric; any permutation of edges corresponds to a relabeling of vertices (automorphism group is S4 of order 24). However not all 720 permutations of edges correspond to relabelings of vertices; the automorphism group of K4 (the full symmetry group) is S4, which acts on the 6 edges with permutations. The number of distinct edge labelings up to vertex relabeling is 6! / 24 = 30. That means for a given multiset of 6 edge lengths, we only need to test 30 distinct assignments (representatives) because any permutation that results from vertex relabeling yields the same tetrahedron (just renaming vertices) and same volume. But careful: if we assign lengths to edges arbitrarily, relabeling vertices will produce a different assignment of lengths to specific positions, but the set of edge lengths is the same multiset; the volume depends only on which lengths are paired as opposite edges? Actually volume is invariant under renaming vertices because it's just a relabeling; the volume computed from the same multiset will be the same regardless of which lengths we call a,b,c,d,e,f as long as the mapping is consistent? Wait, if we have a set of six numbers and we assign them to edges arbitrarily, then we compute volume. If we apply a permutation to the labeling of vertices, the resulting assignment of numbers to the positions (a=AB, b=AC, c=AD, d=BC, e=BD, f=CD) will change, but the volume computed from the new assignment should be the same as the volume computed from the original assignment because it's the same geometric tetrahedron, just renamed vertices. However, is the volume formula symmetric under all permutations of the six lengths? No, the volume is not fully symmetric; different assignments of the same six lengths can yield different volumes or even invalidity because the combinatorial structure (which edges share a vertex) matters. For example, suppose we have six sticks: four long and two short. If we assign the two short sticks to be opposite edges, maybe that yields a degenerate shape? Actually, the volume depends on the actual arrangement. The same multiset can produce tetrahedra with different volumes when assigned differently. However, if we relabel vertices, that corresponds to a permutation of the six edge labels that preserves the incidence structure. That permutation is not arbitrary; it is from the automorphism group of K4, which has size 24. So for a given multiset, there may be up to 720/24=30 distinct tetrahedra (different edge-graph assignments) that are not equivalent under vertex relabeling. So we need to consider essentially all distinct ways to assign the six lengths to the six edges up to graph isomorphism. That is 30 possibilities.
But is it necessary to consider all 30? Since N is small, we could just iterate all 720 permutations and compute, ignoring duplicates. But computing 720 Cayley-Menger determinants per subset could be heavy but still okay. With 5005 subsets, that's 3.6 million determinants. Each determinant is 5x5, computed with double arithmetic; that's fine. However, we also need to compute sqrt for volume only if determinant > 0. So 3.6 million might be borderline but should be fine in C++ with optimization.
But there is nuance: N <= 15, but number of subsets of size exactly 6 is at most C(15,6)=5005. But the problem states "he need not use all of the given sticks", meaning he can use any subset of sticks, not necessarily exactly 6? Actually a tetrahedron requires exactly 6 edges, so he must use exactly 6 sticks (since each stick is an edge, cannot combine). So yes, choose exactly 6 sticks.
But what about using fewer than 6? Could he use 5 sticks? No, tetrahedron needs 6 edges. So must select 6 sticks.
Thus we just need to consider all subsets of size 6. For each subset, we consider all permutations of its elements assigned to edges, compute volume if valid, and track max.
But could there be a possibility to use more than 6 sticks? Possibly if some sticks are not used? But we must form a tetrahedron's frame. That uses exactly 6 edges. So we need exactly 6 sticks. So subset size must be 6. Yes.
Thus algorithm: For each test case, read N and array a[0..N-1]. Enumerate all combinations of 6 indices. For each combination, get list of 6 lengths. For each permutation of those 6 lengths (use next_permutation on sorted list?), compute Cayley-Menger determinant to check validity ( > 1e-12) and compute volume = sqrt( determinant / 288.0 ). Keep max.
But 3.6 million permutations with next_permutation may be okay. However we have to generate permutations for each combination, and for each we need to compute the determinant. 3.6 million determinants of 5x5 is about 3.6 million * (25 operations?) Actually computing determinant directly with hardcoded formula might be faster.
We can compute 288 V^2 directly using known formula for tetrahedron volume given six edges. There is a formula known as the "Cayley-Menger" simplified expression:
Let edges: AB = w, AC = v, AD = u, BC = z, BD = y, CD = x. Then:
Volume = sqrt(
( 4uuvvww
- uu(yy + zz - x*x)^2
- vv(xx + zz - y*y)^2
- ww(xx + yy - z*z)^2
- (uuvvzz + uuwwyy + vvwwxx + xxyyzz) ) / 12
? That seems messy.
Better to compute determinant.
But we can predefine indices for edges: For convenience, label vertices 0,1,2,3. Edges: between 0-1, 0-2, 0-3, 1-2, 1-3, 2-3. We'll assign lengths: l01, l02, l03, l12, l13, l23.
Then Cayley-Menger determinant D =
|0 1 1 1 1|
|1 0 l01^2 l02^2 l03^2|
|1 l01^2 0 l12^2 l13^2|
|1 l02^2 l12^2 0 l23^2|
|1 l03^2 l13^2 l23^2 0|
We can compute D using standard determinant algorithm or using formula:
D = - (l01^2 + l02^2 - l12^2)(l01^2 + l03^2 - l13^2)(l02^2 + l03^2 - l23^2) ... not.
Better to compute with linear algebra. Since it's a 5x5 symmetric matrix, we can compute determinant using Chio's condensation or use known expansion.
Alternatively, we can compute the volume using the formula derived from the determinant:
288 V^2 =
a^2 b^2 c^2
- a^2 (e^2 + f^2 - d^2)^2 / 2? Wait, I'm mixing.
I recall a formula:
Let U = a^2, V = b^2, W = c^2, X = d^2, Y = e^2, Z = f^2, where a = BC? Actually we need consistency.
Perhaps easier: Use function to compute determinant via expansion. 5x5 determinant is not too heavy. We can implement using double and using the standard method: compute using Gaussian elimination to upper triangular and multiply diagonal. But that might be slower and prone to numerical error if pivoting not used. However for small matrix and many calls, we can hardcode the determinant using the known expression.
There is a known expression for the Cayley-Menger determinant for tetrahedron:
Δ = a^2 b^2 c^2
- a^2 d^2 e^2
- b^2 d^2 f^2
- c^2 e^2 f^2
- a^2 b^2 d^2
- a^2 c^2 e^2
- b^2 c^2 f^2
- d^2 e^2 f^2
- a^2 f^2 (a^2?) Not.
Let me derive from scratch. The Cayley-Menger determinant for n=3 (tetrahedron) can be expressed as:
288 V^2 =
| 0 1 1 1 |
| 1 0 d12^2 d13^2 |
| 1 d12^2 0 d23^2 |
| 1 d13^2 d23^2 0 | for triangle? Actually that's for triangle area.
For tetrahedron we have 4 points; the determinant is 5x5.
After some research, there is formula:
288 V^2 =
a^2 b^2 c^2
- a^2 e^2 f^2
- b^2 d^2 f^2
- c^2 d^2 e^2
- a^2 d^2 (a^2? No.
Wait, I found online: For tetrahedron with edge lengths:
AB = p, AC = q, AD = r, BC = s, BD = t, CD = u.
Then volume V = (1/12) * sqrt(
4 p^2 q^2 r^2
- p^2 (s^2 + t^2 - u^2)^2
- q^2 (s^2 + u^2 - t^2)^2
- r^2 (t^2 + u^2 - s^2)^2
- (p^2 q^2 s^2 + p^2 r^2 t^2 + q^2 r^2 u^2 + s^2 t^2 u^2)
? Actually that looks plausible.
Check: There is known formula:
V = 1/12 * sqrt(
4 a^2 b^2 c^2
- a^2 (b^2 + c^2 - a'^2)^2? Not.
Better: Use the Cayley-Menger determinant:
Let M be:
[0, 1, 1, 1, 1]
[1, 0, d01^2, d02^2, d03^2]
[1, d01^2, 0, d12^2, d13^2]
[1, d02^2, d12^2, 0, d23^2]
[1, d03^2, d13^2, d23^2, 0]
We can compute determinant D = det(M). Then V = sqrt(D/288). So D must be positive.
We can compute D by expanding. The matrix has structure. There is known formula:
D = - ( (sum over edges squared products) - ... ) but it's messy.
Given we can compute D by performing Gaussian elimination for each candidate. 5x5 matrix, we can compute determinant via LU decomposition with partial pivoting. That's maybe 125 operations per determinant? Could be okay. 3.6 million * 125 = 450 million ops, maybe borderline but possible in optimized C++ if using double and simple loops. But we can try to reduce.
We can also reduce the number of permutations by using symmetry: For each combination, we can generate assignments up to vertex relabeling, i.e., 30 assignments. But that requires generating distinct assignments. Might be simpler to just generate all permutations, but we can avoid duplicates due to equal lengths using next_permutation on sorted array; it will generate each distinct permutation exactly once (if we sort and then use next_permutation, it will handle duplicates). However number of distinct permutations for a multiset can be less than 720, but worst-case all six distinct yields 720 distinct. So worst-case still 720. 5005 * 720 = 3.6 million. That's okay.
But is there any scenario where we need to consider subsets of sizes other than 6? Possibly if we can use less than 6 sticks by using some sticks as multiple edges? No, rule (2) says you must not glue sticks together to make longer sticks. So each edge is a single stick. So exactly 6 sticks.
Thus algorithm is straightforward.
However we must also consider that tetrahedron must be non-degenerate, i.e., volume > 0. The problem says "It is guaranteed that for each test case, at least one tetrahedral vessel can be formed." So at least one valid subset.
Now about output: Print maximum possible volume with arbitrary digits after decimal point as long as error <= 1e-6. So we can print with e.g., printf("%.10f") or similar.
Implementation details:
- Parse input lines until "0".
- For each test case:
- Read N then N integers.
- Enumerate combinations of 6 indices. Since N <= 15, we can use recursion or loops. Simpler: use next_combination function or nested loops for indices i0<i1<...<i5.
- For each combination, extract lengths into an array len[6].
- Sort len to facilitate next_permutation.
- Do while (next_permutation) to generate permutations. For each perm, assign to edges: a = perm[0], b = perm[1], c = perm[2], d = perm[3], e = perm[4], f = perm[5] (mapping to edges as we define). Then compute squared lengths: a2 = aa, b2 = bb, ... f2 = f*f.
- Compute the Cayley-Menger determinant D.
- If D > eps (say 1e-12), compute volume = sqrt(D/288.0). Keep max volume.
- Output max volume.
Now need to compute D accurately.
Let's derive a closed-form expression to avoid matrix ops.
We can compute D by expansion using known formula. I recall that for tetrahedron, the Cayley-Menger determinant can be expressed as:
D = - ( (a^2 f^2 (-a^2 + b^2 + c^2 - d^2 + e^2 + f^2) ... )? Not.
Better: Use formula from Wikipedia: For a tetrahedron, the volume V is given by:
288 V^2 =
| 0 1 1 1 1 |
| 1 0 d12^2 d13^2 d14^2 |
| 1 d12^2 0 d23^2 d24^2 |
| 1 d13^2 d23^2 0 d34^2 |
| 1 d14^2 d24^2 d34^2 0 |
One can expand.
I can try to derive a formula using variables.
Let denote squared lengths:
Let p = d12^2, q = d13^2, r = d14^2, s = d23^2, t = d24^2, u = d34^2.
Then the determinant D = det(M) where M is:
[0, 1, 1, 1, 1]
[1, 0, p, q, r]
[1, p, 0, s, t]
[1, q, s, 0, u]
[1, r, t, u, 0]
We can compute D using linear algebra.
One approach: Compute D = - (1/2) * det(2M')? Not.
I can compute D by subtracting first row/col to reduce to 4x4. But perhaps it's easier to code a small determinant function.
Define function det5(mat) that computes determinant of 5x5 matrix. Since it's symmetric and we know first row and column have 0 and 1s, we could do analytic simplification.
Let's attempt to simplify: Expand along first row? The matrix is:
Row0: [0, 1, 1, 1, 1]
Row1: [1, 0, p, q, r]
Row2: [1, p, 0, s, t]
Row3: [1, q, s, 0, u]
Row4: [1, r, t, u, 0]
We can compute D = determinant.
Let's do expansion using the first row. D = sum_{j=0..4} (-1)^{0+j} * M[0][j] * C_{0j}, where C_{0j} is cofactor.
But M[0][0]=0 so j=0 term zero. For j=1..4, M[0][j]=1. So D = (-1)^{0+1}1C01 + (-1)^{0+2}1C02 + (-1)^{0+3}1C03 + (-1)^{0+4}1C04 = -C01 + C02 - C03 + C04? Actually (-1)^{0+j} = (-1)^j. Since j starts at 1: (-1)^1 = -1, (-1)^2 = +1, (-1)^3 = -1, (-1)^4 = +1. So D = -C01 + C02 - C03 + C04, where C0j = determinant of submatrix obtained by removing row 0 and column j.
So we need compute four 4x4 determinants. Each submatrix is 4x4: For each j (1..4), we remove row0 and column j from M.
Let's define M rows 1..4 and columns 0..4 except column j.
Better to compute directly using known formula. I found formula on internet: For tetrahedron with edges (AB, AC, AD, BC, BD, CD) as (d01,d02,d03,d12,d13,d23) squared lengths (U,V,W,X,Y,Z). Then:
288 V^2 = U V W + U (Y + Z - X)^2 / 4 + V (X + Z - Y)^2 / 4 + W (X + Y - Z)^2 / 4 - (U V X + U W Y + V W Z + X Y Z) / 2
But this looks plausible. Let's verify with known formula for regular tetrahedron side length s: Volume = s^3 / (6√2). Then squared volume = s^6 / (72). For s=1, V^2=1/72? Actually V = sqrt(2)/12 ≈ 0.11785, squared = 2/144 = 1/72 ≈ 0.0138889. Then 288 V^2 = 288/72 = 4. So we need expression = 4. For regular tetrahedron, all edges = 1. So U=V=W=X=Y=Z=1^2=1. Plug into formula: U V W =1. Next term: U(Y+Z-X)^2/4 = 1*(1+1-1)^2/4 = (1)^2/4 = 1/4. Similarly V term: (1+1-1)^2/4 = 1/4. W term: 1/4. Sum so far = 1 + 0.75 = 1.75. Then subtract (U V X + U W Y + V W Z + X Y Z)/2 = (1+1+1+1)/2 = 4/2=2. So total = 1.75 - 2 = -0.25. That's not 4. So missing something. Perhaps sign or plus? Maybe it's:
288 V^2 = U V W + U (Y+Z-X)^2/4 + V (X+Z-Y)^2/4 + W (X+Y-Z)^2/4 - (U V X + U W Y + V W Z + X Y Z)/2 + (X Y Z)/? Hmm not.
Another formula:
V^2 = (1/288) * | 0 1 1 1 1; 1 0 d1^2 d2^2 d3^2; 1 d1^2 0 d4^2 d5^2; 1 d2^2 d4^2 0 d6^2; 1 d3^2 d5^2 d6^2 0 |.
Maybe we can compute determinant using expansion into sums of products. There is known formula:
Δ = -a^2 b^2 c^2 - a^2 d^2 e^2 - b^2 d^2 f^2 - c^2 e^2 f^2 + a^2 b^2 d^2 + a^2 c^2 e^2 + b^2 c^2 f^2 + d^2 e^2 f^2 + a^2 d^2 (a^2?) no.
I can compute D by performing Gaussian elimination for a 5x5 matrix, which is straightforward and likely fast enough. But we should be careful about precision. We can compute determinant via LU with partial pivoting.
Alternatively, we can compute D by using the formula for Cayley-Menger determinant expressed in terms of squared distances. I recall that the determinant can be computed as:
D = -1/2 * | 0 d01^2 d02^2 d03^2 1 |
| d01^2 0 d12^2 d13^2 1 |
| d02^2 d12^2 0 d23^2 1 |
| d03^2 d13^2 d23^2 0 1 |
| 1 1 1 1 0 |
But that's different ordering. Actually the Cayley-Menger matrix is usually bordered by ones.
But the standard form is as we have.
Given the small size, we could code determinant as:
double mat[5][5];
Initialize mat[0][0]=0; mat[0][1]=1; mat[0][2]=1; mat[0][3]=1; mat[0][4]=1;
mat[1][0]=1; mat[1][1]=0; mat[1][2]=a2; mat[1][3]=b2; mat[1][4]=c2;
mat[2][0]=1; mat[2][1]=a2; mat[2][2]=0; mat[2][3]=d2; mat[2][4]=e2;
mat[3][0]=1; mat[3][1]=b2; mat[3][2]=d2; mat[3][3]=0; mat[3][4]=f2;
mat[4][0]=1; mat[4][1]=c2; mat[4][2]=e2; mat[4][3]=f2; mat[4][4]=0;
Then compute determinant.
We can compute using row operations to upper triangular. But we need to be careful with zero pivots. Since the matrix is not necessarily positive definite, but we can use partial pivoting. However we can use a more stable method: use the standard formula for Cayley-Menger determinant which is known to be equivalent to:
D = ( (a2 + f2 - b2 - c2 - d2 - e2 + ...)? Not.
Given that we will compute many determinants, maybe it's better to derive an explicit polynomial expression.
I found a formula online (maybe from mathworld) for the Cayley-Menger determinant for tetrahedron:
|0 1 1 1 1|
|1 0 d12^2 d13^2 d14^2|
|1 d12^2 0 d23^2 d24^2|
|1 d13^2 d23^2 0 d34^2|
|1 d14^2 d24^2 d34^2 0| =
- (d12^2 d34^2 (-d12^2 + d13^2 + d14^2 + d23^2 + d24^2 - d34^2) + ...)?? Not.
Let's derive it manually using algebraic expansion.
Define squared distances: p = d12^2, q = d13^2, r = d14^2, s = d23^2, t = d24^2, u = d34^2.
Matrix M:
[0, 1, 1, 1, 1]
[1, 0, p, q, r]
[1, p, 0, s, t]
[1, q, s, 0, u]
[1, r, t, u, 0]
We want det(M).
We can subtract appropriate multiples of rows to simplify. However we can exploit the structure: The matrix is of the form:
M = [0 1^T; 1 D], where D is a 4x4 symmetric matrix with zero diagonal and off-diagonal entries squared distances.
One known result: det(M) = - (det(B)) where B is something like? Actually for a bordered matrix, there is formula.
Alternatively, we can compute the determinant by eliminating the first row and column via Schur complement. Since the top-left entry is 0, the Schur complement formula is det(M) = -1 * det( [1,1,1,1; D]? Not.
Let’s write M = [[0, b^T], [b, D]] where b is a column vector of four ones. Then det(M) = (-1) * b^T adj(D) b * det(D) ??? Not simple.
But we can compute directly via expansion into 4x4 determinants as earlier: D = -det(M01) + det(M02) - det(M03) + det(M04), where M0j is submatrix removing row0 col j.
Let's compute those 4x4 determinants.
Define the 4x4 matrices:
For j=1: remove row0 and column1. So we keep rows 1-4, columns 0,2,3,4.
Thus M01 =
columns: col0, col2, col3, col4.
Rows 1 to 4:
Row1: [1, p, q, r] (since col0=1, col2=p, col3=q, col4=r)
Row2: [1, 0, s, t] (col0=1, col2=0, col3=s, col4=t)
Row3: [1, s, 0, u] (col0=1, col2=s, col3=0, col4=u)
Row4: [1, t, u, 0] (col0=1, col2=t, col3=u, col4=0)
So M01 is a 4x4 matrix. Its determinant we can compute.
Similarly, for j=2: remove row0 col2. Keep rows1-4, columns0,1,3,4.
M02:
Row1: [1, 0, q, r] (col0=1, col1=0, col3=q, col4=r)
Row2: [1, p, s, t] (col0=1, col1=p, col3=s, col4=t)
Row3: [1, q, 0, u] (col0=1, col1=q, col3=0, col4=u)
Row4: [1, r, u, 0] (col0=1, col1=r, col3=u, col4=0)
j=3: remove row0 col3. Keep cols0,1,2,4.
M03:
Row1: [1,0,p,r] (col0=1, col1=0, col2=p, col4=r)
Row2: [1,p,0,t] (col0=1, col1=p, col2=0, col4=t)
Row3: [1,q,s,u] (col0=1, col1=q, col2=s, col4=u)
Row4: [1,r,t,0] (col0=1, col1=r, col2=t, col4=0)
j=4: remove row0 col4. Keep cols0,1,2,3.
M04:
Row1: [1,0,p,q] (col0=1, col1=0, col2=p, col3=q)
Row2: [1,p,0,s] (col0=1, col1=p, col2=0, col3=s)
Row3: [1,q,s,0] (col0=1, col1=q, col2=s, col3=0)
Row4: [1,r,t,u] (col0=1, col1=r, col2=t, col3=u)
Now D = -det(M01) + det(M02) - det(M03) + det(M04).
We can compute each 4x4 determinant. Perhaps we can find a pattern and combine.
But maybe we can derive a compact formula. I recall the following expression for the Cayley-Menger determinant for a tetrahedron:
Δ = - ( (a^2 f^2 (-a^2 + b^2 + c^2 + d^2 + e^2 - f^2) + ... )? Actually I'm mixing with formula for volume in terms of opposite edges: For a tetrahedron with opposite edges (say, a and A, b and B, c and C) there is formula: 144 V^2 = a^2 A^2 (b^2 + c^2 + B^2 + C^2 - a^2 - A^2) + ... - (a^2 b^2 c^2 + a^2 B^2 C^2 + b^2 A^2 C^2 + c^2 A^2 B^2). Something like that.
Better to implement a generic determinant function for 5x5. Since we have many calls, we could precompute the determinant formula as a polynomial in the six squared lengths. That polynomial is degree 3? Actually each term is product of three squared lengths? Let's see: Volume squared is degree 6 in lengths? Actually squared volume involves squares of lengths, so 288 V^2 is homogeneous of degree 6. So D is homogeneous of degree 6 in lengths (since each entry squared lengths, determinant is sum of products of 5 entries, each could be squared length or 0 or 1, so overall each term is product of up to 3 squared lengths? Actually each term in determinant expansion picks one element from each row and column. The matrix has zeros on diagonal. So each term is a product of 5 entries. Among those entries, some are 0, 1, or squared lengths. To get a nonzero term, we cannot take a diagonal zero unless we also pick something else? Wait, the diagonal entries are zeros, but we can still select them as part of permutation. However, the determinant includes terms with zero product if any chosen entry is zero. They vanish. So non-zero terms correspond to permutations where we avoid selecting zeros? But we can select zeros if we like, but term becomes zero. So non-zero terms must pick non-zero entries. The non-zero entries are: the ones (in first row and first column) and the squared lengths in off-diagonal positions (excluding first row/col and diagonal). Actually the matrix has structure: first row: 0,1,1,1,1; first column: 0,1,1,1,1; diagonal (0..4): 0,0,0,0,0. So the only non-zero entries besides ones are the squared lengths at positions (1,2),(1,3),(1,4),(2,1),(2,3),(2,4),(3,1),(3,2),(3,4),(4,1),(4,2),(4,3). But note that (1,2) and (2,1) both equal p etc. So the matrix is symmetric.
Given this structure, the determinant will be a polynomial in the squared lengths. It might be expressed as:
D = -p^2 q^2 r^2 - p^2 s^2 t^2 - ...? Not.
Let's compute D directly with symbolic algebra. We can use expansion by minors as above. Compute det(M01), etc.
We can try to compute each 4x4 determinant symbolically. Because they have similar patterns, we might be able to sum them.
But perhaps simpler: Since N is small, computing 3.6 million 5x5 determinants via Gaussian elimination is acceptable. Let's estimate operations: each determinant via Gaussian elimination with partial pivoting on 5x5 takes about 5^3/3 ≈ 42 operations for LU (but with double and loops). Actually naive Gaussian elimination for 5x5: each pivot row elimination requires about O(n^2) operations, total about O(n^3)=125 multiply-adds. So 125 operations per determinant. 3.6 million * 125 = 450 million flops. In C++ with double, 450 million operations might take a few seconds (maybe 2-3 seconds) and could be okay given typical contest time limits (maybe 1 sec? But we can optimize). However we also have to iterate over combinations: 5005, and for each combination we have many permutations. So maybe it's okay. But we also need to sort each combination's array and generate permutations, which adds overhead.
But 5005 * 720 = 3.6 million permutations. For each we need to compute squared lengths and determinant. 3.6 million determinants is acceptable if optimized. However we also need to consider worst-case input: multiple test cases. Input terminates with 0. The number of test cases could be many? Possibly up to unknown number. But given N up to 15, and each test case has N and numbers, there could be many test cases. But typical problem statements might have up to, say, 30 test cases. 30 * 3.6 million = 108 million determinants? Actually 3.6 million per case, times maybe 30 = 108 million, which is still okay. But we need to be careful about time.
But we can improve by pruning: for each combination of 6 sticks, we need to check if there exists some permutation that yields positive volume. However we can't easily know max volume without checking all permutations. But maybe we can do something smarter: The volume is related to the product of areas? Not simple.
Alternatively, we can generate all assignments up to isomorphism: 30 per combination. That reduces to 5005 * 30 = 150,150 determinants per test case, which is much smaller. So it's beneficial to reduce permutations to 30.
Thus we should implement assignment by considering distinct ways to assign six lengths to the six edges of K4 up to vertex relabeling. That is, we need to consider all distinct labelings of the complete graph K4 with 6 edges with given lengths, where two labelings are considered equivalent if they differ by a permutation of vertices (S4). Since the graph is fully symmetric, any permutation of vertices induces a permutation on edges. The edge permutation group induced by S4 has order 24 and acts on the 6 edges. So the number of distinct assignments (orbits) for a given multiset is 720/24 = 30 only if all edges lengths are distinct. If there are duplicates, the number of distinct assignments (orbits) is less, but 30 is an upper bound. So we can generate 30 canonical assignments by fixing a labeling of vertices and then considering all distinct bijections from the multiset to the edges modulo vertex relabeling? Actually we can generate all permutations of the 6 lengths to the edges, but then factor out the group of 24 symmetries. However generating all 720 and then discarding duplicates is wasteful. Better to generate only one representative per orbit. How to systematically generate? We can assign lengths to edges in a canonical way: Because vertices are unlabeled, we can assign lengths to the six edges in a way that respects some ordering to break symmetries. For instance, we can label vertices 0,1,2,3. Edges: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). The symmetry group S4 permutes vertices. To get distinct assignments up to symmetry, we can impose an ordering on the edge lengths assigned to certain edges, like require that the three edges incident to vertex 0 (which are edges 0-1,0-2,0-3) are sorted in non-decreasing order, and also maybe other constraints to break symmetry. However the group action is not simply ordering of those three edges; other symmetries could permute the rest. Let's think.
We have six edges. The action of S4 on edges yields that the edge set partitions into orbits? Actually all edges are equivalent under S4? In K4, the automorphism group is S4, which is edge-transitive? Yes, K4 is edge-transitive: any edge can be mapped to any other edge by some vertex permutation. So all edges are equivalent. But the action is not free: the stabilizer of an edge has size 4 (the permutations that fix that edge as set? Actually edge stabilizer in S4 for K4: an edge has two vertices, permutations that fix the set of those two vertices (possibly swapping them) and possibly permuting the other two vertices). So the group size is 24, edge orbit size is 6, so stabilizer size 4. So each assignment (bijection from the multiset of lengths to the 6 edges) can be transformed by 24 vertex permutations, but many will map to the same edge labeling if lengths have symmetry.
To generate distinct orbits, we could iterate over all ways to assign lengths to edges with some canonical labeling condition. Since the number is only 30, we could precompute all 30 distinct "patterns" of edge assignments relative to a fixed vertex labeling, by considering all permutations of lengths to edges and then applying a canonical normalization that maps each assignment to a canonical representative (e.g., by applying the minimal representation under lexicographic order after sorting edges according to some fixed order, considering all vertex relabelings). But maybe simpler: we can just generate all 720 permutations but use a hash set to avoid recomputing the same orbit? But that adds overhead.
Better approach: Use backtracking to assign lengths to edges while respecting vertex symmetries by imposing ordering constraints. For example, we can label vertices arbitrarily but fix that vertex 0 is the vertex with smallest sum of incident edges? That's messy.
Given that 720 permutations per combination is not huge, we can accept it. However we need to consider the possibility of many test cases. But typical contest problems with N up to 15 and multiple test cases might still be okay with 720 per combination, given that C(15,6)=5005, 5005*720=3.6M, and each determinant calculation maybe ~100 operations, so 360M operations total per test case, which might be borderline in Python but fine in C++. In C++, 360M double ops might be around a second or two with optimizations? Actually 360 million operations could be around 0.5-1 second if optimized? But careful: Each determinant via full Gaussian elimination might be ~125 floating operations, but with loops overhead it could be more. 3.6M * 125 = 450M flops. Modern CPUs can do billions of flops per second, but with branching and memory access, it might be a bit slower. However we also have overhead for combination generation, permutation generation, etc. Could be around 1-2 seconds per test case. If there are many test cases, maybe up to 10, could be 10-20 seconds, which might be too high. So it's better to reduce the inner loop to 30 per combination.
Thus let's aim to generate 30 assignments per combination.
How to generate the 30 distinct assignments? One way: Since the symmetry group of K4 (S4) has 24 elements, the number of distinct labelings of edges by distinct labels (i.e., assignments) is 6! / 24 = 30. For each combination of 6 lengths (multiset), the number of distinct edge-labeled tetrahedra up to congruence (ignoring vertex labeling) is the number of orbits of the symmetric group action on the set of bijections from the 6 sticks to the 6 edge positions. This equals the number of distinct ways to assign the lengths to edges, where two assignments are considered the same if one can be obtained by relabeling vertices. In terms of constructing tetrahedra, the volume depends only on the assignment up to vertex relabeling? Actually yes, because relabeling vertices just renames the edges, but the geometric shape (the set of edge lengths with connectivity) is the same if we permute vertices; it's the same tetrahedron. So the volume is invariant under vertex relabeling. So we only need to consider one representative from each orbit.
Thus we can generate all 6! permutations and then apply a canonical reduction: for each permutation, compute a canonical signature by considering all 24 vertex relabelings and taking the lexicographically smallest (or some hash) among the resulting edge assignments (ordered by a fixed edge order). Then only process if the current permutation is the canonical one. But that would require for each permutation to iterate over 24 relabelings, which adds factor 24, making it worse. Not good.
Better to generate orbits directly: we can fix an ordering of vertices to break symmetry. For example, we can fix that the three edges incident to vertex 0 (call them e01, e02, e03) are assigned lengths in non-decreasing order. But that's not sufficient to eliminate all symmetry, because vertices 1,2,3 are still permutable. However if we also enforce an ordering condition on the other edges relative to vertex 0, we might break symmetry fully.
Let's label vertices 0,1,2,3. Edges: e0 = (0,1), e1 = (0,2), e2 = (0,3), e3 = (1,2), e4 = (1,3), e5 = (2,3). We want to impose constraints such that any labeling of vertices yields a unique representation. This is similar to canonical labeling of a complete graph with labeled edges. Since vertices are unlabeled, we need to choose a labeling that yields a canonical form.
One method: Because the graph is small, we can simply generate all 6! permutations and then use a hash set to avoid duplicates per combination, using a canonical representation that is invariant under vertex relabeling. But that would require storing the 6-length tuple in some canonical order that respects graph isomorphism. We can define a canonical ordering of the 6 edges based on the structure: sort the edge list in some order that is independent of vertex labeling. However the edges are unlabeled, so we need to assign a canonical labeling to the vertices based on the edge lengths. This is essentially the graph isomorphism problem for K4 with edge weights; we need to find a canonical labeling of the vertices such that the resulting edge list (ordered by some fixed edge order) is lexicographically minimal (or maximal). This can be done by trying all 24 vertex labelings and picking the one that yields the smallest (or largest) tuple of edge lengths when edges are listed in a fixed order (e.g., (0-1,0-2,0-3,1-2,1-3,2-3) after relabeling vertices). Then for a given multiset, we can generate permutations and for each permutation, we compute its canonical form under vertex relabeling, and only accept if the permutation equals its canonical form (i.e., it is the lexicographically smallest among its orbit). This still requires for each permutation to compute 24 relabelings to check if it's minimal, which would be 720*24=17280 per combination, which is worse. So not good.
Alternatively, we can enumerate assignments by iterating over distinct ways to assign lengths to the edges up to symmetry using backtracking with pruning based on vertex symmetry breaking constraints. Since the number of assignments up to symmetry is only 30, we could generate them by first generating all 6! permutations but then using a visited set based on orbits. But for each combination we could generate the 6! permutations and store them in a set of 6-tuples using a canonical representation that collapses under symmetry. That is, for each permutation (assignment to edges in fixed order e01,e02,e03,e12,e13,e23), we compute its canonical signature as the lexicographically smallest tuple among all 24 vertex relabelings. Then we insert that signature into a set. However that would still need to compute 24 transformations per permutation to get the canonical signature. But we could precompute the 24 permutations of edges induced by vertex relabelings. That is, for each of the 24 permutations of vertices (S4), we can compute the corresponding permutation on the 6 edges (since edges are indexed). Then for a given assignment (tuple of 6 numbers), applying a vertex relabeling corresponds to permuting the tuple according to that edge permutation. So we can precompute an array of 24 permutations on indices 0..5. Then for each tuple (assignment), we can compute its orbit by applying these 24 permutations and take the lexicographically smallest tuple as canonical. Then we can process only those assignments where the tuple itself is the canonical representative (i.e., it is minimal among its orbit). But to decide if a given tuple is the canonical one, we need to compare with its orbit, which requires applying up to 24 permutations. That's 24 operations per tuple, which is less than computing determinant. 720 * 24 = 17280 per combination, which is small compared to 720 determinants? Actually 17280 operations are just integer swaps, not heavy. But then we still compute determinants only for those canonical tuples? Actually we would compute determinants only for canonical tuples, but we still need to generate all permutations and filter. That yields about 720 permutations generated, and for each we apply 24 transformations to check canonicity; then if canonical, compute determinant. The number of canonical tuples per combination is at most 30, so we compute at most 30 determinants. The overhead of generating 720 permutations and 24 checks each (17280) might be acceptable, as it's just integer comparisons and maybe a few array operations. 5005 combinations * 17280 = ~86 million simple operations, which is fine.
But we can do even simpler: just compute determinants for all 720 permutations; that's 3.6M determinants. 3.6M determinants each maybe ~125 flops = 450M flops. That might still be okay, but to be safe, implementing the orbit reduction reduces determinant computations to about 150k per test case, which is trivial. So I'll implement the orbit reduction.
Thus steps:
- Precompute the 24 vertex permutations (bijections of {0,1,2,3}) and the induced edge permutations.
We label edges as indices 0..5 with fixed mapping:
e0: (0,1)
e1: (0,2)
e2: (0,3)
e3: (1,2)
e4: (1,3)
e5: (2,3)
Given a permutation p of vertices (size 4), we define the new vertex labels: original vertex v becomes p(v). The edge (i,j) becomes (p(i), p(j)). Since edges are unordered pairs, we need to map them back to the fixed edge indices based on sorted vertex order. After applying p, edge (i,j) becomes (p(i), p(j)). To convert to edge index, we sort the two vertex labels to (a,b) with a<b, then assign:
if (a,b) == (0,1) -> index 0
if (0,2) -> 1
if (0,3) -> 2
if (1,2) -> 3
if (1,3) -> 4
if (2,3) -> 5
Thus for each p (24 permutations), we can compute an array edge_perm[24][6] that maps original edge index k to new edge index under the vertex relabeling. That is, for each original edge k (with vertices (i,j)), after applying p, the new edge corresponds to some new index l. Then the tuple of lengths assigned to edges under relabeling becomes: new_tuple[l] = old_tuple[k]. So the permutation on indices is: for each old index k, its value goes to new index l = perm_edge[k]. Actually careful: If we have assignment tuple T (lengths assigned to edges indices 0..5), after relabeling vertices, the edge that was originally k is now at position l? Actually the labeling of edges is defined by vertex pairs. When we relabel vertices, the edge that originally corresponded to pair (i,j) now corresponds to pair (p(i), p(j)). Under our fixed indexing, we assign index based on the pair after relabeling. So the new tuple S (in the same fixed ordering of edge indices) has at position l the length that was originally at position k, where l is the index of (p(i),p(j)). So S[l] = T[k]. This defines a permutation sigma on indices: sigma(k) = l, and we have S = T composed with sigma^{-1}? Actually if we want to express the transformation as a permutation on the tuple positions: given T (original assignment), after relabeling, the new assignment (according to same indexing) is given by: for each new index l (edge (a,b) in fixed order), the length comes from old index k such that (p(i),p(j)) = (a,b) where (i,j) is the original edge for index k. That is, k = sigma^{-1}(l). So it's easier: precompute for each vertex permutation p, an array perm[6] such that for each original edge index k, the new index is perm[k] (i.e., where the length from old index k goes). Then the transformed tuple S is defined by S[perm[k]] = T[k]. So we can generate S by iterating k.
Thus we can precompute these 24 permutations.
Now for a given tuple T (list of 6 lengths), we can generate its orbit by applying all 24 permutations to get S. The canonical representative can be the lexicographically smallest S (as a sequence of 6 numbers). Since lengths are integers, we can compare tuples easily. Then we consider T only if T is the lexicographically smallest among its orbit. That is, for all 24 perm, S (obtained as above) is >= T lexicographically? Actually we need T <= S for all S. So we can check: if for any perm, the transformed tuple is lexicographically smaller than T, then T is not canonical. So we need to check all 24 perms and ensure T is the smallest.
But we have to be careful: when there are duplicate lengths, there may be multiple permutations that give the same tuple; we treat them as same. The condition "smallest" ensures we pick a unique representative.
Thus algorithm per combination:
-
Get the 6 lengths as an array orig_len[6] (sorted initially? We'll generate permutations later, so T will be a specific ordering of the 6 numbers.)
-
We will generate all permutations of the 6 numbers (using next_permutation on sorted list). For each permutation, treat it as assignment T to edges in order (0,1,2,3,4,5). Then we test if T is canonical: for each of the 24 precomputed permutations, we compute S by applying permutation: S[perm[k]] = T[k] for k=0..5. Then compare S with T lexicographically. If any S < T, then skip this T (not canonical). Else, it's canonical, compute determinant and volume.
But this checking for each T requires 24 transformations and comparisons. That's okay.
To avoid duplicate work due to symmetric permutations, we need to ensure that we generate each permutation exactly once (with duplicates handled by next_permutation). Since we generate all distinct permutations of the multiset, we will generate each distinct ordering. Some orderings may be equivalent under symmetry; we only process those that are canonical.
Now, is it guaranteed that each orbit has at least one canonical representative? Yes, the lexicographically smallest tuple in the orbit will be chosen. Since we generate all permutations, we will encounter that representative at some point. And we will process it when we encounter it. When there are ties (multiple orderings giving the same tuple, but they are identical as sequences), if that tuple is the smallest, it will be processed only once because we will generate it once? Actually if the multiset has duplicates, there may be duplicate tuples identical as sequences from different permutations? No, next_permutation on sorted array generates each distinct sequence exactly once. So if the canonical tuple appears, it will be generated exactly once.
Thus we reduce determinant computations to at most 30 per combination.
Now we need to ensure we precompute the 24 vertex permutations. We can generate all permutations of 0,1,2,3 (24). For each, compute edge mapping.
Edge list: edges = [(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]
For a vertex permutation p (array of size 4), for each edge index k with pair (i,j), compute new pair (p[i], p[j]), sort, then determine new index l. Then set perm[k] = l.
Now we have 24 permutations.
Now we need to compute the Cayley-Menger determinant