Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.
Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.
Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).
A regiment is compact only if the position points of the 4 moles form a square with non-zero area.
Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.
Input
The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments.
The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).
Output
Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).
We need to solve: for each group of 4 moles (4 consecutive lines), each mole i has initial position (xi, yi) and home (ai, bi). A move rotates (xi, yi) by 90° ccw around its home. So after k moves, the mole's position becomes the rotation by 90°*k around its home.
We need to choose for each mole a number of moves ki ∈ {0,1,2,3} (since rotating 4 times returns to original, we can limit to 0..3 as more moves would be reducible mod 4 and would be wasteful) such that the four resulting points form a square (non-zero area). The goal is to minimize total moves sum(ki). If impossible, output -1.
We need to compute for each regiment the minimum sum.
n ≤ 100, so per regiment we can brute force all 4^4=256 possibilities, and check if the four points form a square. That's fine.
The main challenge: check if four points (order not given) form a square. We have four points from the four moles after chosen rotations. We need to determine if they can be the vertices of a square with non-zero area. Since the points are not in any specific order, we need to check if there is a way to label them as square vertices. Typically, we can sort points or compute distances.
Approach: given 4 points, compute all pairwise distances squared. For a square, there should be 4 equal side lengths (non-zero) and 2 equal diagonal lengths (which are twice the side squared). Also, the set of distances squared should have exactly two distinct values: side^2 (occurring 4 times) and diagonal^2 (occurring 2 times). But careful: if points are not distinct? The problem says positions of 4 moles, they might coincide after rotations? But square requires non-zero area, so points must be distinct and not degenerate. So we also need to ensure area >0.
But also could be a rhombus? A rhombus with equal sides but not right angles would have side squared equal for all four sides, but diagonals would be different; but the distance set would have side^2 (4 times), and two diagonal squared (maybe different). For a square, the diagonals are equal. So condition: exactly 2 distinct distance values, and among the 6 distances, the smaller one occurs 4 times, larger occurs 2 times, and 2 * smaller == larger (since diagonal^2 = 2 * side^2). Also area >0 ensures smaller >0.
But there might be cases where the points form a square but distances include also other values due to floating? But we use integer coordinates, so distances squared are integers. So we can compute.
Alternatively, we can sort points, compute vectors, but careful with order.
Simpler: For each set of 4 points (p0,p1,p2,p3), we can generate permutations? That would be 24, too many but still okay if done per each of 256 combinations, but that's 25624=6144 checks per regiment, still fine (1006144=614400). But we can do distance-based check without permutations.
So algorithm:
For a regiment:
For each mole i (0..3), we precompute its possible positions after k moves (k=0,1,2,3). That is: for given (x,y) and home (a,b), after rotation by 90°*k ccw around home, the coordinates are:
Let dx = x - a, dy = y - b.
After rotation by 90° ccw: ( -dy, dx )? Actually rotation matrix: (dx, dy) rotated by θ: (dx cosθ - dy sinθ, dx sinθ + dy cosθ). For 90°, cos=0, sin=1 => (-dy, dx). So new point = (a + (-dy), b + dx) = (a - dy, b + dx).
After 180°: (-dx, -dy) => (a - dx, b - dy)
After 270°: (dy, -dx) => (a + dy, b - dx)
So compute for each mole i and k, pos[i][k] = (x_k, y_k) as integer.
Now we iterate over k0,k1,k2,k3 each from 0 to 3, compute total moves = sum(ki). If total moves >= current min, we can skip (pruning). For each combo, we have points p0 = pos[0][k0], p1 = pos[1][k1], p2 = pos[2][k2], p3 = pos[3][k3].
Check if they form a square with non-zero area:
Compute list of points = [p0,p1,p2,p3]
Check all points distinct? Could be but if not, fails square (area zero). But we can include in distance check: if any distance squared = 0, then two points coincide, so not a square (non-zero area). So we can just ensure that the smaller distance >0.
Compute pairwise distances squared between all 6 pairs.
Sort them. Let d = sorted list.
Check: d[0] > 0 (so no coinciding points)
Check: d[0]==d[1]==d[2]==d[3] (four smallest should be equal sides)
Edge Cases: Might there be a degenerate square where points are in order but distances match? The condition above is necessary and sufficient for a set of 4 points to form a square (non-zero area) ignoring order. However, consider a rhombus with angles 60 and 120? Then sides equal, diagonals not equal, so d[4]!=d[5] fail. A rectangle that is not square: sides a and b, with a != b. Then distance set: two sides of length a (square?), wait: In rectangle, opposite sides equal. Pairwise distances: 2 sides squared = a^2 (two opposite edges? Actually distances between vertices: four sides: two of length a^2, two of length b^2? Wait sides: There are 4 edges: two edges of length a, two of length b. But pairwise distances among vertices include edges: Actually the set of 6 distances includes: 4 sides (edges) and 2 diagonals. In rectangle, sides are not all equal: there are two pairs of equal sides. So distance squared values: a^2 appears 2 times (the two sides of length a), b^2 appears 2 times (two sides of length b), and diagonal^2 = a^2+b^2 appears 2 times. So three distinct values. So fails.
What about a square but with points not in order? The set of distances is still as described.
But caution: The distance method can be fooled if the points form a line? For a degenerate line: distances: some zero? Actually if all points colinear, the set of distances might include zeros if coincident. But if they are distinct colinear points, then there is no equal side lengths etc. It will fail.
So the distance check is robust.
But we must consider integer overflow? coordinates up to 1e4, after rotation coordinates may be up to? dx = x - a, up to 2e4, after rotation and adding a, still within maybe 3e4? Actually x, a up to 1e4, difference up to 2e4, adding a up to 1e4 gives range [-1e4-2e4? Wait: a - dy: a up to 1e4, dy up to 2e4, so a - dy could be as low as -1e4 - 2e4 = -3e4, so coordinates could be between -3e4 and 3e4. Squaring: up to 9e8, fits in 32-bit int? 9e8 < 2^31-1. Sum of squares: distance squared = (dx)^2+(dy)^2, each up to (3e4)^2=9e8, sum up to 1.8e9, still fits in 32-bit signed? 2,147,483,647 > 1.8e9, so safe. But careful: if we compute with long long to avoid overflow, we can use long long in C++.
We'll use Python, unlimited.
Now the main problem: minimal moves per regiment. We'll iterate all 4^4=256 combos. For each, compute sum ki, if less than min and square condition passes, update min.
If min remains INF, output -1.
We need to parse input: first line n, then 4n lines each with xi yi ai bi. We'll process in groups of 4.
Implementation steps:
Read n
For each regiment index i from 0 to n-1:
Initialize a list mole_positions = [] for 4 moles
For each mole in range(4):
read xi, yi, ai, bi (if using sys.stdin)
compute pos_k = []
for k in 0,1,2,3:
compute as described.
mole_positions.append(pos_k)
Set ans = INF (e.g., 1e9)
Loop over k0..k3 in product(range(4), repeat=4):
total = sum(ks)
if total >= ans: continue (optional pruning)
pts = [mole_positions[i][ks[i]] for i in range(4)]
if is_square(pts):
ans = total
print(ans if ans != INF else -1)
Define is_square(pts):
Compute dist2 = []
for i in range(4):
for j in range(i+1,4):
dx = pts[i][0]-pts[j][0]
dy = pts[i][1]-pts[j][1]
d = dxdx + dydy
dist2.append(d)
sort dist2
Check:
if dist2[0] == 0: return False
if dist2[0] == dist2[1] == dist2[2] == dist2[3] and dist2[4] == dist2[5] and 2*dist2[0] == dist2[4]:
return True
else: return False
But careful: There could be case where the points are a square but due to floating? Not.
Edge Cases: Points might be in order such that the four smallest distances are not all equal? In a square, the side length is the smallest distance (since diagonal > side). So yes, the four smallest distances are the sides, and the two largest are diagonals. So sorted order: sides (4 times) then diagonals (2 times). But ensure that side length is indeed smaller than diagonal. Since diagonal squared = 2 * side^2 > side^2 for side>0. So yes.
But what if the square is oriented such that some side distances equal? Always.
Thus check is valid.
Now ensure we consider that we may have degenerate square? Not.
Potential optimization: skip if any two points coincide: that would cause dist2[0] == 0; but it's already covered.
Now test with given examples.
We'll implement in Python.
Let's quickly test manually with first regiment:
Input first 4 lines:
1 1 0 0
-1 1 0 0
-1 1 0 0
1 -1 0 0
Positions: For each mole, home (0,0). So they are initially at (1,1), (-1,1), (-1,1), (1,-1). Actually third mole also (-1,1). So we have duplicate points: two moles at (-1,1). After moves, can we get a square? They said minimal moves = 1.
Let's see: We have 4 points: (1,1), (-1,1), (-1,1), (1,-1). To be a square, we need distinct points. So we must move at least one of the duplicates. For example, move second or third mole once: rotating ( -1,1) around (0,0) 90° ccw gives (-1? Actually compute: (-1,1) relative to (0,0) is (-1,1). Rotating 90 ccw: (-dy, dx) = (-1, -1)? Wait: dx = -1, dy = 1. Then rotated: (-dy, dx) = (-1, -1)? Actually -dy = -1, dx = -1 => (-1, -1). So new point (-1,-1). That would give points: (1,1), (-1,1), (-1,-1), (1,-1) which is a square. Total moves 1. So our code should find that.
Check is_square for those points: distances: sides: between (1,1) and (-1,1): 2^2=4, (1,1) and (1,-1): 2^2=4, (-1,1) and (-1,-1): 4, (-1,-1) and (1,-1):4; diagonals: between (1,1) and (-1,-1): 8, ( -1,1) and (1,-1):8. So sorted: [4,4,4,4,8,8] check passes.
Second regiment: They say impossible.
Third: etc.
So algorithm works.
Now we need to be careful: For each regiment, we must treat moles in given order; but the order doesn't matter since we consider all combinations of rotations.
Implementation details: we can read all lines and process.
Complexities: n ≤ 100, each regiment 256 combos, each check O(1). So trivial.
Now implement in code.
We should also consider using integer coordinates.
Now double-check rotation formulas:
Given (x,y) and home (a,b). Compute dx = x - a, dy = y - b.
After k rotations of 90° CCW:
k=0: (a + dx, b + dy)
k=1: (a - dy, b + dx)
k=2: (a - dx, b - dy)
k=3: (a + dy, b - dx)
Yes.
Test with simple: (x,y)=(1,0), home (0,0): k1 gives (0,1)? Actually (a - dy=0-0=0, b+dx=0+1=1) => (0,1) correct.
So we'll use that.
Now produce code.
But there's nuance: The problem statement says each mole can be moved multiple times, meaning you can apply rotation multiple times. Since rotation by 90°, applying 4 times yields original. So we only need consider 0..3 moves. However, could using more than 3 moves ever yield a solution with fewer total moves? No, because sum mod 4? Actually each individual mole's position after k moves is same as after k mod 4 moves. But the count of moves is total number of rotations applied, which is sum of ki. If we use ki = 5, that is 5 moves for that mole, but the resulting position is same as 1 move (since 5 mod 4 =1) but total moves count would be 5, which is larger than 1, so it's never beneficial to use >3 moves because we can reduce to 1 and lower total sum. So it's safe to limit to 0..3.
Thus the brute force over 4^4 is exhaustive.
Now edge Cases: Could there be a case where two different ki values give the same position? Yes, if rotation is periodic. But we still consider all.
Now let's double-check distance condition: Could there be a square where the sorted distances have sides not as the smallest? Actually diagonal is longer than side for positive area, so sides are smallest. So sorted works.
But what if the square has side length s and diagonal d, and s^2 and d^2 satisfy 2*s^2 = d^2, but there might be other distances if points are not ordered? No, only those six distances. So condition is correct.
However, I recall that sometimes the set of distances for a square may have 2 distinct values but also there is possibility that the four smallest distances could include diagonals if the points are arranged? For a square, diagonal is always longer than side, so no.
Thus it's fine.
But we need to be careful about precision: we are using integers, so equality check works.
Now consider degenerate case: all four points the same? Then dist2[0]=0, fails.
Now implement.
Potential improvements: Early pruning: if total moves already >= current min, skip. Also we can compute minimal possible moves lower bound? Not needed.
Now let's consider the possibility that the same square can be formed with different move sets; we take min.
Now implement code.
We'll define a function is_square(pts) that returns bool.
Testing with the fourth regiment from example: They said output 3. Let's test manually? Not needed.
Now confirm the reading: The example input: After first regiment (4 lines) second regiment (lines 5-8) etc. So we process sequentially.
Now write code.
But need to ensure we correctly parse all 4n lines. We'll read all lines into list or process line by line.
Implementation in Python:
import sys
from itertools import product
def rotate(x, y, a, b, k):
dx = x - a
dy = y - b
if k == 0:
return (a + dx, b + dy)
elif k == 1:
return (a - dy, b + dx)
elif k == 2:
return (a - dx, b - dy)
else: # k == 3
return (a + dy, b - dx)
def is_square(pts):
# pts: list of 4 tuples (x, y)
dists = []
for i in range(4):
x1, y1 = pts[i]
for j in range(i+1, 4):
x2, y2 = pts[j]
dx = x1 - x2
dy = y1 - y2
d = dxdx + dydy
dists.append(d)
dists.sort()
# Check criteria
if dists[0] == 0:
return False
if dists[0] != dists[1] or dists[1] != dists[2] or dists[2] != dists[3]:
return False
if dists[4] != dists[5]:
return False
if 2 * dists[0] != dists[4]:
return False
return True
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
n = int(next(it))
out_lines = []
for _ in range(n):
# read 4 moles
pos = [] # for each mole, list of 4 positions after rotations
for i in range(4):
x = int(next(it)); y = int(next(it)); a = int(next(it)); b = int(next(it))
mole_positions = [rotate(x, y, a, b, k) for k in range(4)]
pos.append(mole_positions)
min_moves = 1e9
for ks in product(range(4), repeat=4):
total = sum(ks)
if total >= min_moves:
continue
pts = [pos[i][ks[i]] for i in range(4)]
if is_square(pts):
min_moves = total
if min_moves == 1e9:
out_lines.append("-1")
else:
out_lines.append(str(min_moves))
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
This should work.
But we need to double-check product: It yields tuples (0,0,0,0) etc.
But there is a nuance: The distance check must ensure that the four points are exactly the vertices of a square, not just that distances satisfy conditions. Is the condition (4 equal sides, 2 equal diagonals, and 2side^2==diag^2) sufficient to guarantee a square? For a set of four points in the plane, if the distances among them satisfy that, does it guarantee they form a square? Consider a rhombus with 60-120 angles: sides equal, diagonals lengths: d1^2 = a^2 + a^2 - 2a^2 cos(120) = 2a^2(1 - cos120)?? Actually better: For rhombus with side s, diagonals are generally not equal. But could it be that both diagonals are equal? In a rhombus, diagonals are equal only if it's a square (since a rhombus with equal diagonals is a square?). Wait, a rhombus with equal diagonals implies all sides equal and diagonals equal. In a rhombus, diagonals are perpendicular? Not necessarily. But a quadrilateral with all sides equal and diagonals equal is a square? Actually a rhombus with equal diagonals is a square because in a rhombus, the angles are supplementary; if diagonals are equal, then the angles are equal, and all angles become 90 degrees. Yes, a rhombus with equal diagonals is a square. So the condition that four equal sides (rhombus) and equal diagonals forces it to be a square. But we also require 2side^2 == diag^2; that's actually stronger than just equal diagonals: it ensures the angle is 90 because diagonal^2 = side^2+side^2 - 2side^2cos(theta) for a parallelogram? Actually for a rhombus, the diagonal lengths: d1^2 = 2s^2(1 - cosθ), d2^2 = 2s^2(1 + cosθ). For them to be equal, we need cosθ=0 => θ=90. So d1=d2 = s√2. So our condition of 2side^2 == diag^2 already implies right angle and equal diagonals. So having four equal sides and 2side^2==diag^2 ensures it's a square.
But is the condition of four equal sides necessary? Could there be a configuration that is a square but not all sides equal? No.
But we must also ensure that the points are coplanar? They are in plane.
Thus condition is sufficient.
However, there is a pitfall: The set of six distances for a square might also be obtained by a different configuration? For instance, four points could be such that distances: four equal smallest distances and two larger equal distances but 2*small != large? That would be a rhombus with equal diagonals but not right angle? Actually if diagonals are equal, we already argued it's square. But could we have a configuration that is not a quadrilateral? For example, three points forming an equilateral triangle and the fourth point somewhere? That wouldn't yield exactly four equal smallest distances. So it's safe.
Thus our is_square is correct.
Now we should verify that the distance check doesn't mistakenly accept a degenerate case where the four points are in a cross shape? Example: points at (0,0), (1,0), (0,1), (1,1) form a square. Our condition works.
Another test: points (0,0), (0,1), (1,0), (1,1) - sides: distances: between (0,0)-(0,1)=1, (0,0)-(1,0)=1, (1,1)-(0,1)=1, (1,1)-(1,0)=1, diagonals: (0,0)-(1,1)=2, (0,1)-(1,0)=2 => passes.
Now we should consider that the points might be in a different order; the distance set is the same.
Thus algorithm stands.
Now note: The problem says "non-zero area", which we ensure by side>0.
Now we think about potential integer overflow? In Python it's fine.
Now what about time? n=100, 256 combos per regiment, each combo compute distances: 6 distance calculations, sort list of 6, trivial. So fine.
Now we need to consider if there are any tricky cases where the rotation leads to points that are not integer? Actually rotations around integer coordinates with integer dx,dy may produce integer coordinates? Since dx,dy are integers, rotation by 90° yields (-dy, dx) which are integers. So all positions remain integer coordinates. So we avoid floating.
But we must be careful: In the third regiment, we have three moles at the same initial position. To form a square, we need four distinct vertices. So we must move at least some. The answer is 3.
Our brute force should find a combination with sum=3.
Now check potential pitfalls: The is_square function might incorrectly accept a set of points that are not a square due to ordering? But we already argued it's fine.
But there is nuance: The condition that the four smallest distances are equal and the two largest are equal and 2small=large is necessary and sufficient for a set of four points to be vertices of a square. However, consider a degenerate case where the four points are the vertices of a square but one of the sides equals the diagonal? That would require side=diagonal, which would mean 2side^2=side^2 => side=0, impossible. So okay.
But we need to also consider that the points might be not in convex position? Square is convex. Could a set of four points that satisfy these distances be a crossing quadrilateral? For example, a kite shape? But the distances would not satisfy. Actually consider four points: (0,0), (1,0), (0,2), (1,2). That's a rectangle 1x2, not square. Distances: sides: two of length 1, two of length 2, diagonals sqrt(5). Not our condition.
What about (0,0), (2,0), (1,1), (1,-1)? This is a diamond shape? That's a square rotated? Let's compute: points: (0,0), (2,0), (1,1), (1,-1). Sides: distances between (0,0)-(1,1)=√2, (0,0)-(1,-1)=√2, (2,0)-(1,1)=√2, (2,0)-(1,-1)=√2 => all sides √2. Diagonals: (0,0)-(2,0)=2, (1,1)-(1,-1)=2. So it's a square (actually a diamond oriented). So condition passes. Good.
Now consider (0,0), (1,0), (0,1), (1,1) obviously passes.
So condition works.
Now we need to be careful about integer arithmetic: dists[0], etc. Compare using !=.
Now we also need to consider potential rounding errors? No.
Now, what about case where the four points form a square but are in a different order and some distances are equal? For example, a square with side length s, there are also distances between opposite vertices? Those are the diagonals. There are also distances between non-adjacent vertices? In a square, there are exactly two distinct distances: side and diagonal. However, there are also distances between vertices that are not adjacent? The only pairs are either adjacent (side) or opposite (diagonal). There are no other pairs. So yes.
Thus it's robust.
Now implement.
Potential performance improvement: For each regiment, we could pre-compute positions for each mole, but we already did.
Now double-check input parsing: After reading n, we have 4n lines each with 4 ints. We'll read via iter.
Now test with sample manually by mental? Might be okay.
Now consider possibility of -1 output: if no combo yields square.
Now think about potential pitfalls: The rotation formulas as defined yield integer coordinates, but what if after rotation we get float? No.
Now about product: from itertools import product.
Now test with a simple case: n=1, all moles at same home? Actually if all four moles are at same point? Then cannot form square because need distinct points. Our is_square will detect dist[0]==0? Actually if all points coincide, the smallest distance is 0, fails. So min moves remains INF, output -1. Good.
Now consider a case where one mole's home is not at origin, rotation might produce points that are not at integer? It's integer.
Now I'll write the final code.
But there might be a nuance: The problem says "non-zero area". In a square, area = side^2 >0, so we need side >0. Our condition ensures side >0 because dist[0] >0.
Thus done.
Now we could also simplify: Instead of sorting, we can count distances, etc. But fine.
Now, one more check: The distance check as described might be misled by a configuration where the points are not in a square but distances satisfy the pattern? Let's try to think of a counterexample. Consider a rhombus with angles 60 and 120: sides equal, diagonals: one diagonal length = side * sqrt(2+2cosθ)? Actually compute: In a rhombus with side s and acute angle θ, diagonals are d1 = s * sqrt(2+2cosθ)?? More precisely, using law of cos: d1^2 = s^2 + s^2 - 2s^2 cosθ = 2s^2(1 - cosθ). d2^2 = 2s^2(1 + cosθ). They are not equal unless cosθ=0. So diagonals are not equal. So not our condition.
What about a square with one extra point? No.
Thus condition is sufficient.
Now, let's test with a known tricky shape: a kite that is actually a square? Not.
So ok.
Now finalize code.
Edge Cases: Could there be a scenario where the four points are vertices of a square but due to integer rounding? Already int.
Now ensure we output lines for each regiment.
Now additional thought: The rotations are applied individually per mole. Could we rotate a mole more than 3 times? No, as argued not beneficial.
But there is a nuance: The problem says "moving this mole one time means rotating his position point 90 degrees counter-clockwise around it's home point." So each move is a rotation. So after k moves, the mole has been rotated k times. So indeed, if we rotate 4 times, it's back to original, and counts as 4 moves. So we would never do that because 0 moves is better.
Now confirm that our rotation for k=2 and k=3 are correct:
k=2: 180°: (a - dx, b - dy)
k=3: 270°: (a + dy, b - dx)
Yes.
Now we should also consider that the home (ai, bi) might be different for each mole, so rotations are independent.
Now confirm with the fourth regiment: Let's test with our code mentally? Not needed.
Now check if any scenario where after rotation, the same point appears multiple times, but still could form square? For a square, all vertices must be distinct, so duplicates not allowed. Our is_square will reject because a distance zero will appear.
Now think about possible bug: In is_square, we check dists[0]==dists[1]==dists[2]==dists[3]. But if some distances are equal but not all four? That's fine.
But note that in Python, chained equality like a == b == c means a == b and b == c. So we can write: if dists[0] == dists[1] == dists[2] == dists[3]: ... But careful: In Python, this works as expected because it's comparing each pairwise. However, it's not a single expression with all four? Actually a == b == c == d is equivalent to a == b and b == c and c == d. So that's fine.
But we need to ensure that we don't have case where there are more than 2 distinct distances but the sorting makes the first four equal incorrectly? That can't happen because if there are 3 distinct values, the sorted list may have some equalities but not all four smallest equal. For rectangle with sides a<b, distances sorted: a^2 (2 occurrences), b^2 (2 occurrences), diagonal^2 (2 occurrences). The first four: a^2, a^2, b^2, b^2 => not all equal. So condition fails.
Now check for a square with side s: sorted: [s^2,s^2,s^2,s^2,2s^2,2s^2] passes.
Now consider a degenerate case where the four points form a line in a symmetric pattern: e.g., points at (-1,0), (0,0), (1,0), (2,0). Distances: many, not matching.
Now consider a case where points are at (0,0), (0,1), (1,0), (1,1) but one point is duplicate? Not.
Thus good.
Now potential issue: In Python, reading with sys.stdin.read().split() will split all tokens, we need to ensure the input format exactly as described.
Now we should test with sample:
We'll simulate quickly using mental code? Could trust.
Now final code.
But we may want to include a small optimization: early exit if current sum >= min_moves.
Also we could skip if any two positions after rotation coincide? Not needed.
Now consider possibility of negative coordinates; all fine.
Now consider the case where the square's side squared might be same as diagonal squared if side=0 but we already check >0.
Now about the distance check: we need to be careful about the order of sorting: For a square, sides are smaller than diagonals, so the 4 smallest distances are sides. However, what if side length is larger than diagonal? That's impossible because diagonal length = side * sqrt(2) > side. So yes.
Thus done.
Now I'll implement final solution.
But there is also a known approach: Use squared distances and check 2*side == diag and number of distinct distances = 2.
We can implement more robust: use a Counter of distances. If len(distinct) == 2 and count of smallest == 4 and count of largest == 2 and 2*smallest == largest. That might be even clearer.
Let's do:
def is_square(pts):
dists = []
for i in range(4):
for j in range(i+1,4):
dx = pts[i][0]-pts[j][0]
dy = pts[i][1]-pts[j][1]
d = dxdx + dydy
dists.append(d)
# using set and count
from collections import Counter? But we can just sort.
dists.sort()
# after sorting, sides are the smaller value
if dists[0] == 0:
return False
if dists[0] == dists[1] == dists[2] == dists[3] and dists[4] == dists[5] and 2*dists[0] == dists[4]:
return True
return False
We'll keep that.
Now check: What if there are only 2 distinct values but the counts are 4 and 2 but the order in sorted list could be [side,side,side,side,diag,diag] if side < diag. That's what we assume. But could the diagonal be smaller than side? No.
Thus fine.
Now answer.
Now I'm thinking: Could there be a configuration where the four points are vertices of a square but the distances include some side distances equal to diagonal? No.
Thus final.
Now we should also consider potential floating point if we used sqrt; we don't.
Now implement final solution.
But note: The input coordinates can be up to 10^4, and after rotation coordinates may go up to ±3e4, squares up to 9e8, sum up to 1.8e9, fits in Python int.
Now we can test with some custom cases:
Case 1: All four moles already form a square. Then answer 0.
Input: n=1, four points of a square, homes arbitrary but we can set homes such that no rotation needed: e.g., all homes at (0,0) and positions (0,0),(1,0),(0,1),(1,1) but that's a square? Actually (0,0),(1,0),(0,1),(1,1) is a square with side 1. So set x,y accordingly with home at (0,0) for each. Then answer 0.
Our code will find k0=k1=k2=k3=0 with total 0, and is_square true. min_moves = 0.
Case 2: All four moles at same point, but with homes such that rotating can produce distinct points. Could be possible. But we need to find min moves. Our code should handle.
Now think about the possibility of having to rotate some mole more than 3 times? As argued, no. But let's confirm: Could there be a case where rotating a mole 4 times yields the same as 0, but rotating another mole 0 times yields a configuration that can't be achieved with any combination of 0-3? No, because each mole's position after k moves is determined by k mod 4. So any solution with some ki > 3 can be reduced to ki mod 4 with a lower total sum (since mod 4 gives value 0-3, and total sum reduces by multiples of 4). However, could there be a solution where we need to rotate a mole, say, 2 times and another mole 6 times? That sum is 8, but we could reduce the 6 to 2 (since 6 mod 4 = 2) and sum becomes 4, which is less, so the minimal sum would never use >3. So safe.
Now we are done.
Now produce final code.
But wait: The problem might have constraints: n up to 100, each regiment 4 lines. So reading all tokens fine.
Now, we can write.
One more nuance: In Python, product(range(4), repeat=4) yields 256 combos. For each we compute sum(ks). That's fine.
Now we also need to be careful about global variable naming.
Now final answer.
Let's add a docstring.
Now test with sample input quickly by running mentally? Not needed.
Now we should also check if there is any case where the square can be formed but with points not distinct? Square must have non-zero area, so points distinct.
Now consider if the four points after rotations are not distinct but is_square returns false because dists[0]==0. Good.
Now final code.
Now we might want to speed up is_square by early break? Not needed.
Now we might use tuple for points.
Now I'm ready.
But wait: There's an edge case: Suppose the four points form a square but the distances squared are such that sides and diagonals have the same value? That would require side^2 = diagonal^2 => side = diagonal, impossible for non-zero side because diagonal = side * sqrt(2). So not.
Now think about integer rounding: Since coordinates are integers, side^2 and diagonal^2 are integers. The condition 2side^2 == diagonal^2 can only hold if side^2 is such that 2side^2 is a perfect square. For a square with integer coordinates, side^2 may not be integer? Actually side squared is integer (sum of squares of integer differences). For a square with integer-coordinate vertices, the diagonal squared is also integer, but 2side^2 may not equal diagonal^2 if the square is not axis-aligned? Actually consider a square with vertices (0,0), (1,1), (0,2), (-1,1). This is a diamond with side length sqrt(2). side^2 = 2, diagonal squared = 4, 2side^2=4, matches. So it works.
But for a square with side length sqrt(5) etc, side^2=5, diagonal^2=10. 2*5=10, works. So any square with vertices at integer coordinates will satisfy that because the vector between adjacent vertices (dx,dy) is such that dx^2+dy^2 = side^2, and the diagonal vector is (dx+dy, dy-dx) or something? Actually the diagonal is sum of two orthogonal vectors of equal length. If the two sides are perpendicular and of equal length, then diagonal squared = (dx1+dx2)^2 + (dy1+dy2)^2 = (dx1^2+dy1^2)+(dx2^2+dy2^2)+2(dx1dx2+dy1dy2) = side^2+side^2+0 = 2 side^2, because dot product zero. So condition holds exactly for any square, regardless of integer coordinates. So no rounding issues.
Thus the check is exact.
Now the solution is complete.
Now we produce final answer.
But note: The problem statement: "make the regiments compact" meaning make each regiment's four moles form a square. We treat each regiment independently.
Now final code.
Now we output each answer on separate line.
Now let's write final solution.
But before final, I'll do a quick test with the sample input to ensure our code yields the expected outputs.
Let's simulate the first regiment:
Mole0: (1,1) home (0,0) -> positions: k0=0:(1,1);1:(-1,1);2:(-1,-1);3:(1,-1)
Mole1: (-1,1) home (0,0) -> positions: 0:(-1,1);1:(-1,-1);2:(1,-1);3:(1,1)
Mole2: (-1,1) home (0,0) -> same as mole1
Mole3: (1,-1) home (0,0) -> positions: 0:(1,-1);1:(1,1);2:(-1,1);3:(-1,-1)
Now we need minimal moves: possible combo with sum=0: points: (1,1),(-1,1),(-1,1),(1,-1) -> duplicate (-1,1) -> distances: compute: pairs: (1,1) & (-1,1): 4; (1,1)&(-1,1) again? Actually two moles at (-1,1) are same coordinate, so distances between them is 0. So dists include 0 -> fails. So sum 0 invalid.
Sum=1: e.g., ks=(0,1,0,0): points: mole0: (1,1); mole1: k=1 -> (-1,-1); mole2: ( -1,1); mole3: (1,-1). This yields points: (1,1),(-1,-1),(-1,1),(1,-1). All distinct. Distances: sides? Let's compute distances: between (1,1) and (1,-1): 4; (1,1) and (-1,1):4; (-1,1) and (-1,-1):4; (-1,-1) and (1,-1):4; diagonal: (1,1)-(-1,-1):8; (-1,1)-(1,-1):8. So passes. So min_moves becomes 1. So answer 1.
We need to check if any combination yields square. According to problem answer -1. So our code should output -1.
Third regiment:
Mole0: (1,1) home (0,0) -> as before
Mole1: (-1,1) home (0,0) -> as before
Mole2: (-1,1) home (0,0) -> as before
Mole3: (-1,1) home (0,0) -> same
So all start at either (1,1) or three at (-1,1). Actually Mole0: (1,1); the rest three: (-1,1). So positions: mole0: four positions: (1,1), (-1,1), (-1,-1), (1,-1). Each of moles1-3: four positions: (-1,1), (-1,-1), (1,-1), (1,1). We need to pick one configuration with total moves minimal that yields square. We have essentially four points, each can be any of those four positions, but some duplicates might exist. To form a square, we need four distinct vertices of a square: e.g., (1,1), (-1,1), (-1,-1), (1,-1). So we need to assign each mole to one of these vertices, possibly multiple moles assigned to same vertex? No, they must be distinct. So we need to assign the four moles to the four distinct points. Currently we have three moles that can be at the same starting point (-1,1). So we need to move at least two of them to different vertices, but we have limited rotations. The minimal moves likely 3? Let's check: We need to achieve the set of four distinct vertices. Mole0 can be (1,1) with 0 moves. Mole1 could be (-1,1) with 0 moves, Mole2 could be (-1,-1) with 1 move (rotate 90°), Mole3 could be (1,-1) with 2 moves? Actually for a mole with home (0,0) starting at (-1,1): positions: 0: (-1,1); 1: (-1,-1); 2: (1,-1); 3: (1,1). So to be (-1,-1) takes 1 move, to be (1,-1) takes 2 moves, to be (1,1) takes 3 moves. So we need to assign each of the three duplicate moles to three distinct vertices other than possibly (1,1) already taken? Actually we have four vertices: V1=(1,1), V2=(-1,1), V3=(-1,-1), V4=(1,-1). Mole0 can be V1 (0 moves). We need one mole at V2, one at V3, one at V4. Among the three duplicates, we can assign: one to V2 (0 moves), one to V3 (1 move), one to V4 (2 moves). Total moves=0+0+1+2=3. That's the minimal. Could we do with 2 moves? Possibly assign Mole0 to V2? But Mole0 is (1,1) starting; to be V2 = (-1,1) takes 1 move (rotate 90°? Actually from (1,1) to (-1,1) is rotation by? (1,1) rotated 90 gives (-1,1)? Let's check: (1,1) rot 90 = (-1,1)? Actually (1,1) dx=1,dy=1 -> rot90: (-1,1)? a=0,b=0 -> (-dy,dx)=(-1,1) yes. So Mole0 could become (-1,1) with 1 move. Then one of the duplicates could become (1,1) with 3 moves? That would increase. Or could we have a different square? The only square with these possible positions? The possible positions for each mole are exactly the four vertices of the square centered at origin? Actually for home (0,0) and starting positions (±1,±1) and (±1,∓1)? The reachable positions for each mole are exactly the four points of the square rotated? But they all share the same home (0,0), so the set of positions each can take is exactly those four points. So any square formed must be those four points. So we need to assign each mole to a distinct vertex. That's a matching problem. Since three moles start at (-1,1) and one at (1,1), minimal moves is 3 as computed. So answer 3. Good.
Our code should find total=3.
Fourth regiment: More complex, but answer 3.
Thus all good.
Now code final.
Now we need to ensure we import product.
Now finalize.
But wait: The problem's input may have negative values for coordinates and homes, but our rotation formulas handle them.
Now potential bug: The rotate function uses if/elif. That's fine.
Now also, we may precompute positions for each mole to avoid recomputation in loops.
Now let's produce final answer.
But one more check: In is_square, we assume that the four smallest distances are sides. But is it always that sides are the four smallest? In a square, sides are smaller than diagonals, so yes. But what if the square has side length 0? Not allowed. So fine.
Now I'm confident.
Now we produce final answer.
But we should also consider the possibility of a square with points not in general position but that the six distances include the sides and diagonals but also maybe additional distances if points are not in order? No, only six pairs.
Now final code:
python
import sys
from itertools import product
def rotate(x, y, a, b, k):
dx = x - a
dy = y - b
if k == 0:
return (a + dx, b + dy)
elif k == 1:
return (a - dy, b + dx)
elif k == 2:
return (a - dx, b - dy)
else: # k == 3
return (a + dy, b - dx)
def is_square(pts):
dists = []
for i in range(4):
x1, y1 = pts[i]
for j in range(i+1, 4):
x2, y2 = pts[j]
dx = x1 - x2
dy = y1 - y2
d = dx*dx + dy*dy
dists.append(d)
dists.sort()
# Check for square: four equal sides, two equal diagonals, and diagonal^2 = 2 * side^2
if dists[0] == 0:
return False
if dists[0] == dists[1] == dists[2] == dists[3] and dists[4] == dists[5] and 2*dists[0] == dists[4]:
return True
return False
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
n = int(next(it))
out = []
for _ in range(n):
pos = []
for _ in range(4):
x = int(next(it)); y = int(next(it)); a = int(next(it</think>