#B4307. Stone Row Color Matching
Stone Row Color Matching
Stone Row Color Matching
There are two rows of stones, each containing (n) stones arranged from left to right. Each stone is either yellow (represented by (1)) or green (represented by (0)). In one operation, you can swap any stone from the first row with any stone from the second row. The goal is to make every column (i.e. the stones at the same index in each row) have the same color. Determine the minimum number of swaps needed to achieve this. If it is impossible to make every column have the same color regardless of the number of swaps, output (-1).
Important notes:
- The input begins with an integer \(n\) (\(1 \leq n \leq 10^5\)).
- The next line contains \(n\) integers (each either \(0\) or \(1\)) representing the first row.
- The following line contains \(n\) integers (each either \(0\) or \(1\)) representing the second row.
Analysis:
Let a column be in one of three states:
- Matched: both stones have the same color.
- Mismatched of type \((1, 0)\): the first row is \(1\) and the second row is \(0\).
- Mismatched of type \((0, 1)\): the first row is \(0\) and the second row is \(1\).
If \(d = 0\), no swaps are needed. If \(d\) is even, the minimum number of swaps is \(d\) (each swap can fix two mismatched columns by pairing them within the same type).
If \(d\) is odd, then one column of each mismatch type remains unpaired. In this case, if there exists at least one initially matched column, you can use that column as an auxiliary to fix the remaining pair with 2 extra swaps. Thus, the answer becomes \(d + 1\). If no such auxiliary (matched column) exists, then it is impossible to fix the configuration and you should output \(-1\).
Formula Summary: \[ \text{Let } d = \#(1,0) = \#(0,1).\] \] \[ \text{Answer} = \begin{cases} 0, & \text{if } d = 0; \\ \,d, & \text{if } d \text{ is even}; \\ \,d + 1, & \text{if } d \text{ is odd and there exists at least one matched column}; \\ -1, & \text{otherwise.} \end{cases} \]
inputFormat
The first line contains a single integer (n) indicating the number of stones in each row. The second line contains (n) space-separated integers (each either 0 or 1) representing the colors of the stones in the first row. The third line contains (n) space-separated integers (each either 0 or 1) representing the colors of the stones in the second row.
outputFormat
Output a single integer which is the minimum number of swaps needed to make each column have stones of the same color. If it is impossible, output (-1).
sample
3
1 0 1
0 1 1
2