exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | f4e2f94aeae99a934854262cec76b36b | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.Scanner;
public class Main {
public static long hs(int[] array) {
long cnt = 0;
int index = 1;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] % 2 == array[i + 1] % 2) {
for (int j = Math.max(index + 1,i+2); j < array.length; j++) {
if (array[j] % 2 != array[i + 1] % 2) {
index = j;
break;
}
}
cnt += index - (i + 1);
int temp = array[i + 1];
array[i + 1] = array[index];
array[index] = temp;
} else {
continue;
}
}
return cnt;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
int n = scanner.nextInt();
int[] array = new int[n];
int[] na = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
na[i] = array[i];
}
int oscnt = 0;
int jscnt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
oscnt++;
} else {
jscnt++;
}
}
long cnt = 0;
long osjs = 0;
long jsjs = 0;
if (oscnt == jscnt) {
if (array[0] % 2 == 0) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] % 2 != 0) {
index = i;
break;
}
}
jsjs += index;
int temp = array[0];
array[0] = array[index];
array[index] = temp;
jsjs += hs(array);
osjs += hs(na);
} else {
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] % 2 == 0) {
index = i;
break;
}
}
osjs += index;
int temp = array[0];
array[0] = array[index];
array[index] = temp;
osjs += hs(array);
jsjs += hs(na);
}
System.out.println(Math.min(jsjs, osjs));
} else if (oscnt == jscnt + 1) {
if (array[0] % 2 != 0) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] % 2 == 0) {
index = i;
break;
}
}
cnt += index;
int temp = array[0];
array[0] = array[index];
array[index] = temp;
}
cnt += hs(array);
System.out.println(cnt);
} else if (oscnt + 1 == jscnt) {
if (array[0] % 2 == 0) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] % 2 != 0) {
index = i;
break;
}
}
cnt += index;
int temp = array[0];
array[0] = array[index];
array[index] = temp;
}
cnt += hs(array);
System.out.println(cnt);
} else {
System.out.println(-1);
}
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 58e68649e53218859fcbc05971287d22 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Iterator;
public class First {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int T = fs.nextInt();
for (int tt = 0; tt < T; tt++) {
solve(fs);
}
}
static void solve(FastScanner fs)
{
int n=fs.nextInt();
int[] arr=takeInt(n, fs);
int[] orig=new int[n];
Queue<Integer> eq=new LinkedList<>();
Queue<Integer> oq=new LinkedList<>();
for(int i=0;i<n;++i)
{
orig[i]=arr[i];
if(arr[i]%2==0)
eq.add(i);
else
oq.add(i);
}
long ans=Integer.MAX_VALUE, even=0, odd=0;
for(int ele: arr)
if(ele%2==0)
even++;
else
odd++;
if((n%2==0 && even!=odd) || (n%2==1 && Math.abs(even-odd)!=1))
{
pn(-1); return;
}
long totalSwaps1=0, totalSwaps2=0;
boolean swap1=false, swap2=false;
if(odd>=even)
{
swap1=true;
//o e o e o
int i=0;
while(i<n)
{
if(((i+1)%2==1 && arr[i]%2==1) || ((i+1)%2==0 && arr[i]%2==0))
i++;
else
{
if((i+1)%2==1) // no should be odd
{
while(!oq.isEmpty() && oq.peek()<i)
{
oq.remove();
}
int j=oq.remove();
totalSwaps1+=(long)(j-i);
swap(arr, i, j);
}
else // no should be even
{
while(!eq.isEmpty() && eq.peek()<i)
{
eq.remove();
}
int j=eq.remove();
totalSwaps1+=(long)(j-i);
swap(arr, i, j);
}
i+=2;
}
}
}
eq.clear();
oq.clear();
for(int i=0;i<n;++i)
{
if(orig[i]%2==0)
eq.add(i);
else
oq.add(i);
}
if(even>=odd)
{
swap2=true;
//e o e o e
int i=0;
while(i<n)
{
if((i%2==1 && orig[i]%2==1) || (i%2==0 && orig[i]%2==0))
{
i++;
}
else
{
if((i)%2==1) // no should be odd
{
while(!oq.isEmpty() && oq.peek()<i)
{
oq.remove();
}
int j=oq.remove();
totalSwaps2+=(long)(j-i);
swap(orig, i, j);
}
else // no should be even
{
while(!eq.isEmpty() && eq.peek()<i)
{
eq.remove();
}
int j=eq.remove();
totalSwaps2+=(long)(j-i);
swap(orig, i, j);
}
i+=2;
}
}
}
if(swap1)
ans=Math.min(ans, totalSwaps1);
if(swap2)
ans=Math.min(ans, totalSwaps2);
if(ans==Integer.MAX_VALUE)
pn(-1);
else
pn(ans);
}
static int MOD=(int)(1e9+7);
static void swap(int[] arr, int i, int j)
{
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static void pn(Object o) { System.out.println(o); }
static void p(Object o) { System.out.print(o); }
static void flush() { System.out.flush(); }
static void debugInt(int[] arr)
{
for(int i=0;i<arr.length;++i)
System.out.print(arr[i]+" ");
System.out.println();
}
static void debugIntInt(int[][] arr)
{
for(int i=0;i<arr.length;++i)
{
for(int j=0;j<arr[0].length;++j)
System.out.print(arr[i][j]+" ");
System.out.println();
}
System.out.println();
}
static void debugLong(long[] arr)
{
for(int i=0;i<arr.length;++i)
System.out.print(arr[i]+" ");
System.out.println();
}
static void debugLongLong(long[][] arr)
{
for(int i=0;i<arr.length;++i)
{
for(int j=0;j<arr[0].length;++j)
System.out.print(arr[i][j]+" ");
System.out.println();
}
System.out.println();
}
static long[] takeLong(int n, FastScanner fs)
{
long[] arr=new long[n];
for(int i=0;i<n;++i)
arr[i]=fs.nextLong();
return arr;
}
static long[][] takeLongLong(int m, int n, FastScanner fs)
{
long[][] arr=new long[m][n];
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
arr[i][j]=fs.nextLong();
return arr;
}
static int[] takeInt(int n, FastScanner fs)
{
int[] arr=new int[n];
for(int i=0;i<n;++i)
arr[i]=fs.nextInt();
return arr;
}
static int[][] takeIntInt(int m, int n, FastScanner fs)
{
int[][] arr=new int[m][n];
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
arr[i][j]=fs.nextInt();
return arr;
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
class Pair
{
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a83745d1477d4cace3d923216ef027b1 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class codeforcesA{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]){
FastReader sc=new FastReader();
int t=sc.nextInt();
StringBuilder sb=new StringBuilder();
while(t-->0){
int n=sc.nextInt();
int ar[]=new int[n];
int odd=0,even=0;
int ans=Integer.MAX_VALUE;
for(int i=0;i<n;i++){ar[i]=sc.nextInt();if(ar[i]%2==0){even++;}
else{odd++;}
}
if(n%2==0){
if(odd==even){
int ans1=0;
Queue<Integer> q1=new ArrayDeque<>();
Queue<Integer> q2=new ArrayDeque<>();
for(int i=0;i<n;i++){
if(i%2==0 && ar[i]%2==1){q1.add(i);}
if(i%2==1 && ar[i]%2==0){q2.add(i);}
}
while(!q1.isEmpty()){
ans1+=Math.abs(q1.poll()-q2.poll());
}
q1=new ArrayDeque<>();
q2=new ArrayDeque<>();
int ans2=0;
for(int i=0;i<n;i++){
if(i%2==1 && ar[i]%2==1){q1.add(i);}
if(i%2==0 && ar[i]%2==0){q2.add(i);}
}
while(!q1.isEmpty()){
ans2+=Math.abs(q1.poll()-q2.poll());
}
ans=Math.min(ans1,ans2);
}
}
else{
if(Math.abs(odd-even)==1){
int ans1=0;
int x=0,y=1;
if(odd>even){x=1;y=0;}
Queue<Integer> q1=new ArrayDeque<>();
Queue<Integer> q2=new ArrayDeque<>();
for(int i=0;i<n;i++){
if(i%2==0 && ar[i]%2==y){q1.add(i);}
if(i%2==1 && ar[i]%2==x){q2.add(i);}
}
while(!q1.isEmpty()){
ans1+=Math.abs(q1.poll()-q2.poll());
}
ans=ans1;
}
}
if(ans==Integer.MAX_VALUE){ans=-1;}
sb.append(ans+"\n");
}
System.out.print(sb.toString());
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5bd80f52383b07db7abff3eaf49a7fd6 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | /**
* check out my youtube channel sh0rkyboy
* https://tinyurl.com/zdxe2y4z
* I do screencasts, solutions, and other fun stuff in the future
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.max;
public class EdA {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] largewang) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-->0) {
int n = sc.nextInt();
int[] arr = readArrayInt(n);
int odd = 0;
int even = 0;
for(int j : arr) {
if (j%2 == 0)
even++;
else
odd++;
}
if (abs(odd-even) <=1 ) {
long min = Long.MAX_VALUE;
if (odd >= even) {
long od = 0;
int count = 0;
for(int j = 0;j<n;j++){
if (arr[j] %2 == 1){
od += (long)abs(j-count);
count+=2;
}
}
long el = 0;
count = 1;
for(int j = 0;j<n;j++){
if (arr[j] %2 == 0){
el += (long)abs(j-count);
count+=2;
}
}
min = min(min, od);
min = min(min, el);
}
if (even >= odd) {
int sum = 0;
long el = 0;
int count = 0;
for(int j = 0;j<n;j++){
if (arr[j] %2 == 0){
el += (long)abs(j-count);
count+=2;
}
}
long od = 0;
count = 0;
for(int j = 0;j<n;j++){
if (arr[j] %2 == 1){
od += (long)abs(j-count);
count+=2;
}
}
min = min(min, el);
min = min(min, el);
}
out.println(min);
} else {
out.println(-1);
}
}
out.close();
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 7be79de28e8d7c0e1b0a03f0cd289321 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.*;
import static java.lang.System.out;
import static java.lang.Math.*;
public class pre346 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class MultiSet<K> {
TreeMap<K, Integer> map;
MultiSet() {
map = new TreeMap<>();
}
void add(K a) {
map.put(a, map.getOrDefault(a, 0) + 1);
}
boolean contains(K a) {
return map.containsKey(a);
}
void remove(K a) {
map.put(a, map.get(a) - 1);
if (map.get(a) == 0) map.remove(a);
}
int occrence(K a) {
return map.get(a);
}
K floor(K a) {
return map.floorKey(a);
}
K ceil(K a) {
return map.ceilingKey(a);
}
@Override
public String toString() {
ArrayList<K> set = new ArrayList<>();
for (Map.Entry<K, Integer> i : map.entrySet()) {
for (int j = 1; j <= i.getValue(); j++) set.add(i.getKey());
}
return set.toString();
}
}
static class Pair<K, V> {
K value1;
V value2;
Pair(K a, V b) {
value1 = a;
value2 = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equals(this.value1, p.value1) && Objects.equals(this.value2, p.value2);
}
@Override
public int hashCode() {
int result = this.value1.hashCode();
result = 31 * result + this.value2.hashCode();
return result;
}
@Override
public String toString() {
return ("[" + value1 + " <=> " + value2 + "]");
}
}
static ArrayList<Integer> primes;
static void setPrimes(int n) {
boolean p[] = new boolean[n];
Arrays.fill(p, true);
for (int i = 2; i < p.length; i++) {
if (p[i]) {
primes.add(i);
for (int j = i * 2; j < p.length; j += i) p[j] = false;
}
}
}
static int mod = (int) (1e9 + 7);
static int gcd(int a, int b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static void main(String args[]) {
FastReader obj = new FastReader();
int tc = obj.nextInt();
while(tc--!=0){
int n = obj.nextInt(),arr[] = new int[n],arr2[] = new int[n];
for(int i=0;i<n;i++) arr2[i] = arr[i] = obj.nextInt();
int even = 0,odd = 0;
for(int i=0;i<n;i++) if(arr[i]%2==0) even++; else odd++;
if(even+1==odd || odd+1==even || even==odd){
if(even>odd){
long a1= 0,cu = 0;
for(int i=0;i<n;i++){
if(arr[i]%2==0) {
a1+=abs(i-cu);
cu+=2;
}
}
out.println(a1);
}else if(odd>even){
long a1 = 0,cu = 0;
for(int i=0;i<n;i++){
if(arr[i]%2==1){
a1+=abs(i-cu);
cu+=2;
}
}
out.println(a1);
}else{
long a1 = 0,a2 = 0,cu = 0;
for(int i=0;i<n;i++){
if(arr[i]%2==0){
a1+=abs(i-cu);
cu+=2;
}
}
cu = 0;
for(int i=0;i<n;i++){
if(arr[i]%2==1){
a2+=abs(i-cu);
cu+=2;
}
}
out.println(min(a1,a2));
}
}else out.println(-1);
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | bf271ed6b6afbc333e696fbe7933cf3e | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.Scanner;
/**
*
* @author devya
*/
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
int test=in.nextInt();
while(test-->0){
int n=in.nextInt();
long arr[]=new long[n];
int odd=0;
int even=0;
for(int i=0;i<n;i++){
arr[i]=in.nextLong();
arr[i]=arr[i]%2;
if(arr[i]==0)
even++;
else
odd++;
}
if(Math.abs(even-odd)>1){
System.out.println(-1);
}
else if(even>odd){
System.out.println(function(arr,n,0));
}
else if(odd>even){
System.out.println(function(arr,n,1));
}
else{
System.out.println(Math.min(function(arr,n,0),function(arr,n,1)));
}
}
}
public static int function(long arr[],int n,int index){
int count=0;
for(int i=0;i<n;i++){
if(arr[i]==0){
count+=Math.abs(i-index);
index+=2;
}
}
return count;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | bea68f286615140fabb8a981cea3339d | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.*;
public class A {
BufferedReader br;
StringTokenizer st;
public A(){ // constructor
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
static void sort(int[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i = 0; i < n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static class Pair{
String str;
int sq_no;
Pair(String str, int sq_no){
this.str = str;
this.sq_no = sq_no;
}
}
static long gcd_long(long a, long b) {
if(b == 0) {
return a;
}
return gcd_long(b, a % b);
}
static long mod = (long)1e9 + 7;
static long mul_long = 1;
public static void main(String[] args) throws Exception{
A in = new A();
PrintWriter out = new PrintWriter(System.out);
// hard work will power dedication
// Rippling CNIL Spri GOOG.
int test = in.nextInt();
while(test-- > 0) {
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = in.nextInt();
arr[i] = arr[i] & 1;
}
ArrayList<Integer> zero = new ArrayList<>();
ArrayList<Integer> one = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(arr[i] == 0) {
zero.add(i);
}
else {
one.add(i);
}
}
if(Math.abs(zero.size() - one.size()) > 1) {
out.println(-1);
}
else {
// 010101..
long min = (long)1e14;
if(zero.size() >= one.size()) {
min = cal(zero, one, 0, 1);
}
// 101010..
if(one.size() >= zero.size()) {
min = Math.min(min, cal(zero, one, 1, 0));
}
out.println(min / 2);
}
}
out.flush();
out.close();
}
static long cal(ArrayList<Integer> zero, ArrayList<Integer> one, int o, int z) {
long ans = 0;
for(int ele : zero) {
ans = ans + Math.abs(ele - o);
o = o + 2;
}
for(int ele : one) {
ans = ans + Math.abs(ele - z);
z = z + 2;
}
return ans;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 54d2e963dabe4b331f22347aa5f46c69 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // package MyJava;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import static java.lang.Math.min;
import static java.lang.Math.max;
import static java.lang.Math.abs;
public class Main {
static boolean DEBUG = false;
public static void main(String[] args) throws IOException {
Comparator<pair> com = (p1,
p2) -> ((p1.first > p2.first || (p1.first == p2.first && p1.second > p2.second)) ? 1 : -1);
if (System.getProperty("ONLINE_JUDGE") == null) {
// System.setIn(new FileInputStream(new File("D://program//javaCPEclipse//MyJava//src//MyJava//input.txt")));
// System.setOut(new PrintStream(new File("output.txt")));
// System.setErr(new PrintStream(new File("D://program//javaCPEclipse//MyJava//src//MyJava//error.txt")));
DEBUG = true;
}
Reader fs = new Reader();
PrintWriter pw = new PrintWriter(System.out, true);
int t = fs.nextInt();
while (t-- > 0) {
int n = fs.nextInt();
int[] a = fs.readArray(n, 0);
for (int i = 0; i < n; i++) {
a[i] &= 1;
}
int tot = 0;
for (int i = 0; i < n; i++) {
tot += a[i];
}
ArrayList<Integer> ones = new ArrayList<Integer>();
ArrayList<Integer> zeros = new ArrayList<Integer>();
ArrayList<Integer> req_one = new ArrayList<Integer>();
ArrayList<Integer> req_zer = new ArrayList<Integer>();
int next_ev = 0, next_od = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 1) {
ones.add(i);
req_one.add(next_od);
next_od += 2;
} else {
zeros.add(i);
req_zer.add(next_ev);
next_ev += 2;
}
}
if (n % 2 == 0 && tot == n / 2) {
int ans1 = 0, ans2 = 0;
for (int i = 0; i < ones.size(); i++) {
ans1 += abs(ones.get(i) - req_one.get(i));
}
for (int i = 0; i < zeros.size(); i++) {
ans2 += abs(zeros.get(i) - req_zer.get(i));
}
pw.println(min(ans1, ans2));
} else if (n % 2 == 1 && tot == n / 2 + 1) {
int ans = 0;
for (int i = 0; i < ones.size(); i++) {
ans += abs(ones.get(i) - req_one.get(i));
}
pw.println(ans);
} else if (n % 2 == 1 && tot == n / 2) {
int ans = 0;
for (int i = 0; i < zeros.size(); i++) {
ans += abs(zeros.get(i) - req_zer.get(i));
}
pw.println(ans);
} else {
pw.println(-1);
}
}
fs.close();
pw.close();
}
static <T> void debug(HashSet<Integer> a, String l) {
if (DEBUG) {
System.err.println(l + " -> ");
System.err.println(a);
}
}
static void debug(String a, String l) {
if (DEBUG) {
System.err.println(l + " -> " + a);
}
}
static void debug(StringBuilder a, String l) {
if (DEBUG) {
System.err.println(l + " -> " + a);
}
}
static <T extends Number, V extends T> void debug(HashMap<T, V> a, String l) {
if (DEBUG) {
System.err.println(l + " -> ");
System.err.println(a);
}
}
static <T extends Number> void debug(T a, String l) {
if (DEBUG) {
System.err.println(l + " -> " + a);
}
}
static <T extends Number> void debug(T[] a, String l) {
if (DEBUG) {
System.err.print(l + " -> \n" + "[ ");
for (int i = 0; i < a.length; i++) {
System.err.print(a[i] + " ");
}
System.err.println("]");
}
}
static <T> void debug(ArrayList<T> a, String l) {
if (DEBUG) {
System.err.print(l + " -> ");
System.err.print("[ ");
for (T q : a) {
System.err.print(q + " ");
}
System.err.println("]");
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() throws IOException {
byte[] buf = new byte[100009];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c <= ' ') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public int[] readArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] readArray(int n, int x) throws IOException {
int[] arr = new int[n + x];
for (int i = x; i < n + x; i++) {
arr[i] = nextInt();
}
return arr;
}
public ArrayList<Integer> readList(int n) throws IOException {
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
a.add(nextInt());
}
return a;
}
public int[][] read2Array(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static int pow(int base, int index) {
if (index == 0) {
return 1;
} else if (index % 2 == 0) {
return pow(base * base, index / 2);
} else {
return base * pow(base * base, ((index - 1) / 2));
}
}
public static long pow(long base, long index) {
if (index == 0) {
return 1;
} else if (index % 2 == 0) {
return pow(base * base, index / 2);
} else {
return base * pow(base * base, ((index - 1) / 2));
}
}
static class pair {
int first;
int second;
pair() {
this.first = 0;
this.second = 0;
}
pair(int first, int second) {
this.first = first;
this.second = second;
}
void make_pair(int first, int second) {
this.first = first;
this.second = second;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 8850c2153b6fbeb7b0f0a1c744c6aa90 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // package MyJava;
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static final long INF = Long.MAX_VALUE/2;
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] arr = readArr(N, infile, st);
for(int i=0; i < N; i++)
arr[i] &= 1;
int tot = 0;
for(int x: arr)
tot += x;
ArrayList<Integer> zeros = new ArrayList<Integer>();
ArrayList<Integer> ones = new ArrayList<Integer>();
for(int i=0; i < N; i++)
{
if(arr[i] == 0)
zeros.add(i);
else
ones.add(i);
}
if(N%2 == 0 && tot == N/2)
{
int[] lol = new int[N];
int p0 = 0, p1 = 0, boof = 1;
for(int i=0; i < N; i++)
{
if((i&1) == 0)
lol[zeros.get(p0++)] = boof++;
else
lol[ones.get(p1++)] = boof++;
}
long res = inversions(lol);
lol = new int[N];
p0 = p1 = boof = 0;
boof = 1;
for(int i=1; i <= N; i++)
{
if((i&1) == 0)
lol[zeros.get(p0++)] = boof++;
else
lol[ones.get(p1++)] = boof++;
}
res = min(res, inversions(lol));
sb.append(res+"\n");
}
else if(N%2 == 1 && tot == N/2)
{
//start on 0
int[] lol = new int[N];
int p0 = 0, p1 = 0, boof = 1;
for(int i=0; i < N; i++)
{
if((i&1) == 0)
lol[zeros.get(p0++)] = boof++;
else
lol[ones.get(p1++)] = boof++;
}
long res = inversions(lol);
sb.append(res+"\n");
}
else if(N%2 == 1 && tot == N/2+1)
{
int[] lol = new int[N];
int p0 = 0, p1 = 0, boof = 1;
for(int i=1; i <= N; i++)
{
if((i&1) == 0)
lol[zeros.get(p0++)] = boof++;
else
lol[ones.get(p1++)] = boof++;
}
long res = inversions(lol);
sb.append(res+"\n");
}
else
sb.append("-1\n");
}
System.out.print(sb);
}
public static long inversions(int[] arr)
{
int N = arr.length;
FenwickTree bit = new FenwickTree(N+3);
long res = 0;
for(int x: arr)
{
res += bit.find(x, N);
bit.add(x, 1);
}
return res;
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
class FenwickTree
{
//Binary Indexed Tree
//1 indexed
public int[] tree;
public int size;
public FenwickTree(int size)
{
this.size = size;
tree = new int[size+5];
}
public void add(int i, int v)
{
while(i <= size)
{
tree[i] += v;
i += i&-i;
}
}
public int find(int i)
{
int res = 0;
while(i >= 1)
{
res += tree[i];
i -= i&-i;
}
return res;
}
public int find(int l, int r)
{
return find(r)-find(l-1);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 8fcf565b489afd8c3b85e1252d7149f7 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer out = new StringBuffer();
int T = in.nextInt();
OUTER:
while (T-- > 0) {
int n = in.nextInt();
ArrayList<Integer> list[] = new ArrayList[2];
for(int i=0; i<2; i++) {
list[i] = new ArrayList<>();
}
for(int i=0; i<n; i++) {
list[in.nextInt()%2].add(i);
}
if(Math.abs(list[0].size()-list[1].size())>1) {
out.append("-1");
} else {
long min=Long.MAX_VALUE;
if(list[0].size()>=list[1].size()) {
min=Math.min(min, findDiff(list, 0, 1));
}
if(list[0].size()<=list[1].size()) {
min=Math.min(min, findDiff(list, 1, 0));
}
out.append(min/2L);
}
out.append("\n");
}
System.out.print(out);
}
private static long findDiff(ArrayList<Integer> list[], int s0, int s1) {
long sum=0;
for(int item: list[0]) {
sum+=Math.abs(item-s0);
s0+=2;
}
for(int item: list[1]) {
sum+=Math.abs(item-s1);
s1+=2;
}
return sum;
}
private static long gcd(long a, long b) {
if (a==0)
return b;
return gcd(b%a, a);
}
private static int toInt(String s) {
return Integer.parseInt(s);
}
private static long toLong(String s) {
return Long.parseLong(s);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 8916cf5d81dcfaa95ce8af4ec00d5397 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class B implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new B(), "SwapnilGanguly", 1 << 24).start();
}
public void run() {
SwapScanner sc = new SwapScanner();
PrintWriter pr = new PrintWriter(System.out);
int T = sc.nextInt();
while (T-- > 0) {
int n = sc.nextInt();
int[] ar = new int[n + 1];
List<Integer> even = new ArrayList<>();
List<Integer> odd = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ar[i] = sc.nextInt();
if (ar[i] % 2 == 0)
even.add(i);
else
odd.add(i);
}
if (Math.abs(even.size() - odd.size()) > 1) {
pr.println(-1);
continue;
}
List<Integer> start = null, end = null;
long ans = 0L;
if (even.size() == odd.size()) {
long ans1 = helper(even, odd, ar);
long ans2 = helper(odd, even, ar);
ans = Math.min(ans1, ans2);
}
else {
if (even.size() > odd.size()) {
start = new ArrayList<>(even);
end = new ArrayList<>(odd);
}
else {
start = new ArrayList<>(odd);
end = new ArrayList<>(even);
}
ans = helper(start, end, ar);
}
pr.println(ans);
}
pr.close();
}
public static long helper(List<Integer> start, List<Integer> end, int[] ar) {
int curr = 1;
long moves = 0L;
for (int i = 0; i < start.size(); i++) {
// System.out.println(start.get(i) + " " + curr);
moves += (long) Math.abs(start.get(i) - curr);
curr += 2;
}
return moves;
}
public static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
public static class SwapScanner {
BufferedReader br;
StringTokenizer st;
public SwapScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = nextInt();
return ar;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a5c9bcf814e1d2075f4a3e0395fce513 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
FastReader f = new FastReader();
StringBuffer sb=new StringBuffer();
int test=f.nextInt();
while(test-->0)
{
int n=f.nextInt();
int a[]=new int[n],a2[]=new int[n];
for(int i=0;i<n;i++)
a[i]=a2[i]=f.nextInt()%2;
TreeSet<Integer> odd=new TreeSet<Integer>(),even=new TreeSet<>();
for(int i=0;i<n;i++)
{
if(a[i]%2==0)
even.add(i);
if(a[i]%2!=0)
odd.add(i);
}
if(Math.abs(even.size()-odd.size())>1)
{
sb.append("-1\n");
continue;
}
int ans=0;
for(int i=0;i<n;i++)
{
// System.out.println("odd = "+odd);
// System.out.println("even = "+even);
if(i%2==0)
{
// System.out.println("need even = "+a[i]);
if(a[i]!=0)
{
if(even.isEmpty())
{
ans=Integer.MAX_VALUE;
break;
}
int idx=even.pollFirst();
// System.out.println("polled = "+idx);
a[i]=0;
a[idx]=1;
odd.add(idx);
odd.remove(i);
ans+=Math.abs(idx-i);
// System.out.println("adding = "+Math.abs(idx-i));
}
else
even.remove(i);
}
else
{
if(a[i]!=1)
{
if(odd.isEmpty())
{
ans=Integer.MAX_VALUE;
break;
}
int idx=odd.pollFirst();
a[i]=1;
a[idx]=0;
even.add(idx);
even.remove(i);
ans+=Math.abs(idx-i);
}
else
odd.remove(i);
}
}
odd=new TreeSet<Integer>();even=new TreeSet<>();
for(int i=0;i<n;i++)
{
if(a2[i]%2==0)
even.add(i);
if(a2[i]%2!=0)
odd.add(i);
}
//starting odd here
int ans2=0;
for(int i=0;i<n;i++)
{
if(i%2==0)
{
//we want odd here
if(a2[i]!=1)
{
if(odd.isEmpty())
{
ans2=Integer.MAX_VALUE;
break;
}
int idx=odd.pollFirst();
a2[i]=1;
a2[idx]=0;
even.add(idx);
even.remove(i);
ans2+=Math.abs(idx-i);
}
else
odd.remove(i);
}
else
{
//we want even here
if(a2[i]!=0)
{
if(even.isEmpty())
{
ans2=Integer.MAX_VALUE;
break;
}
int idx=even.pollFirst();
a2[i]=0;
a2[idx]=1;
odd.add(idx);
odd.remove(i);
ans2+=Math.abs(idx-i);
}
else
even.remove(i);
}
}
// System.out.println("ans = "+ans);
// System.out.println("ans2 = "+ans2);
sb.append(Math.min(ans,ans2)+"\n");
}
System.out.println(sb);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6992fd698ec4c56da825fc4b28b668b0 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.util.Scanner;
public class B {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n=sc.nextInt();
int a[]=new int[n];
int z=0,o=0;
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
a[i]=a[i]%2;
if(a[i]==0)
z++;
else
o++;
}
int b[]=new int[n];
if(Math.abs(o-z)>=2)
{
System.out.println("-1");
continue;
}
if(n%2==1)
{
if(o>z)
{
for(int i=0;i<n;i++)
{
if(i%2==0)
b[i]=1;
else
b[i]=0;
}
int i=0,j=0;int c=0;
while (i<n&&j<n)
{
if(a[i]==0)
i++;
if(b[j]==0)
j++;
if(i<n&&j<n&&a[i]==1&&b[j]==1) {
c += Math.abs(j - i);
i++;j++; }
}
System.out.println(c);
}
if(o<z)
{
for(int i=0;i<n;i++)
{
if(i%2==0)
b[i]=0;
else
b[i]=1;
}
int i=0,j=0;int c=0;
while (i<n&&j<n)
{
if(a[i]==1)
i++;
if(b[j]==1)
j++;
if(i<n&&j<n&&a[i]==0&&b[j]==0) {
c += Math.abs(j - i);
i++;j++;
}
}
System.out.println(c);
}
}
else
{
int c=0;
for (int ii = 0; ii < n; ii++) {
if (ii % 2 == 0)
b[ii] = 0;
else
b[ii] = 1;
}
int ii=0,jj=0;
while (ii<n&&jj<n)
{
if(a[ii]==1)
ii++;
if(b[jj]==1)
jj++;
if(ii<n&&jj<n&&a[ii]==0&&b[jj]==0) {
c += Math.abs(jj - ii);
ii++;jj++;
}
}
int c1=0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0)
b[i] = 1;
else
b[i] = 0;
}
int i=0,j=0;
while (i<n&&j<n)
{
if(a[i]==0)
i++;
if(b[j]==0)
j++;
if(i<n&&j<n&&a[i]==1&&b[j]==1) {
c1 += Math.abs(j - i);
i++;j++;
}
}
System.out.println(Math.min(c,c1));
// System.out.println(Math.min(c1,c));
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | fa37a501b0ea244e559f37f03e5de146 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class DiffParity {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
long[] array = new long[n];
for(int i=0;i<n;i++)
array[i] = (sc.nextLong())%2;
if(n==1)
System.out.println(0);
else
{
int odd = 0, even = 0;
for(int i=0;i<n;i++)
{
if(array[i]==0)
even++;
else
odd++;
}
if((n%2==0 && even != odd) || (n%2==1 && Math.abs(odd-even)!=1))
System.out.println("-1");
else if(even==odd)
{
int index = 0;
long count1 = 0;
for(int i=0;i<n;i++)
{
if(array[i]==0)
{
count1 += Math.abs(i-index);
index += 2;
}
}
index = 1;
long count2 = 0;
for(int i=0;i<n;i++)
{
if(array[i]==0)
{
count2 += Math.abs(i-index);
index += 2;
}
}
System.out.println(Math.min(count1, count2));
}
else if(odd>even)
{
int index = 1;
long count = 0;
for(int i=0;i<n;i++)
{
if(array[i]==0)
{
count += Math.abs(i-index);
index += 2;
}
}
System.out.println(count);
}
else
{
int index = 0;
long count = 0;
for(int i=0;i<n;i++)
{
if(array[i]==0)
{
count += Math.abs(i-index);
index += 2;
}
}
System.out.println(count);
}
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | c4795e26379539c612ed7372f3830b24 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.util.Scanner;
public class cfContest1556 {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
int n = scan.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = scan.nextInt() % 2;
}
int cz = 0;
int oz = 0;
for (int i = 1; i <= n; i++) {
if (a[i] == 0) {
++cz;
} else {
++oz;
}
}
long res = 0;
if (cz == oz + 1) {
a[0] = 1;
int o = 0;
int z = 0;
for (int i = 2; i <= n; i++) {
if (a[i] == 0) {
z = i;
break;
}
}
for (int i = 2; i <= n; i++) {
if (a[i] == 1) {
o = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (a[i - 1] == a[i]) {
if (a[i] == 1) {
if (z <= i) {
while ((z <= i) || (z <= n && a[z] != 0)) {
++z;
}
}
res += (z - i);
a[i] = 0;
a[z] = 1;
while (z < n && a[z] != 0) {
++z;
}
} else {
if (o <= i) {
while ((o <= i) || (o <= n && a[o] != 1)) {
++o;
}
}
res += (o - i);
a[i] = 1;
a[o] = 0;
while (o <= n && a[o] != 1) {
++o;
}
}
}
}
System.out.println(res);
} else if (oz == cz + 1) {
a[0] = 0;
int o = 0;
int z = 0;
for (int i = 2; i <= n; i++) {
if (a[i] == 0) {
z = i;
break;
}
}
for (int i = 2; i <= n; i++) {
if (a[i] == 1) {
o = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (a[i - 1] == a[i]) {
if (a[i] == 1) {
if (z <= i) {
while ((z <= i) || (z <= n && a[z] != 0)) {
++z;
}
}
res += (z - i);
a[i] = 0;
a[z] = 1;
while (z < n && a[z] != 0) {
++z;
}
} else {
if (o <= i) {
while ((o <= i) || (o <= n && a[o] != 1)) {
++o;
}
}
res += (o - i);
a[i] = 1;
a[o] = 0;
while (o <= n && a[o] != 1) {
++o;
}
}
}
}
System.out.println(res);
} else if (oz == cz) {
int[] temp = new int[n + 1];
for (int i = 0; i <= n; i++) {
temp[i] = a[i];
}
a[0] = 1;
int o = 0;
int z = 0;
for (int i = 2; i <= n; i++) {
if (a[i] == 0) {
z = i;
break;
}
}
for (int i = 2; i <= n; i++) {
if (a[i] == 1) {
o = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (a[i - 1] == a[i]) {
if (a[i] == 1) {
if (z <= i) {
while ((z <= i) || (z <= n && a[z] != 0)) {
++z;
}
}
res += (z - i);
a[i] = 0;
a[z] = 1;
while (z < n && a[z] != 0) {
++z;
}
} else {
if (o <= i) {
while ((o <= i) || (o <= n && a[o] != 1)) {
++o;
}
}
res += (o - i);
a[i] = 1;
a[o] = 0;
while (o <= n && a[o] != 1) {
++o;
}
}
}
}
long res2 = 0;
for (int i = 0; i <= n; i++) {
a[i] = temp[i];
}
a[0] = 0;
o = 0;
z = 0;
for (int i = 2; i <= n; i++) {
if (a[i] == 0) {
z = i;
break;
}
}
for (int i = 2; i <= n; i++) {
if (a[i] == 1) {
o = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (a[i - 1] == a[i]) {
if (a[i] == 1) {
if (z <= i) {
while ((z <= i) || (z <= n && a[z] != 0)) {
++z;
}
}
res2 += (z - i);
a[i] = 0;
a[z] = 1;
while (z < n && a[z] != 0) {
++z;
}
} else {
if (o <= i) {
while ((o <= i) || (o <= n && a[o] != 1)) {
++o;
}
}
res2 += (o - i);
a[i] = 1;
a[o] = 0;
while (o <= n && a[o] != 1) {
++o;
}
}
}
}
System.out.println(Math.min(res, res2));
} else {
System.out.println(-1);
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5dbff71996589e9180ddf6e1603deb50 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.io.PrintStream;
//import java.util.*;
public class Solution {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
static class FastScanner {
BufferedReader br;
StringTokenizer st ;
FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
FastScanner(String file) {
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
st = new StringTokenizer("");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("file not found");
e.printStackTrace();
}
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String readLine() throws IOException{
return br.readLine();
}
}
static class Pair<T,X>{
T first;
X second;
Pair(T first,X second){
this.first = first;
this.second = second;
}
@Override
public int hashCode(){
return Objects.hash(first,second);
}
@Override
public boolean equals(Object obj){
return obj.hashCode() == this.hashCode();
}
}
public static void main(String[] args) throws Exception {
FastScanner s = new FastScanner();
if(LOCAL){
s = new FastScanner("src/input.txt");
PrintStream o = new PrintStream("src/sampleout.txt");
System.setOut(o);
}
int tcr = s.nextInt();
for(int tc=0;tc<tcr;tc++){
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = s.nextInt();
}
int curr[] = new int[n];
int cnt1 = 0;
int cnt0 = 0;
for(int i=0;i<n;i++){
curr[i] = (arr[i] % 2);
if(curr[i] == 1){cnt1++;}
else{cnt0++;}
}
if(Math.abs(cnt1 - cnt0) > 1){
println(-1);
continue;
}
int ar_op1[] = new int[n];
int turn = 0;
for(int i=0;i<n;i++){
ar_op1[i] = turn;
turn = turn ^ 1;
}
int ar_op2[] = new int[n];
turn = 1;
for(int i=0;i<n;i++){
ar_op2[i] = turn;
turn = turn ^ 1;
}
if(n % 2 == 0){
long op1 = solve(curr,ar_op1);
long op2 = solve(curr,ar_op2);
println(Math.min(op1,op2));
}else{
if(cnt0 > cnt1){
println(solve(curr,ar_op1));
}else{
println(solve(curr,ar_op2));
}
}
}
}
public static long solve(int a[],int b[]){
List<Integer> z_pos = new ArrayList<>();
List<Integer> o_pos = new ArrayList<>();
for(int i=0;i<a.length;i++){
if(a[i] != b[i]){
if(a[i] == 0){z_pos.add(i);}
else{o_pos.add(i);}
}
}
Collections.sort(z_pos);
Collections.sort(o_pos);
long ans = 0;
for(int i=0;i<z_pos.size();i++){
ans += (Math.abs(z_pos.get(i) - o_pos.get(i)));
}
return ans;
}
public static long modpow(long num,long pow,long mod){
long val = num;
long ans = 1l;
while(pow > 0l){
long bit = pow & 1l;
if(bit == 1){
ans = (ans * (val%mod))%mod;
}
val = (val * val) % mod;
pow = pow >> 1;
}
return ans;
}
public static char get(int n){
return (char)('a' + n);
}
public static long[] sort(long arr[]){
List<Long> list = new ArrayList<>();
for(long n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
public static int[] sort(int arr[]){
List<Integer> list = new ArrayList<>();
for(int n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
// return the (index + 1)
// where index is the pos of just smaller element
// i.e count of elemets strictly less than num
public static int justSmaller(long arr[],long num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
//return (index of just greater element)
//count of elements smaller than or equal to num
public static int justGreater(long arr[],long num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static void println(Object obj){
System.out.println(obj.toString());
}
public static void print(Object obj){
System.out.print(obj.toString());
}
public static int gcd(int a,int b){
if(b == 0){return a;}
return gcd(b,a%b);
}
public static long gcd(long a,long b){
if(b == 0l){
return a;
}
return gcd(b,a%b);
}
public static int find(int parent[],int v){
if(parent[v] == v){
return v;
}
return parent[v] = find(parent, parent[v]);
}
public static List<Integer> sieve(){
List<Integer> prime = new ArrayList<>();
int arr[] = new int[100001];
Arrays.fill(arr,1);
arr[1] = 0;
arr[2] = 1;
for(int i=2;i<=100000;i++){
if(arr[i] == 1){
prime.add(i);
for(long j = (i*1l*i);j<100001;j+=i){
arr[(int)j] = 0;
}
}
}
return prime;
}
static boolean isPower(long n,long a){
long log = (long)(Math.log(n)/Math.log(a));
long power = (long)Math.pow(a,log);
if(power == n){return true;}
return false;
}
private static int mergeAndCount(int[] arr, int l,int m, int r)
{
// Left subarray
int[] left = Arrays.copyOfRange(arr, l, m + 1);
// Right subarray
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
// Merge sort function
private static int mergeSortAndCount(int[] arr, int l,int r)
{
// Keeps track of the inversion count at a
// particular node of the recursion tree
int count = 0;
if (l < r) {
int m = (l + r) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, l, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, r);
// Merge count
count += mergeAndCount(arr, l, m, r);
}
return count;
}
static class Debug {
//change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) throws Exception {
if(LOCAL) {
PrintStream ps = new PrintStream("src/Debug.txt");
System.setErr(ps);
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | d81f19e6b0c9d13e39695ba9bb1f0ef3 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class B {
static HashMap<Long, Long> combos = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = System.out;
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine());
String[] in = br.readLine().split(" ");
int[] arr = new int[n];
int ones = 0;
for (int x = 0; x < n; x++) {
arr[x] = Integer.parseInt(in[x])%2;
ones += arr[x];
}
if (Math.abs(n - 2*ones) > 1) {
out.println(-1);
continue;
}
long low = 0;
long high = 0;
long count = 0;
for (int x = 0; x < n; x++) {
if (arr[x] == 1) {
low += Math.abs(count-x);
count++;
high += Math.abs(count-x);
count++;
}
}
if (n - 2*ones == 1) {
out.println(Math.abs(high));
} else if (n - 2*ones == -1) {
out.println(Math.abs(low));
} else {
out.println(Math.min(Math.abs(high), Math.abs(low)));
}
}
System.out.flush();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 51a0b3e4bf8ad03fad8070ec9014b059 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BPoMestam solver = new BPoMestam();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BPoMestam {
long doit(int[] a, int st, int n) {
List<List<Integer>> b = new ArrayList<>();
b.add(new ArrayList<>());
b.add(new ArrayList<>());
for (int i = 0; i < n; i++) {
b.get(a[i]).add(i);
}
long ans = 0;
int[] cur = {0, 0};
for (int i = 0; i < n; i++) {
if (b.get(st).size() == cur[st]) {
return Long.MAX_VALUE;
}
ans += Math.abs(i - b.get(st).get(cur[st]));
cur[st]++;
st = Math.abs(st - 1);
}
return ans;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
int val = in.nextInt();
val = (val % 2 == 0 ? 0 : 1);
a[i] = val;
}
long ans = doit(a, 0, n);
ans = Math.min(ans, doit(a, 1, n));
if (ans == Long.MAX_VALUE) {
out.println(-1);
return;
}
out.println(ans / 2);
}
}
static class InputReader {
private static final int BUFFER_LENGTH = 1 << 10;
private InputStream stream;
private byte[] buf = new byte[BUFFER_LENGTH];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int nextC() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String next() {
int c = nextC();
while (isSpaceChar(c)) {
c = nextC();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = nextC();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = skipWhileSpace();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextC();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = nextC();
} while (!isSpaceChar(c));
return res * sgn;
}
public int skipWhileSpace() {
int c = nextC();
while (isSpaceChar(c)) {
c = nextC();
}
return c;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | f6b4390f0bbbb61923feade3edb2b9f9 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n =Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] ars= br.readLine().split(" ");
int countEven = 0, countOdd = 0;
LinkedList<Integer> evens = new LinkedList<>();
LinkedList<Integer> odds = new LinkedList<>();
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(ars[i]);
if (arr[i] % 2 == 0) {
countEven++;
evens.addLast(i);
} else {
countOdd++;
odds.addLast(i);
}
}
int[] arrClone = arr.clone();
if ((n % 2 == 0 && countEven != countOdd) || (n % 2 != 0 && Math.abs(countEven - countOdd) != 1)) {
pw.println(-1);
continue;
}
if (n == 1) {
pw.println(0);
continue;
}
int min1 = 0;
boolean even = true;
for (int i = 0; i < n; i++) {
if (n % 2 != 0 && countOdd > countEven)
break;
if (even && arr[i] % 2 != 0) {
int nextEven = evens.removeFirst();
odds.removeFirst();
odds.addFirst(nextEven);
min1 += nextEven - i;
int tmp = arr[i];
arr[i] = arr[nextEven];
arr[nextEven] = tmp;
} else if (!even && arr[i] % 2 == 0) {
int nextOdd = odds.removeFirst();
evens.removeFirst();
evens.addFirst(nextOdd);
min1 += nextOdd - i;
int tmp = arr[i];
arr[i] = arr[nextOdd];
arr[nextOdd] = tmp;
} else if (even && arr[i] % 2 == 0) {
evens.removeFirst();
} else if (!even && arr[i] % 2 != 0) {
odds.removeFirst();
}
even = !even;
}
if (n % 2 != 0 && countOdd < countEven) {
pw.println(min1);
continue;
}
evens = new LinkedList<>();
odds = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (arrClone[i] % 2 == 0) {
evens.addLast(i);
} else {
odds.addLast(i);
}
}
int min2 = 0;
even = false;
for (int i = 0; i < n; i++) {
if (even && arrClone[i] % 2 != 0) {
int nextEven = evens.removeFirst();
odds.removeFirst();
odds.addFirst(nextEven);
min2 += nextEven - i;
int tmp = arrClone[i];
arrClone[i] = arrClone[nextEven];
arrClone[nextEven] = tmp;
} else if (!even && arrClone[i] % 2 == 0) {
int nextOdd = odds.removeFirst();
evens.removeFirst();
evens.addFirst(nextOdd);
min2 += nextOdd - i;
int tmp = arrClone[i];
arrClone[i] = arrClone[nextOdd];
arrClone[nextOdd] = tmp;
} else if (even && arrClone[i] % 2 == 0) {
evens.removeFirst();
} else if (!even && arrClone[i] % 2 != 0) {
odds.removeFirst();
}
even = !even;
}
if (n % 2 != 0 && countOdd > countEven) {
pw.println(min2);
continue;
}
pw.println(min1 < 0 ? min2 : min2 < 0 ? min1 : Math.min(min1, min2));
}
pw.flush();
pw.close();
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | cfff0eeee8338a6de47226971e9752fe | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int T = in.nextInt();
for(int ttt = 1; ttt <= T; ttt++) {
int n = in.nextInt();
int[] a = in.readInt(n);
int e = 0, ans = 0;
for(int val : a) if(val%2==0) e++;
if((n%2==0 && e!=n/2) || (e!=n/2 && e!=n/2+1)) out.println(-1);
else {
if(n%2==0) {
int m1 = 0, m2 = 0, cur = 0;
for(int i = 0; i < n; i++) {
if(a[i]%2==0) {
if(i != cur) m1 += Math.abs(cur-i);
cur+=2;
}
}
cur = 0;
for(int i = 0; i < n; i++) {
if(a[i]%2==1) {
if(i != cur) m2 += Math.abs(cur-i);
cur+=2;
}
}
ans = Math.min(m1, m2);
}
else {
if(e==n/2) {
int cur = 0;
for(int i = 0; i < n; i++) {
if(a[i]%2==1) {
if(i != cur) ans += Math.abs(cur-i);
cur+=2;
}
}
}
else {
int cur = 0;
for(int i = 0; i < n; i++) {
if(a[i]%2==0) {
if(i != cur) ans += Math.abs(cur-i);
cur+=2;
}
}
}
}
out.println(ans);
}
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); }
String next() {
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try { str = br.readLine(); }
catch(IOException e) { e.printStackTrace(); }
return str;
}
int[] readInt(int size) {
int[] arr = new int[size];
for(int i = 0; i < size; i++)
arr[i] = Integer.parseInt(next());
return arr;
}
long[] readLong(int size) {
long[] arr = new long[size];
for(int i = 0; i < size; i++)
arr[i] = Long.parseLong(next());
return arr;
}
int[][] read2dArray(int rows, int cols) {
int[][] arr = new int[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++)
arr[i][j] = Integer.parseInt(next());
}
return arr;
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a3473f337525143af7066fbec0f6847f | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | //package com.example.lib;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class Algorithm {
static int ans =0;
public static void main(String[] rgs) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\USER\\AndroidStudioProjects\\MyApplication\\lib\\src\\main\\java\\com\\example\\lib\\inpu"));
StringBuilder stringBuilder = new StringBuilder();
int t = Integer.parseInt(bufferedReader.readLine());
for (int i = 0; i < t; i++) {
int size= Integer.parseInt(bufferedReader.readLine());
String[] a= bufferedReader.readLine().split(" ");
int [] input = new int[size];
int onecount=0;
List<Integer> onepos= new ArrayList<>();
for (int j = 0; j < a.length; j++) {
if(Integer.parseInt(a[j])%2==1){
onecount++;
input[j]=1;
onepos.add(j);
}
}
if(onecount<size/2 ||(size%2==1&&onecount>(size/2)+1)){
stringBuilder.append("-1\n");
continue;
}
if(size%2==0&&onecount>size/2){
stringBuilder.append("-1\n");
continue;
}
if(size%2==0) {
int ans=0;
int p=0;
for (int j = 0; j < input.length; j += 2) {
ans+= Math.abs(onepos.get(p++)-j);
}
p=0;
int other=0;
for (int j = 1; j < input.length; j += 2) {
other+= Math.abs(onepos.get(p++)-j);
}
stringBuilder.append(Math.min(ans,other)+"\n");
}else{
int ans=0;
int p=0;
if(onecount==size/2){
for (int j = 1; j < input.length; j += 2) {
ans+= Math.abs(onepos.get(p++)-j);
}
}else{
for (int j = 0; j < input.length; j += 2) {
ans+= Math.abs(onepos.get(p++)-j);
}
}
stringBuilder.append(ans+"\n");
}
}
System.out.println(stringBuilder);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a3de34a3d9ee3bc11fd3507bf8ce1903 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class TakeYourPlace {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a[]=new int[n];
int even=0,odd=0;
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
a[i]=a[i]%2;
if(a[i]==0)even++;
else odd++;
}
if(Math.abs(even-odd)>1)System.out.println(-1);
else if(even>odd)System.out.println(calculate(a,n,0));
else if(odd>even)System.out.println(calculate(a,n,1));
else System.out.println(Math.min(calculate(a,n,1), calculate(a,n,0)));
}
}
static int calculate(int a[],int n,int index) {
int count=0;
for(int i=0;i<n;i++) {
if(a[i]==0) {
count+=Math.abs(i-index);
index+=2;
}
}
return count;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5f6d1f9361eb1b17989555ef909f3f43 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class TakeYourPlaces{
static MyScanner sc = new MyScanner();
static void solve(){
int n = sc.nextInt();
long arr[] = new long[n];
ArrayList<Integer> od = new ArrayList<>();
ArrayList<Integer> ev = new ArrayList<>();
int odd = 0;
int even = 0;
for(int i = 0;i<n;i++){
arr[i] = sc.nextLong();
if(arr[i]%2==0){
even++;
ev.add(odd);
}else{
odd++;
od.add(even);
}
}
if(even>(n+1)/2 || odd>(n+1)/2){
out.println(-1);
return;
}
int ans = -1;
if(od.size()<ev.size() || ev.size()<od.size()){
ans = 0;
if(od.size()<ev.size()) od = ev;
for(int i = 0;i<(n+1)/2;i++){
ans+= Math.abs(i-od.get(i));
}
}else{
int ans1 = 0;
int ans2 = 0;
for(int i = 0;i<(n+1)/2;i++){
ans1 += Math.abs(i-od.get(i));
}
for(int i = 0;i<(n+1)/2;i++){
ans2 += Math.abs(i-ev.get(i));
}
ans = Math.min(ans1,ans2);
}
out.println(ans);
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
while(t-- >0){
solve();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | e130b88bb5345095fd38fe5cfc22a0b3 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = in.nextInt();
// debug(t);
for (int tt = 0; tt < t; tt++) {
int n = in.nextInt();
int[] a = new int[n];
int c0 = 0;
int c1 = 0;
ArrayDeque<Integer> q0 = new ArrayDeque<>();
ArrayDeque<Integer> q1 = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt() % 2;
if (a[i] == 0) {
c0++;
q0.add(i);
} else {
c1++;
q1.add(i);
}
}
if (Math.abs(c0 - c1) > 1) {
System.out.println(-1);
continue;
}
q0.add(n);
q1.add(n);
ArrayDeque<Integer> q0c = q0.clone();
ArrayDeque<Integer> q1c = q1.clone();
int curr = '0';
if (c1 > c0)
curr = '1';
long ans = 0;
for (int i = 0; i < n; ++i) {
int qnum = curr == '0' ? q0.removeFirst() : q1.removeFirst();
int oq = curr == '1' ? q0.peekFirst() : q1.peekFirst();
curr ^= 1;
if (qnum < oq)
continue;
ans += qnum - i;
}
if (c0 == c1) {
long ans2 = 0;
q0 = q0c;
q1 = q1c;
curr = '1';
for (int i = 0; i < n; ++i) {
int qnum = curr == '0' ? q0.removeFirst() : q1.removeFirst();
int oq = curr == '1' ? q0.peekFirst() : q1.peekFirst();
curr ^= 1;
if (qnum < oq)
continue;
ans2 += qnum - i;
}
ans = Math.min(ans, ans2);
}
System.out.println(ans);
}
pw.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | ff9414ad999ca38e7a66300574050d96 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
/*
*/
public class B{
static FastReader sc=null;
static int nax=(int)1e15;
public static void main(String[] args) {
sc=new FastReader();
int t=sc.nextInt();
for(int tt=0;tt<t;tt++) {
int n=sc.nextInt();
int a[]=sc.readArray(n);
ArrayList<Integer> pos[]=new ArrayList[2];
for(int i=0;i<2;i++)pos[i]=new ArrayList<>();
for(int i=0;i<n;i++)pos[a[i]%2].add(i);
long ans=nax;
for(int j=0;j<2;j++) {
if(pos[j].size()!=(n+1)/2)continue;
long val=0;
for(int i=0;i<n;i+=2)val+=Math.abs((int)pos[j].get(i/2)-i);
ans=Math.min(ans, val);
}
System.out.println(ans==nax?-1:ans);
}
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5e20474cffdf9013529c3b3d9bcd9f25 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class TaskB {
static long mod = 1000000007;
static FastScanner scanner;
static final StringBuilder result = new StringBuilder();
public static void main(String[] args) {
scanner = new FastScanner();
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
solve();
result.append("\n");
}
System.out.println(result);
}
static void solve() {
int n = scanner.nextInt();
int[] a = scanner.nextIntArray(n);
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
odd += a[i] % 2 == 1 ? 1 : 0;
even += a[i] % 2 == 0 ? 1 : 0;
}
if ((n % 2 == 0 && odd != even) || (n % 2 == 1 && Math.abs(odd - even) > 1)) {
result.append(-1);
return;
}
if (odd > even) {
result.append(oddFirst(a));
} else if (odd < even) {
result.append(evenFirst(a));
} else {
result.append(Math.min(oddFirst(a), evenFirst(a)));
}
}
static int oddFirst(int[] a) {
return calc(a, 0);
}
static int evenFirst(int[] a) {
return calc(a, 1);
}
static int calc(int[] a, int first) {
int p0 = 0;
int p1 = 0;
boolean[] used = new boolean[a.length];
int i = 0;
int cost = 0;
while (i < a.length) {
while (used[p0]) p0++;
if (p1 <= p0) {
p1 = p0 + 1;
}
if (i % 2 == first) {
if (a[p0] % 2 == 1) {
p0++;
} else {
while (a[p1] % 2 != 1) p1++;
cost += p1 - i;
used[p1++] = true;
}
} else {
if (a[p0] % 2 == 0) {
p0++;
} else {
while (a[p1] % 2 != 0) p1++;
cost += p1 - i;
used[p1++] = true;
}
}
i++;
}
return cost;
// 1 2 2 2 3 5 5
// 0 2 4 6 -
}
// 1 1 1 2 2 2
// 0 2 4 1 3 5
// 0 - 1 - 2 + 2 + 1
static class WithIdx implements Comparable<WithIdx> {
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
if (val == o.val) {
return Integer.compare(idx, o.idx);
}
return Integer.compare(val, o.val);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j];
j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
static long modInverse(long a, long m) {
long g = gcdF(a, m);
if (g != 1) {
throw new IllegalArgumentException("Inverse doesn't exist");
} else {
// If a and m are relatively prime, then modulo
// inverse is a^(m-2) mode m
return modpow(a, m - 2, m);
}
}
static public long gcdF(long a, long b) {
while (b != 0) {
long na = b;
long nb = a % b;
a = na;
b = nb;
}
return a;
}
}
}
/*
5
3 2 3 8 8
2 8 5 10 1
*/ | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6fb136c6abb518249ef8f47e18857b1b | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class Solve {
public static int count(int[] a, int first) {
int ret = 0, delta = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i] != first) {
if (a[i] == 0) delta++;
else delta--;
}
ret += Math.abs(delta);
first ^= 1;
}
return ret;
}
public static int solve(int n, int[] a) {
int odd = 0, even = 0;
for (int i = 0; i < n; ++i) {
a[i] = a[i] % 2;
}
for (int i = 0; i < n; ++i) {
if (a[i] != 0) odd++;
else even++;
}
if (Math.abs(odd - even) >= 2) return -1;
if (odd == even) return Math.min(count(a, 0), count(a, 1));
else if (odd > even) return count(a, 1);
else return count(a, 0);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
// scanner.nextLine();
while (t-- > 0) {
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) a[i] = scanner.nextInt();
System.out.println(solve(n, a));
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | d4f8f99420a2bbccb72c8d7cb2b15406 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = true;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
long[] arr = new long[n];
for (int i = 0; i < n; i++) arr[i] = r.nl();
List<Long> rr = new ArrayList<>();
List<Long> ll = new ArrayList<>();
for (int i = 0; i < n; i++) {
if ((arr[i] & 1) == 0) rr.add((long) i);
else ll.add((long) i);
}
long temp = 0;
if ((n & 1) == 1) {
int len = Math.abs(ll.size() - rr.size());
if (len != 1) {
out.write((-1 + " ").getBytes());
} else {
long ans1 = 0;
if (ll.size() <= rr.size()) {
for (long ele : rr) {
ans1 += Math.abs(ele - temp);
temp += 2;
}
} else {
for (long ele : ll) {
ans1 += Math.abs(ele - temp);
temp += 2;
}
}
out.write((ans1 + " ").getBytes());
}
} else {
if (ll.size() != rr.size()) {
out.write((-1 + " ").getBytes());
} else {
long ans1 = 0;
for (long ele : ll) {
ans1 += Math.abs(ele - temp);
temp += 2;
}
long res = 0;
temp = 0;
for (long ele : rr) {
res += Math.abs(ele - temp);
temp += 2;
}
out.write((Math.min(ans1, res) + " ").getBytes());
}
}
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nl() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) < k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static int upper_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) <= k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 908abe2877272e9c476af10e0d1ca67f | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static long inf=(long)1e18;
static long solve(int[]in,int par,int n) {
int i=0;
int[]ptr=new int[2];
long ans=0;
while(i<n) {
if(in[i]==par) {
i++;
par^=1;
continue;
}
while(ptr[par]<=i)ptr[par]++;
while(ptr[par]<n && in[ptr[par]]!=par) {
ptr[par]++;
}
if(ptr[par]>=n)return inf;
ans+=ptr[par]-i;
in[i]=par;
in[ptr[par]]=par^1;
i++;
par^=1;
}
return ans;
}
static void main() throws Exception{
int n=sc.nextInt();
int[]in=sc.intArr(n);
int[]cnt=new int[2];
for(int i=0;i<n;i++) {
int cur=(in[i]&1);
cnt[cur]++;
in[i]=cur;
}
int x=(n+1)/2;
if(cnt[0]>x || cnt[1]>x) {
pw.println(-1);
return;
}
pw.println(Math.min(solve(in.clone(), 0, n), solve(in.clone(), 1, n)));
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case %d:\n", i);
main();
}
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a36d67ee4b5e5f5c708bd340e8abcf52 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Scratch {
public static int ceil(int p, int q)
{
if (p%q==0)
return p/q;
else
return p/q+1;
}
public static void main(String[] args) throws IOException {
Reader sc=new Reader();
int p=sc.nextInt();
for (int q=0;q<p;q++)
{
int n=sc.nextInt();
int[] arr=new int[n];
for (int r=0;r<n;r++)
arr[r]=sc.nextInt();
ArrayList<Integer> eve=new ArrayList<>();
ArrayList<Integer> odd=new ArrayList<>();
int e=0;
int o=0;
for (int i=0;i<n;i++)
{
if (arr[i]%2==0)
{
e+=1;
eve.add(i);
}
else
{
o+=1;
odd.add(i);
}
}
if (e>ceil(n,2) || o>ceil(n,2))
System.out.println(-1);
else if (n%2==0)
{
int ans1=0;
int ans2=0;
for (int i=0;i<eve.size();i++)
{
ans1+=Math.abs(2*(i)-eve.get(i));
}
for (int i=0;i<odd.size();i++)
{
ans2+=Math.abs(2*(i)-odd.get(i));
}
System.out.println(Math.min(ans1,ans2));
}
else
{
int ans1=0;
if (eve.size()>odd.size())
for (int i=0;i<eve.size();i++)
{
ans1+=Math.abs(2*(i)-eve.get(i));
}
else
for (int i=0;i<odd.size();i++)
{
ans1+=Math.abs(2*(i)-odd.get(i));
}
System.out.println(ans1);
}
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
// Function to return gcd of a and b
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | ace4428edf8f9207ebb06edf1abdf9a2 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = scan.nextInt();
for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out);
out.close();
}
static class Task {
static long INF = Long.MAX_VALUE / 10;
public void solve(int testNumber, FastReader scan, PrintWriter out) {
int n = scan.nextInt();
int[] x = new int[n];
long ans = INF;
for(int i = 0; i < n; i++) x[i] = scan.nextInt() % 2;
outer:
for(int i = 0; i <= 1; i++) {
int[] a = Arrays.copyOf(x, n);
long curr = 0;
int[] ptr = new int[2];
for(int j = 0; j < n; j++) {
int need = (i + j) % 2;
while(ptr[need] < n && a[ptr[need]] != need) ptr[need]++;
if(ptr[need] >= n) continue outer;
curr += ptr[need] - j;
a[j] ^= 1;
a[ptr[need]++] ^= 1;
}
ans = Math.min(curr, ans);
}
out.println(ans == INF ? -1 : ans);
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 671d09b5709a4223c1333d868d830edf | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // Generated by Code Flattener.
// https://plugins.jetbrains.com/plugin/9979-idea-code-flattener
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Solution solution = new ASolution();
boolean local = System.getProperty("ONLINE_JUDGE") == null && !solution.isInteractive();
String input = local ? "input.txt" : null;
solution.in = new MyScanner(input);
solution.out = MyWriter.of(null);
solution.bm = new Benchmark();
solution.al = new Algorithm();
solution.run();
solution.close();
}
private abstract static class Solution {
public MyScanner in;
public MyWriter out;
public Benchmark bm;
public Algorithm al;
public void init() {
}
public abstract void solve();
protected boolean isMultiTest() {
return true;
}
public void run() {
init();
if (isMultiTest()) {
int t = in.nextInt();
for (int i = 0; i < t; i++) {
solve();
}
} else {
solve();
}
}
public void close() {
out.close();
}
public boolean isInteractive() {
return false;
}
}
private static class ASolution extends Solution {
public void solve() {
int n = in.nextInt();
int[] a = in.nextInts(n);
int even = 0;
int odd = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) even++;
else odd++;
}
List<Integer> needs = new ArrayList<>();
if (even == odd || even == odd + 1) needs.add(0);
if (even == odd || odd == even + 1) needs.add(1);
if (needs.isEmpty()) {
out.println(-1);
return;
}
long result = Long.MAX_VALUE;
for (Integer need : needs) {
long ans = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == need) {
ans += Math.abs(i - count * 2);
count++;
}
}
result = Math.min(result, ans);
}
out.println(result);
}
}
private static class MyScanner {
private final BufferedReader br;
private StringTokenizer st;
public MyScanner(String fileName) {
if (fileName != null) {
try {
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextInts(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public String nextLine() {
try {
String line = br.readLine();
if (line == null) {
throw new RuntimeException("empty line");
}
st = null;
return line;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static class Benchmark {
}
private static class Algorithm {
}
private static class MyWriter extends PrintWriter {
public static MyWriter of(String fileName) {
if (fileName != null) {
try {
return new MyWriter(new FileWriter(fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
return new MyWriter(new BufferedOutputStream(System.out));
}
}
public MyWriter(FileWriter fileWriter) {
super(fileWriter);
}
public MyWriter(OutputStream out) {
super(out);
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | d11dacd2b7c6241f37bc38a1ec0351c5 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Math.*;
import static java.lang.System.out;
import java.util.*;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.math.BigInteger;
public class Main {
/* 10^(7) = 1s.
* ceilVal = (a+b-1) / b */
static final int mod = 1000000007;
static final long temp = 998244353;
static final long MOD = 1000000007;
static final long M = (long)1e9+7;
static class Pair implements Comparable<Pair>
{
int first, second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int compareTo(Pair ob)
{
return (int)(first - ob.first);
}
}
static class Tuple implements Comparable<Tuple>
{
int first, second,third;
public Tuple(int first, int second, int third)
{
this.first = first;
this.second = second;
this.third = third;
}
public int compareTo(Tuple o)
{
return (int)(o.third - this.third);
}
}
public static class DSU
{
int[] parent;
int[] rank; //Size of the trees is used as the rank
public DSU(int n)
{
parent = new int[n];
rank = new int[n];
Arrays.fill(parent, -1);
Arrays.fill(rank, 1);
}
public int find(int i) //finding through path compression
{
return parent[i] < 0 ? i : (parent[i] = find(parent[i]));
}
public boolean union(int a, int b) //Union Find by Rank
{
a = find(a);
b = find(b);
if(a == b) return false; //if they are already connected we exit by returning false.
// if a's parent is less than b's parent
if(rank[a] < rank[b])
{
//then move a under b
parent[a] = b;
}
//else if rank of j's parent is less than i's parent
else if(rank[a] > rank[b])
{
//then move b under a
parent[b] = a;
}
//if both have the same rank.
else
{
//move a under b (it doesnt matter if its the other way around.
parent[b] = a;
rank[a] = 1 + rank[a];
}
return true;
}
}
static class Reader
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) throws IOException {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] longReadArray(int n) throws IOException {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static int gcd(int a, int b)
{
if(b == 0)
return a;
else
return gcd(b,a%b);
}
public static long lcm(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
public static long LongGCD(long a, long b)
{
if(b == 0)
return a;
else
return LongGCD(b,a%b);
}
public static long LongLCM(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
//Count the number of coprime's upto N
public static long phi(long n) //euler totient/phi function
{
long ans = n;
// for(long i = 2;i*i<=n;i++)
// {
// if(n%i == 0)
// {
// while(n%i == 0) n/=i;
// ans -= (ans/i);
// }
// }
//
// if(n > 1)
// {
// ans -= (ans/n);
// }
for(long i = 2;i<=n;i++)
{
if(isPrime(i))
{
ans -= (ans/i);
}
}
return ans;
}
public static long fastPow(long x, long n)
{
if(n == 0)
return 1;
else if(n%2 == 0)
return fastPow(x*x,n/2);
else
return x*fastPow(x*x,(n-1)/2);
}
public static long modPow(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p)
{
return modPow(n, p - 2, p);
}
// Returns nCr % p using Fermat's little theorem.
public static long nCrModP(long n, long r,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[(int)(n)] * modInverse(fac[(int)(r)], p)
% p * modInverse(fac[(int)(n - r)], p)
% p)
% p;
}
public static long fact(long n)
{
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (long i = 1; i <= n; i++)
fac[(int)(i)] = fac[(int)(i - 1)] * i;
return fac[(int)(n)];
}
public static long nCr(long n, long k)
{
long ans = 1;
for(long i = 0;i<k;i++)
{
ans *= (n-i);
ans /= (i+1);
}
return ans;
}
//Modular Operations for Addition and Multiplication.
public static long perfomMod(long x)
{
return ((x%M + M)%M);
}
public static long addMod(long a, long b)
{
return perfomMod(perfomMod(a)+perfomMod(b));
}
public static long subMod(long a, long b)
{
return perfomMod(perfomMod(a)-perfomMod(b));
}
public static long mulMod(long a, long b)
{
return perfomMod(perfomMod(a)*perfomMod(b));
}
public static boolean isPrime(long n)
{
if(n == 1)
{
return false;
}
//check only for sqrt of the number as the divisors
//keep repeating so only half of them are required. So,sqrt.
for(int i = 2;i*i<=n;i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
public static List<Long> SieveList(int n)
{
boolean prime[] = new boolean[(int)(n+1)];
Arrays.fill(prime, true);
List<Long> l = new ArrayList<>();
for (long p = 2; p*p<=n; p++)
{
if (prime[(int)(p)] == true)
{
for(long i = p*p; i<=n; i += p)
{
prime[(int)(i)] = false;
}
}
}
for (long p = 2; p<=n; p++)
{
if (prime[(int)(p)] == true)
{
l.add(p);
}
}
return l;
}
public static long log2(long n)
{
long ans = (long)(log(n)/log(2));
return ans;
}
public static boolean isPow2(long n)
{
return (n != 0 && ((n & (n-1))) == 0);
}
public static boolean isSq(int x)
{
long s = (long)Math.round(Math.sqrt(x));
return s*s==x;
}
/*
*
* >= <=
0 1 2 3 4 5 6 7
5 5 5 6 6 6 7 7
lower_bound for 6 at index 3 (>=)
upper_bound for 6 at index 6(To get six reduce by one) (<=)
*/
public static int LowerBound(long a[], long x)
{
int l=-1,r=a.length;
while(l+1<r)
{
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
public static int UpperBound(long a[], long x)
{
int l=-1, r=a.length;
while(l+1<r)
{
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
public static void Sort(long[] a)
{
List<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
// Collections.reverse(l); //Use to Sort decreasingly
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static void ssort(char[] a)
{
List<Character> l = new ArrayList<>();
for (char i : a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static boolean check(long[] a)
{
int n = a.length;
for(int i = 0;i<n-1;i++)
{
if(a[i] > a[i+1]) return false;
}
return true;
}
public static void main(String[] args) throws Exception
{
Reader sc = new Reader();
PrintWriter fout = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int[] a = sc.readArray(n);
for(int i = 0;i<n;i++) a[i]%=2;
ArrayList<Integer> z = new ArrayList<>();
for(int i = 0;i<n;i++)
{
if(a[i] == 0) z.add(i);
}
long ans = (int)(1e15);
if(z.size() == (n + 1)/2)
{
long c = 0;
for(int i = 0;i<n;i+=2) c += abs(i - z.get(i/2));
ans = min(ans,c);
}
if(z.size() == n/2)
{
long c = 0;
for(int i = 1;i<n;i+=2) c += abs(i - z.get(i/2));
ans = min(ans,c);
}
fout.println(ans == (int)(1e15)? -1 : ans);
}
fout.close();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 84a5fbf88499937d84a4b11e001967e9 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import static java.lang.System.out;
public class RoundDelticB
{
public static void main(String[] args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] arr = readArr(N, infile, st);
int res = solution(arr);
sb.append(res+"\n");
}
out.println(sb);
//BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
//System.setOut(new PrintStream(new File("output.txt")));
}
private static int solution(int[] arr) {
if(arr.length == 1){
return 0;
}
int c = 0, d = 0,c1 = 0, d1 =0;
for (int i = 0; i < arr.length; i++) {
if(arr[i] % 2 == 0){
c+=1;
c1+=Math.abs(c-d);
} else {
d+=1;
d1+=Math.abs(d-c);
}
}
if(Math.abs(c - d) > 1){
return -1;
} else {
if(d > c){
return c1;
} else if(c > d){
return d1;
} else {
return Math.min(c1, d1);
}
}
}
static int segregateEvenOdd(int arr[])
{
/* Initialize left and right indexes */
int left = 0, right = arr.length - 1;
int count = 0;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left]%2 == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right]%2 == 1 && left < right)
right--;
if (left < right)
{
/* Swap arr[left] and arr[right]*/
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
count++;
}
}
return count;
}
private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
public static void print(int[] arr)
{
//for debugging only
for(int x: arr)
out.print(x+" ");
out.println();
}
public static long[] readArr2(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
long[] arr = new long[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Long.parseLong(st.nextToken());
return arr;
}
public static boolean isPrime(long n)
{
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1;
for(long i = 6L; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
public static long gcd(long a, long b)
{
if(a > b)
a = (a+b)-(b=a);
if(a == 0L)
return b;
return gcd(b%a, a);
}
public static int lcm(int a, int b) {
return (a * b) / lcm(a, b);
}
public static String sort(String s){
char[] c = s.toCharArray();
Arrays.sort(c);
return new String(c);
}
static String deleteIth(String str, int i)
{
str = str.substring(0, i) +
str.substring(i + 1);
return str;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 49a578080cf6e7cf06d14c224adba3ac | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | //package CodeForces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class B {
public static int startFromOdd(int[] a, int n) {
int moves = 0;
for (int i = 1, odd = 1, eve = 1 ; i <= n ; ++i) {
// Odd indexes are designated for odd numbers
if(i%2 == 1) {
while (odd <= n && a[odd]%2 == 0) {
++odd;
}
moves += (odd-i);
int temp = a[i];
a[i] = a[odd];
a[odd] = temp;
++odd;
}
else {
while (eve <= n && a[eve]%2 == 1) {
++eve;
}
moves += (eve-i);
int temp = a[i];
a[i] = a[eve];
a[eve] = temp;
++eve;
}
}
return moves;
}
public static int startFromEven(int[] a, int n) {
int moves = 0;
for (int i = 1, odd = 1, eve = 1 ; i <=n ; i++) {
// Odd indexes are designated for even numbers
if(i%2 == 1) {
while (eve <= n && a[eve]%2 == 1) {
++eve;
}
moves += (eve-i);
int temp = a[i];
a[i] = a[eve];
a[eve] = temp;
++eve;
}
else {
while (odd <= n && a[odd]%2 == 0) {
++odd;
}
moves += (odd-i);
int temp = a[i];
a[i] = a[odd];
a[odd] = temp;
++odd;
}
}
return moves;
}
public static void main (String[] Z) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder op = new StringBuilder();
StringTokenizer stz;
int T = Integer.parseInt(br.readLine());
while(T-- > 0) {
int n = Integer.parseInt(br.readLine());
stz = new StringTokenizer(br.readLine());
int[] arr = new int[n+1];
int[] b = new int[n+1];
int c1 = 0, c2 = 0;
for (int i = 1 ; i <= n; i++) {
arr[i] = Integer.parseInt(stz.nextToken());
b[i] = arr[i];
if(arr[i]%2 == 0) {
c2++;
}
else {
c1++;
}
}
if(n == 1) {
op.append("0\n");
continue;
}
int diff = Math.abs(c1-c2);
if(diff > 1) {
op.append("-1\n");
continue;
}
int moves = 0;
if(diff == 1) {
if(c1 > c2) {
moves = startFromOdd(arr, n);
}
else {
moves = startFromEven(arr, n);
}
}
else {
int m1 = startFromOdd(b, n);
int m2 = startFromEven(arr, n);
// System.out.println(m1);
// System.out.println(m2);
moves = Math.min(m1, m2);
}
op.append(moves+"\n");
}
System.out.println(op);
// END OF CODE
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 584fd4acea9c163b07bd7ccfcf484088 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main{
static int steps(int x, int[] arr){
int delta = 0;
int ans = 0;
for(int i=0; i<arr.length; i++){
if(arr[i] != x){
delta += arr[i] - x;
}
ans += Math.abs(delta);
x ^= 1;
}
return ans;
}
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(in.readLine());
while(t-->0){
int n = Integer.parseInt(in.readLine());
int[] arr = new int[n];
String[] s = in.readLine().trim().split(" ");
int[] count = new int[2];
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(s[i]);
arr[i] %= 2;
count[arr[i]]++;
}
if(n % 2 == 0){
if(count[0] == count[1]){
int ans = Math.min(steps(0, arr), steps(1, arr));
out.println(ans);
}else out.println("-1");
}else{
int diff = Math.abs(count[0]-count[1]);
if(diff > 1){
out.println("-1");
continue;
}
if(count[0] > count[1]){
int ans = steps(0, arr);
out.println(ans);
}else{
int ans = steps(1, arr);
out.println(ans);
}
}
}
in.close();
out.close();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 749e33a37149c58413a9c3f6510d5bc3 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | //package contest.DeltixRoundSummer2021;
import java.io.*;
import java.util.*;
public class B1556 {
InputStream is;
FastWriter out;
String INPUT = "";
//提交时注意需要注释掉首行package
//基础类型数组例如long[]使用Arrays排序容易TLE,可以替换成Long[]
//int 最大值2**31-1,2147483647;
//尽量使用long类型,避免int计算的数据溢出
//String尽量不要用+号来,可能会出现TLE,推荐用StringBuffer
void solve() {
int t = ni();
for (; t > 0; t--)
go();
}
void go() {
int n = ni();
Integer[] a = na(n);
int ans = Integer.MAX_VALUE;
boolean flag = false;
for (int i = 0; i < 2; i++) {
int m = i;
List<Integer> p = new ArrayList<>(), q = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (m % 2 != a[j] % 2) {
if (a[j] % 2 == 0) {
p.add(j);
} else {
q.add(j);
}
}
m++;
}
int cnt = 0;
if (p.size() == q.size()) {
for (int j = 0; j < p.size(); j++) {
cnt += Math.abs(p.get(j) - q.get(j));
}
flag = true;
ans = Math.min(cnt, ans);
}
}
if (flag) {
out.println(ans);
} else {
out.println(-1);
}
}
void run() throws Exception {
is = System.in;
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
//debug log
//tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new B1556().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private Integer[] na(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private Long[] nal(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private Integer[][] nmi(int n, int m) {
Integer[][] map = new Integer[n][];
for (int i = 0; i < n; i++)
map[i] = na(m);
return map;
}
private int ni() {
return (int) nl();
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
public void trnz(int... o) {
for (int i = 0; i < o.length; i++)
if (o[i] != 0)
System.out.print(i + ":" + o[i] + " ");
System.out.println();
}
// print ids which are 1
public void trt(long... o) {
Queue<Integer> stands = new ArrayDeque<>();
for (int i = 0; i < o.length; i++) {
for (long x = o[i]; x != 0; x &= x - 1)
stands.add(i << 6 | Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r) {
for (boolean x : r)
System.out.print(x ? '#' : '.');
System.out.println();
}
public void tf(boolean[]... b) {
for (boolean[] r : b) {
for (boolean x : r)
System.out.print(x ? '#' : '.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b) {
if (INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b) {
if (INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 8d412a7013ca2f1545fdb8ebd63c6334 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | //package codeforces.deltix_summer;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
//Think through the entire logic before jump into coding!
//If you are out of ideas, take a guess! It is better than doing nothing!
//Read both C and D, it is possible that D is easier than C for you!
//Be aware of integer overflow!
//If you find an answer and want to return immediately, don't forget to flush before return!
public class B {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
solve(in.nextInt());
//solve(1);
}
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt();
int[] a = in.nextIntArrayPrimitive(n);
List<Integer>[] idx = new List[2];
for(int i = 0; i < 2; i++) idx[i] = new ArrayList<>();
for(int i = 0; i < n; i++) {
idx[a[i] % 2].add(i);
}
if(abs(idx[0].size() - idx[1].size()) > 1) {
out.println(-1);
}
else {
if(n % 2 != 0) {
int ans = 0, expectedParity = idx[0].size() > idx[1].size() ? 0 : 1;
int[] currIdx = new int[2];
for(int i = 0; i < n; i++) {
ans += max(0, idx[expectedParity].get(currIdx[expectedParity]) - i);
currIdx[expectedParity]++;
expectedParity = 1 - expectedParity;
}
out.println(ans);
}
else {
int ans1 = 0, expectedParity1 = 0;
int[] currIdx1 = new int[2];
for(int i = 0; i < n; i++) {
ans1 += max(0, idx[expectedParity1].get(currIdx1[expectedParity1]) - i);
currIdx1[expectedParity1]++;
expectedParity1 = 1 - expectedParity1;
}
int ans2 = 0, expectedParity2 = 1;
int[] currIdx2 = new int[2];
for(int i = 0; i < n; i++) {
ans2 += max(0, idx[expectedParity2].get(currIdx2[expectedParity2]) - i);
currIdx2[expectedParity2]++;
expectedParity2 = 1 - expectedParity2;
}
out.println(min(ans1, ans2));
}
}
}
out.close();
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitive(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitiveOneIndexed(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextInt();
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitive(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitiveOneIndexed(int n) {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextLong();
return a;
}
String[] nextStringArray(int n) {
String[] g = new String[n];
for (int i = 0; i < n; i++) g[i] = next();
return g;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a5078cb21ace80a1d9d732b3b430e326 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
//6 2 3 4 5 1
//0 0 1 0 1 1
//0 1 0 1 0 1
//1 0 1 0 1 0
//1 1 1 0 0 0
//1 0 1 0 1 0
//1 0 1 0 1 0
//0 1 0 1 0 1
public class C {
private static void sport(int[] a) {
int n = a.length;
int[] copy = Arrays.copyOf(a, n);
TreeSet<Integer> zeros = new TreeSet<>();
TreeSet<Integer> ones = new TreeSet<>();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
zeros.add(i);
} else {
ones.add(i);
}
}
if (Math.abs(zeros.size() - ones.size()) > 1) {
System.out.println(-1);
return;
}
//0 1 0 1 0 1
if (zeros.size() >= ones.size()) {
int curr = 0;
int res = 0;
boolean f = false;
for (int i = 0; i < n; i++) {
if (a[i] % 2 != curr) {
if (curr == 0) {
Integer higher = zeros.higher(i);
if (higher == null) {
f = true;
break;
}
zeros.remove(higher);
ones.remove(i);
ones.add(higher);
a[higher] = 1;
res += higher - i;
} else {
Integer higher = ones.higher(i);
if (higher == null) {
f = true;
break;
}
ones.remove(higher);
zeros.remove(i);
zeros.add(higher);
a[higher] = 0;
res += higher - i;
}
}
curr = 1 - curr;
}
if (!f) {
ans = Math.min(ans, res);
}
}
//1 0 1 0 1 0 1 0
if (ones.size() >= zeros.size()) {
zeros.clear();
ones.clear();
a = copy;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
zeros.add(i);
} else {
ones.add(i);
}
}
int curr = 1;
int res = 0;
boolean f = false;
for (int i = 0; i < n; i++) {
if (a[i] % 2 != curr) {
if (curr == 0) {
Integer higher = zeros.higher(i);
if (higher == null) {
f = true;
break;
}
zeros.remove(higher);
ones.remove(i);
ones.add(higher);
a[higher] = 1;
res += higher - i;
} else {
Integer higher = ones.higher(i);
if (higher == null) {
f = true;
break;
}
ones.remove(higher);
zeros.remove(i);
zeros.add(higher);
a[higher] = 0;
res += higher - i;
}
}
curr = 1 - curr;
}
if (!f) {
ans = Math.min(ans, res);
}
}
System.out.println(ans);
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int[] a = sc.readArrayInt(n);
sport(a);
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long[] readArrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int[] readArrayInt(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 46a106c67604515f4726f32d2fa369c8 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // package Self;
import java.util.Scanner;
import java.util.Set;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class Solution {
static FastReader scn = new FastReader();
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long mod = (long) (1e9 + 7);
static int maxN = (int) 2e5 + 10;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
int t = 1;
t = scn.nextInt();
while (t-- > 0) {
int n = scn.nextInt();
int[] arr = input(n);
sb.append(find(arr));
sb.append("\n");
}
System.out.println(sb);
}
private static long find(int[] arr) {
int ce = 0, co = 0;
for (int val : arr) {
if (val % 2 == 0)
ce++;
else
co++;
}
int n = arr.length;
int[] x1 = new int[n];
int[] x2 = null;
if (n % 2 == 0) {
if (co != ce)
return -1;
x1[0] = 0;
for (int i = 1; i < n; i++) {
x1[i] = (x1[i - 1] + 1) % 2;
}
x2 = new int[n];
x2[0] = 1;
for (int i = 1; i < n; i++) {
x2[i] = (x2[i - 1] + 1) % 2;
}
}
else {
if (Math.abs(co - ce) != 1)
return -1;
if (co > ce)
x1[0] = 1;
else
x1[0] = 0;
for (int i = 1; i < n; i++) {
x1[i] = (x1[i - 1] + 1) % 2;
}
}
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] % 2;
}
// for (int val : xor)
// System.out.print(val + " ");
// System.out.println();
long ans = xorOp(arr, x1);
// System.out.println(ans);
if (x2 != null) {
// for (int val : xor)
// System.out.print(val + " ");
// System.out.println();
ans = Math.min(ans, xorOp(arr, x2));
}
return ans;
}
private static long xorOp(int[] a, int[] x) {
int i = 0, j = 0;
long ans = 0;
int n = a.length;
while (i < n && j < n) {
if (a[i] == 0)
i++;
else if (x[j] == 0)
j++;
else {
ans += Math.abs(i - j);
i++;
j++;
}
}
return ans;
}
public static void yes() {
sb.append("YES\n");
}
public static void no() {
sb.append("NO\n");
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static long[] longInput(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextLong();
}
return arr;
}
public static int[] input(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
}
return arr;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | e70e87cf8940d3157689d92dcfab98b1 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf2 {
public static void main(String[] args) {
FastReader fr = new FastReader();
int test_case = fr.nextInt();
while (test_case-- != 0) {
int n = fr.nextInt();
int arr[] = new int[n];
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
int input = fr.nextInt();
if (input % 2 == 0) {
arr[i] = 0;
even++;
} else {
arr[i] = 1;
odd++;
}
}
int ans = 0;
int diff = Math.abs(even - odd);
if (diff >= 2) {
System.out.println(-1);
continue;
}
if (n % 2 == 1) {
int arr2[] = new int[n];
for (int i = 0; i < n; i++) {
if (even > odd) {
if (i % 2 == 0)
arr2[i] = 0;
else
arr2[i] = 1;
} else {
if (i % 2 == 0)
arr2[i] = 1;
else
arr2[i] = 0;
}
}
ans = count(arr, arr2);
} else {
int arr2[] = new int[n];
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
arr2[i] = 0;
} else {
arr2[i] = 1;
}
}
int arr3[] = new int[n];
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
arr3[i] = 1;
} else {
arr3[i] = 0;
}
}
ans = Math.min(count(arr, arr2), count(arr, arr3));
}
System.out.println(ans);
}
}
public static int count(int arr1[], int arr2[]) {
ArrayList<Integer> al1 = new ArrayList<>();
ArrayList<Integer> al2 = new ArrayList<>();
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
if (arr2[i] == 0) {
al2.add(i);
} else {
al1.add(i);
}
}
}
int total = 0;
for (int i = 0; i < al1.size(); i++) {
total += Math.abs(al1.get(i) - al2.get(i));
}
return total;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 90010a17157d42fa4af4c25fad0e6fc9 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | /*Everything is Hard
* Before Easy
* Jai Mata Dii
*/
import java.util.*;
import java.io.*;
public class Main {
static class FastReader{ BufferedReader br;StringTokenizer st;public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOException e){e.printStackTrace();}}return st.nextToken();}int nextInt(){ return Integer.parseInt(next());}long nextLong(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}String nextLine(){String str = ""; try{str = br.readLine(); } catch (IOException e) {e.printStackTrace();} return str; }}
static long mod = (long)(1e9+7);
// static long mod = 998244353;
// static Scanner sc = new Scanner(System.in);
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main (String[] args) {
int ttt = 1;
ttt = sc.nextInt();
z :for(int tc=1;tc<=ttt;tc++){
int n = sc.nextInt();
int a[] = new int[n];
TreeSet<Integer> z = new TreeSet<>();
TreeSet<Integer> o = new TreeSet<>();
for(int i=0;i<n;i++) {
int x = sc.nextInt();
a[i] = (x)%2;
if(a[i] == 0) z.add(i);
else o.add(i);
}
long ans = 0, par = 0;
for(int i=0;i<n;i++) {
if(par == 0) {
if(z.size()==0) {
ans = -1;
break;
}
ans += 1L*Math.abs(i-z.first());
z.pollFirst();
}
else {
if(o.size()==0) {
ans = -1;
break;
}
ans += 1L*Math.abs(i-o.first());
o.pollFirst();
}
par = Math.abs(par-1);
}
for(int i=0;i<n;i++) {
if(a[i] == 0) z.add(i);
else o.add(i);
}
long ans1 = 0; par = 1;
for(int i=0;i<n;i++) {
if(par == 0) {
if(z.size()==0) {
ans1 = -1;
break;
}
ans1 += 1L*Math.abs(i-z.first());
z.pollFirst();
}
else {
if(o.size()==0) {
ans1 = -1;
break;
}
ans1 += 1L*Math.abs(i-o.first());
o.pollFirst();
}
par = Math.abs(par-1);
}
if(ans==-1) ans = ans1;
else if(ans1 == -1) ans = 0+ans;
else ans = Math.min(ans, ans1);
if(ans != -1) ans /= 2;
out.write(ans+"\n");
}
out.close();
}
static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;}
static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); }
private static void sort(double[] a) {List<Double> k = new ArrayList<>();for(double val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 78066337e3a36b221225a964a0d0795b | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.Stack;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 17:56:23 29/08/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt();
int[] a = in.na(n);
int[] p = new int[2];
for(int i : a) p[i%2]++;
if(Math.abs(p[0]-p[1])>=2) {
out.println(-1);
return;
}
long inf = Long.MAX_VALUE/3;
long ans = inf;
{
long curAns = 0;
Stack<Integer> wrongEvens = new Stack();
for(int i = n-1; i>=0; i--) if(a[i]%2==0 && (a[i]+i)%2==0) wrongEvens.add(i);
for(int i = 0; i<n; i++) if(a[i]%2==1 && (a[i]+i)%2==0) {
if(wrongEvens.isEmpty()) {
curAns = inf;
break;
}
int v = wrongEvens.pop();
curAns += Math.abs(v-i);
}
if(!wrongEvens.isEmpty()) curAns = inf;
ans = Math.min(ans, curAns);
}
{
long curAns = 0;
Stack<Integer> wrongEvens = new Stack();
for(int i = n-1; i>=0; i--) if(a[i]%2==0 && (a[i]+i)%2==1) wrongEvens.add(i);
for(int i = 0; i<n; i++) if(a[i]%2==1 && (a[i]+i)%2==1) {
if(wrongEvens.isEmpty()) {
curAns = inf;
break;
}
int v = wrongEvens.pop();
curAns += Math.abs(v-i);
}
if(!wrongEvens.isEmpty()) curAns = inf;
ans = Math.min(ans, curAns);
}
out.println(ans<inf?ans:-1);
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = in.nextInt();
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod){
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0){
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 4ccdf28ee3570ab15e0e4134a9da59f1 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
/**/
int t = sc.nextInt();
for (int z = 0; z < t; ++z) {
int n = sc.nextInt();
int[] a = new int[n];
int c0 = 0;
int c1 = 0;
ArrayDeque<Integer> q0 = new ArrayDeque<>();
ArrayDeque<Integer> q1 = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
a[i] = sc.nextInt()%2;
if (a[i]==0) {
c0++;
q0.add(i);
} else {
c1++;
q1.add(i);
}
}
if (Math.abs(c0-c1)>1) {
System.out.println(-1);
continue;
}
q0.add(n);
q1.add(n);
ArrayDeque<Integer> q0c = q0.clone();
ArrayDeque<Integer> q1c = q1.clone();
int curr = '0';
if (c1>c0)
curr = '1';
long ans = 0;
for (int i = 0; i < n; ++i) {
int qnum = curr=='0'?q0.removeFirst():q1.removeFirst();
int oq = curr=='1'?q0.peekFirst():q1.peekFirst();
curr ^= 1;
if (qnum<oq)
continue;
ans += qnum-i;
}
if (c0==c1) {
long ans2 = 0;
q0 = q0c;
q1 = q1c;
curr = '1';
for (int i = 0; i < n; ++i) {
int qnum = curr=='0'?q0.removeFirst():q1.removeFirst();
int oq = curr=='1'?q0.peekFirst():q1.peekFirst();
curr ^= 1;
if (qnum<oq)
continue;
ans2 += qnum-i;
}
ans = Math.min(ans, ans2);
}
System.out.println(ans);
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 9c69434e8a3d7a09380daaa7db8e60fb | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DeltB {
public static void main(String[] args) {
JS scan = new JS();
int t = scan.nextInt();
while (t-- > 0){
int n = scan.nextInt();
int[] arr = new int[n];
for(int i = 0;i<n;i++){
arr[i] = scan.nextInt();
}
//put evens first or put odds first
long ans1 = 0, ans2 = 0;
int idx = 0;
int count = 0, counto = 0;
for(int i = 0;i<n;i++){
if(arr[i]%2==0){
ans1+=Math.abs(i-idx*2);
count++;
idx++;
}else{
counto++;
}
}
if(Math.abs(count-counto)>1){
System.out.println(-1);
continue;
}
idx = 0;
for(int i = 0;i<n;i++){
if(arr[i]%2==1){
ans2+=(Math.abs(i-idx*2));
idx++;
}
}
//System.out.println(Math.min(ans1,ans2));
if(count==counto)
System.out.println(Math.min(ans1,ans2));
else if(count>counto){
System.out.println(ans1);
}else{
System.out.println(ans2);
}
}
}
static class JS {
public int BS = 1 << 16;
public char NC = (char) 0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
num = 1;
boolean neg = false;
if (c == NC) c = nextChar();
for (; (c < '0' || c > '9'); c = nextChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = nextChar()) {
res = (res << 3) + (res << 1) + c - '0';
num *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / num;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = nextChar();
while (c > 32) {
res.append(c);
c = nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = nextChar();
while (c != '\n') {
res.append(c);
c = nextChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = nextChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 67b46b671e3157cf7124be231d1dee73 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int n = in.nextInt();
int[] a = new int[n];
int[] c = new int[2];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() % 2;
++c[a[i]];
}
final long infinity = (long) 1e18;
long ans = infinity;
for (int step = 0; step < 2; step++) {
int[] d = new int[2];
for (int i = 0; i < n; i++) {
++d[(i + step) % 2];
}
if (!Arrays.equals(c, d)) {
continue;
}
int[] ptr = {step, step ^ 1};
long[] e = {0, 0};
for (int i = 0; i < n; i++) {
int x = a[i];
e[x] += Math.abs(i - ptr[x]);
ptr[x] += 2;
}
// System.out.println(Arrays.toString(e));
ans = Math.min(ans, e[0]);
ans = Math.min(ans, e[1]);
}
if (ans >= infinity) {
ans = -1;
}
out.println(ans);
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | db19c5afe65d4b8487ed8dfef401753d | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; ++i) {
a[i] = sc.nextInt();
}
System.out.println(solve(a));
}
sc.close();
}
static long solve(int[] a) {
int[] evenIndices = IntStream.range(0, a.length).filter(i -> a[i] % 2 == 0).toArray();
int[] oddIndices = IntStream.range(0, a.length).filter(i -> a[i] % 2 != 0).toArray();
int[] largeIndices;
int[] smallIndices;
if (evenIndices.length >= oddIndices.length) {
largeIndices = evenIndices;
smallIndices = oddIndices;
} else {
largeIndices = oddIndices;
smallIndices = evenIndices;
}
if (largeIndices.length - smallIndices.length >= 2) {
return -1;
}
long result =
computeDiffSum(
largeIndices, IntStream.range(0, largeIndices.length).map(i -> i * 2).toArray());
if (largeIndices.length == smallIndices.length) {
result =
Math.min(
result,
computeDiffSum(
largeIndices,
IntStream.range(0, largeIndices.length).map(i -> i * 2 + 1).toArray()));
}
return result;
}
static long computeDiffSum(int[] x, int[] y) {
return IntStream.range(0, x.length).map(i -> Math.abs(x[i] - y[i])).asLongStream().sum();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 398dc706231ded46a584bf6e18052fc0 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw;
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n =sc.nextInt();
int []arr=sc.nextIntArray(n);
PriorityQueue<Integer> oddP = new PriorityQueue<>();
PriorityQueue<Integer> evenP = new PriorityQueue<>();
int odd =0;
int even =0;
for (int i = 0; i < arr.length; i++) {
if(arr[i] % 2 == 0) {
evenP.add(i);
even++;
}
else {
oddP.add(i);
odd++;
}
}
if(Math.abs(even-odd)>1)
pw.println(-1);
else {
long res=0;
int c=0;
if(even>odd) {
while(!evenP.isEmpty()) {
res+=Math.abs(evenP.poll()-c);
c+=2;
}
pw.println(res);
}
else if(odd > even) {
while(!oddP.isEmpty()) {
res+=Math.abs(oddP.poll()-c);
c+=2;
}
pw.println(res);
}
else {
int r1=0;
int r2=0;
int cc=0;
while(!oddP.isEmpty()) {
r1 +=Math.abs(oddP.poll()-cc);
cc+=2;
}
cc=0;
while(!evenP.isEmpty()) {
r2 +=Math.abs(evenP.poll()-cc);
cc+=2;
}
pw.println(Math.min(r1, r2));
}
}
}
pw.close();
}
public static int solve(int cnt,int num ,int min) {
if(num<2*min)
return cnt;
return solve(cnt+1, num-(2*min-1), min);
}
public static int log2(Long N) // log base 2
{
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static long fac(long i) {
long res = 1;
while (i > 0) {
res = res * i--;
}
return res;
}
public static long combination(long x, long y) {
return 1l * (fac(x) / (fac(x - y) * fac(y)));
}
public static long permutation(long x, long y) {
return combination(x, y) * fac(y);
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public int compareTo(Pair p) {
if (this.x == p.x)
return this.y - p.y;
return this.x - p.x;
}
}
static class SegmentTree {
char[] array;
int[] sTree;
int N;
public SegmentTree(char[] in) {
array = in;
N = in.length - 1;
sTree = new int[2 * N];
build(1, 1, N);
}
public void build(int node, int l, int r) { // o(n)
if (l == r) {
sTree[node] = 1 << array[l] - 'a';
} else {
int mid = l + r >> 1;
int leftChild = node << 1;
int rightChild = (node << 1) + 1;
build(leftChild, l, mid);
build(rightChild, mid + 1, r);
sTree[node] = sTree[leftChild] | sTree[rightChild];
}
}
public int query(int i, int j) {
return query(1, 1, N, i, j);
}
public int query(int node, int l, int r, int i, int j) { // [i,j] range I query on
if (l > j || r < i) // no intersection
return 0;
if (l >= i && r <= j) // kolo gwa el range
return sTree[node];
// else (some intersection)
int mid = l + r >> 1;
int leftChild = node << 1;
int rightChild = (node << 1) + 1;
int left = query(leftChild, l, mid, i, j);
int right = query(rightChild, mid + 1, r, i, j);
return left | right;
}
public void updatePoint(int index, char val) {
int node = index + N - 1;
array[index] = val;
sTree[node] = 1 << val - 'a'; // updating the point
while (node > 1) {
node >>= 1; // dividing by 2 to get the parent then update it
int leftChild = node << 1;
int rightChild = (node << 1) + 1;
sTree[node] = sTree[leftChild] | sTree[rightChild];
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextlongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] array = new Long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
public char[] nextCharArray(int n) throws IOException {
char[] array = new char[n];
String string = next();
for (int i = 0; i < n; i++) {
array[i] = string.charAt(i);
}
return array;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 7768ad3543300dce235a1cf037d39ec1 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author eslam
*/
public class Solution {
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>();
static ArrayList<LinkedList<String>> allprems = new ArrayList<>();
static ArrayList<Long> luc = new ArrayList<>();
static long mod = (long) (Math.pow(10, 9) + 7);
static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}};
static int gr[][] = {{0, 0, 1, -1, -1, 1}, {1, -1, 0, 0, -1, 1}};
static int dp[][][];
static double cmp = 0.000000001;
public static void main(String[] args) throws IOException {
// Kattio input = new Kattio("input");
// BufferedWriter log = new BufferedWriter(new FileWriter("output.txt"));
int test = input.nextInt();
loop:
for (int o = 1; o <= test; o++) {
int n = input.nextInt();
ArrayList<Integer> od = new ArrayList<>();
ArrayList<Integer> ev = new ArrayList<>();
int ans1 = 0;
int ans2 = 0;
for (int i = 0; i < n; i++) {
int x = input.nextInt();
if ((x & 1) == 0) {
ev.add(i);
} else {
od.add(i);
}
}
if (Math.abs(ev.size() - od.size()) > 1) {
log.write("-1\n");
continue;
}
if (od.size() >= ev.size()) {
int pos = 0;
for (Integer i : od) {
ans1 += Math.abs(i - pos);
pos += 2;
}
pos = 1;
} else {
ans1 = Integer.MAX_VALUE;
}
if (ev.size() >= od.size()) {
int pos = 0;
for (Integer i : ev) {
ans2 += Math.abs(i - pos);
pos += 2;
}
} else {
ans2 = Integer.MAX_VALUE;
}
log.write(Math.min(ans1, ans2) + "\n");
}
log.flush();
}
static long solve(long h, long n, boolean ch) {
long ha = 1l << h - 1;
if (h == 0) {
return 0;
}
if (n > ha) {
if (ch) {
return 1 + solve(h - 1, n - ha, !ch);
} else {
return 2 * ha + solve(h - 1, n - ha, ch);
}
} else {
if (ch) {
return 2 * ha + solve(h - 1, n, ch);
} else {
return 1 + solve(h - 1, n, !ch);
}
}
}
public static long baseToDecimal(String w, long base) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(base, l);
r = r + x;
l++;
}
return r;
}
static int bs(int v, ArrayList<Integer> a) {
int max = a.size() - 1;
int min = 0;
int ans = 0;
while (max >= min) {
int mid = (max + min) / 2;
if (a.get(mid) >= v) {
ans = a.size() - mid;
max = mid - 1;
} else {
min = mid + 1;
}
}
return ans;
}
static Comparator<tri> cmpTri() {
Comparator<tri> c = new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.z > o2.z) {
return 1;
} else if (o1.z < o2.z) {
return -1;
} else {
return 0;
}
}
}
}
};
return c;
}
static Comparator<pair> cmpPair() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
}
};
return c;
}
static class rec {
long x1;
long x2;
long y1;
long y2;
public rec(long x1, long y1, long x2, long y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public long getArea() {
return (x2 - x1) * (y2 - y1);
}
}
static int sumOfRange(int x1, int y1, int x2, int y2, int e, int a[][][]) {
return (a[e][x2][y2] - a[e][x1 - 1][y2] - a[e][x2][y1 - 1]) + a[e][x1 - 1][y1 - 1];
}
public static int[][] bfs(int i, int j, String w[]) {
Queue<pair> q = new ArrayDeque<>();
q.add(new pair(i, j));
int dis[][] = new int[w.length][w[0].length()];
for (int k = 0; k < w.length; k++) {
Arrays.fill(dis[k], -1);
}
dis[i][j] = 0;
while (!q.isEmpty()) {
pair p = q.poll();
int cost = dis[p.x][p.y];
for (int k = 0; k < 4; k++) {
int nx = p.x + grid[0][k];
int ny = p.y + grid[1][k];
if (isValid(nx, ny, w.length, w[0].length())) {
if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') {
q.add(new pair(nx, ny));
dis[nx][ny] = cost + 1;
}
}
}
}
return dis;
}
public static void dfs(int node, ArrayList<Integer> a[], boolean vi[]) {
vi[node] = true;
for (Integer ch : a[node]) {
if (!vi[ch]) {
dfs(ch, a, vi);
}
}
}
public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static boolean isValid(int i, int j, int n, int m) {
return (i > -1 && i < n) && (j > -1 && j < m);
}
// present in the left and right indices
public static int[] swap(int data[], int left, int right) {
// Swap the data
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static int[] reverse(int data[], int left, int right) {
// Reverse the sub-array
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(int data[]) {
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.length <= 1) {
return false;
}
int last = data.length - 2;
// find the longest non-increasing suffix
// and find the pivot
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0) {
return false;
}
int nextGreater = data.length - 1;
// Find the rightmost successor to the pivot
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
// Swap the successor and the pivot
data = swap(data, nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1, data.length - 1);
// Return true as the next_permutation is done
return true;
}
public static pair[] dijkstra(int node, ArrayList<pair> a[]) {
PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
});
q.add(new tri(node, 0, -1));
pair distance[] = new pair[a.length];
while (!q.isEmpty()) {
tri p = q.poll();
int cost = p.y;
if (distance[p.x] != null) {
continue;
}
distance[p.x] = new pair(p.z, cost);
ArrayList<pair> nodes = a[p.x];
for (pair node1 : nodes) {
if (distance[node1.x] == null) {
tri pa = new tri(node1.x, cost + node1.y, p.x);
q.add(pa);
}
}
}
return distance;
}
public static String revs(String w) {
String ans = "";
for (int i = w.length() - 1; i > -1; i--) {
ans += w.charAt(i);
}
return ans;
}
public static boolean isPalindrome(String w) {
for (int i = 0; i < w.length() / 2; i++) {
if (w.charAt(i) != w.charAt(w.length() - i - 1)) {
return false;
}
}
return true;
}
public static void getPowerSet(Queue<Integer> a) {
int n = a.poll();
if (!a.isEmpty()) {
getPowerSet(a);
}
int s = powerSet.size();
for (int i = 0; i < s; i++) {
ArrayList<Integer> ne = new ArrayList<>();
ne.add(n);
for (int j = 0; j < powerSet.get(i).size(); j++) {
ne.add(powerSet.get(i).get(j));
}
powerSet.add(ne);
}
ArrayList<Integer> p = new ArrayList<>();
p.add(n);
powerSet.add(p);
}
public static int getlo(int va) {
int v = 1;
while (v <= va) {
if ((va&v) != 0) {
return v;
}
v <<= 1;
}
return 0;
}
static long fast_pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a) % mod;
p /= 2;
} else {
res = (res * a) % mod;
p--;
}
}
return res;
}
public static int countPrimeInRange(int n, boolean isPrime[]) {
int cnt = 0;
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * 2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
cnt++;
}
}
return cnt;
}
public static void create(long num) {
luc.add(num);
if (num > power(10, 9)) {
return;
}
create(num * 10 + 4);
create(num * 10 + 7);
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static long round(long a, long b) {
if (a < 0) {
return (a - b / 2) / b;
}
return (a + b / 2) / b;
}
public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) {
if (l.size() == st.size()) {
allprems.add(l);
}
for (int i = 0; i < st.size(); i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<String> nl = new LinkedList<>();
for (String x : l) {
nl.add(x);
}
nl.add(st.get(i));
allPremutationsst(nl, visited, st);
visited[i] = false;
}
}
}
public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) {
if (l.size() == a.length) {
allprem.add(l);
}
for (int i = 0; i < a.length; i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<Integer> nl = new LinkedList<>();
for (Integer x : l) {
nl.add(x);
}
nl.add(a[i]);
allPremutations(nl, visited, a);
visited[i] = false;
}
}
}
public static int binarySearch(long[] a, long value) {
int l = 0;
int r = a.length - 1;
while (l <= r) {
int m = (l + r) / 2;
if (a[m] == value) {
return m;
} else if (a[m] > value) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
public static void reverse(int l, int r, char ch[]) {
for (int i = 0; i < r / 2; i++) {
char c = ch[i];
ch[i] = ch[r - i - 1];
ch[r - i - 1] = c;
}
}
public static int logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static long power(long a, long n) {
if (n == 1) {
return a;
}
long pow = power(a, n / 2);
pow *= pow;
if (n % 2 != 0) {
pow *= a;
}
return pow;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF0(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) == 0) {
cnt++;
}
x <<= 1;
}
return cnt;
}
public static int log2(double n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static ArrayList<Long> primeFactors(long n) {
ArrayList<Long> a = new ArrayList<>();
while (n % 2 == 0) {
a.add(2l);
n /= 2;
}
for (long i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
a.add(i);
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
a.add(n);
}
return a;
}
// end of solution
public static BigInteger f(long n) {
if (n <= 1) {
return BigInteger.ONE;
}
long t = n - 1;
BigInteger b = new BigInteger(t + "");
BigInteger ans = new BigInteger(n + "");
while (t > 1) {
ans = ans.multiply(b);
b = b.subtract(BigInteger.ONE);
t--;
}
return ans;
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n = mod((mod(n, mod) * mod(t, mod)), mod);
t--;
}
return n;
}
public static long rev(long n) {
long t = n;
long ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(long[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalAnyBase(long n, long base) {
String w = "";
while (n > 0) {
w = n % base + w;
n /= base;
}
return w;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] >= a[i + 1]) {
return false;
}
}
return true;
}
public static void print(int[] a) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class gepair {
long x;
long y;
public gepair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pair {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pai {
long x;
int y;
public pai(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(int a, int b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(r.readLine());
}
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
/**
*/ // class RedBlackNode
static class RedBlackNode<T extends Comparable<T>> {
/**
* Possible color for this node
*/
public static final int BLACK = 0;
/**
* Possible color for this node
*/
public static final int RED = 1;
// the key of each node
public T key;
/**
* Parent of node
*/
RedBlackNode<T> parent;
/**
* Left child
*/
RedBlackNode<T> left;
/**
* Right child
*/
RedBlackNode<T> right;
// the number of elements to the left of each node
public int numLeft = 0;
// the number of elements to the right of each node
public int numRight = 0;
// the color of a node
public int color;
RedBlackNode() {
color = BLACK;
numLeft = 0;
numRight = 0;
parent = null;
left = null;
right = null;
}
// Constructor which sets key to the argument.
RedBlackNode(T key) {
this();
this.key = key;
}
}// end class RedBlackNode
static class RedBlackTree<T extends Comparable<T>> {
// Root initialized to nil.
private RedBlackNode<T> nil = new RedBlackNode<T>();
private RedBlackNode<T> root = nil;
public RedBlackTree() {
root.left = nil;
root.right = nil;
root.parent = nil;
}
// @param: X, The node which the lefRotate is to be performed on.
// Performs a leftRotate around X.
private void leftRotate(RedBlackNode<T> x) {
// Call leftRotateFixup() which updates the numLeft
// and numRight values.
leftRotateFixup(x);
// Perform the left rotate as described in the algorithm
// in the course text.
RedBlackNode<T> y;
y = x.right;
x.right = y.left;
// Check for existence of y.left and make pointer changes
if (!isNil(y.left)) {
y.left.parent = x;
}
y.parent = x.parent;
// X's parent is nul
if (isNil(x.parent)) {
root = y;
} // X is the left child of it's parent
else if (x.parent.left == x) {
x.parent.left = y;
} // X is the right child of it's parent.
else {
x.parent.right = y;
}
// Finish of the leftRotate
y.left = x;
x.parent = y;
}// end leftRotate(RedBlackNode X)
// @param: X, The node which the leftRotate is to be performed on.
// Updates the numLeft & numRight values affected by leftRotate.
private void leftRotateFixup(RedBlackNode x) {
// Case 1: Only X, X.right and X.right.right always are not nil.
if (isNil(x.left) && isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 0;
x.right.numLeft = 1;
} // Case 2: X.right.left also exists in addition to Case 1
else if (isNil(x.left) && !isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 2 + x.right.left.numLeft
+ x.right.left.numRight;
} // Case 3: X.left also exists in addition to Case 1
else if (!isNil(x.left) && isNil(x.right.left)) {
x.numRight = 0;
x.right.numLeft = 2 + x.left.numLeft + x.left.numRight;
} // Case 4: X.left and X.right.left both exist in addtion to Case 1
else {
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 3 + x.left.numLeft + x.left.numRight
+ x.right.left.numLeft + x.right.left.numRight;
}
}// end leftRotateFixup(RedBlackNode X)
// @param: X, The node which the rightRotate is to be performed on.
// Updates the numLeft and numRight values affected by the Rotate.
private void rightRotate(RedBlackNode<T> y) {
// Call rightRotateFixup to adjust numRight and numLeft values
rightRotateFixup(y);
// Perform the rotate as described in the course text.
RedBlackNode<T> x = y.left;
y.left = x.right;
// Check for existence of X.right
if (!isNil(x.right)) {
x.right.parent = y;
}
x.parent = y.parent;
// y.parent is nil
if (isNil(y.parent)) {
root = x;
} // y is a right child of it's parent.
else if (y.parent.right == y) {
y.parent.right = x;
} // y is a left child of it's parent.
else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
}// end rightRotate(RedBlackNode y)
// @param: y, the node around which the righRotate is to be performed.
// Updates the numLeft and numRight values affected by the rotate
private void rightRotateFixup(RedBlackNode y) {
// Case 1: Only y, y.left and y.left.left exists.
if (isNil(y.right) && isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 0;
y.left.numRight = 1;
} // Case 2: y.left.right also exists in addition to Case 1
else if (isNil(y.right) && !isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 2 + y.left.right.numRight
+ y.left.right.numLeft;
} // Case 3: y.right also exists in addition to Case 1
else if (!isNil(y.right) && isNil(y.left.right)) {
y.numLeft = 0;
y.left.numRight = 2 + y.right.numRight + y.right.numLeft;
} // Case 4: y.right & y.left.right exist in addition to Case 1
else {
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 3 + y.right.numRight
+ y.right.numLeft
+ y.left.right.numRight + y.left.right.numLeft;
}
}// end rightRotateFixup(RedBlackNode y)
public void insert(T key) {
insert(new RedBlackNode<T>(key));
}
// @param: z, the node to be inserted into the Tree rooted at root
// Inserts z into the appropriate position in the RedBlackTree while
// updating numLeft and numRight values.
private void insert(RedBlackNode<T> z) {
// Create a reference to root & initialize a node to nil
RedBlackNode<T> y = nil;
RedBlackNode<T> x = root;
// While we haven't reached a the end of the tree keep
// tryint to figure out where z should go
while (!isNil(x)) {
y = x;
// if z.key is < than the current key, go left
if (z.key.compareTo(x.key) < 0) {
// Update X.numLeft as z is < than X
x.numLeft++;
x = x.left;
} // else z.key >= X.key so go right.
else {
// Update X.numGreater as z is => X
x.numRight++;
x = x.right;
}
}
// y will hold z's parent
z.parent = y;
// Depending on the value of y.key, put z as the left or
// right child of y
if (isNil(y)) {
root = z;
} else if (z.key.compareTo(y.key) < 0) {
y.left = z;
} else {
y.right = z;
}
// Initialize z's children to nil and z's color to red
z.left = nil;
z.right = nil;
z.color = RedBlackNode.RED;
// Call insertFixup(z)
insertFixup(z);
}// end insert(RedBlackNode z)
// @param: z, the node which was inserted and may have caused a violation
// of the RedBlackTree properties
// Fixes up the violation of the RedBlackTree properties that may have
// been caused during insert(z)
private void insertFixup(RedBlackNode<T> z) {
RedBlackNode<T> y = nil;
// While there is a violation of the RedBlackTree properties..
while (z.parent.color == RedBlackNode.RED) {
// If z's parent is the the left child of it's parent.
if (z.parent == z.parent.parent.left) {
// Initialize y to z 's cousin
y = z.parent.parent.right;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black & z is a right child
else if (z == z.parent.right) {
// leftRotaet around z's parent
z = z.parent;
leftRotate(z);
} // Case 3: else y is black & z is a left child
else {
// recolor and rotate round z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
rightRotate(z.parent.parent);
}
} // If z's parent is the right child of it's parent.
else {
// Initialize y to z's cousin
y = z.parent.parent.left;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black and z is a left child
else if (z == z.parent.left) {
// rightRotate around z's parent
z = z.parent;
rightRotate(z);
} // Case 3: if y is black and z is a right child
else {
// recolor and rotate around z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
leftRotate(z.parent.parent);
}
}
}
// Color root black at all times
root.color = RedBlackNode.BLACK;
}// end insertFixup(RedBlackNode z)
// @param: node, a RedBlackNode
// @param: node, the node with the smallest key rooted at node
public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) {
// while there is a smaller key, keep going left
while (!isNil(node.left)) {
node = node.left;
}
return node;
}// end treeMinimum(RedBlackNode node)
// @param: X, a RedBlackNode whose successor we must find
// @return: return's the node the with the next largest key
// from X.key
public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) {
// if X.left is not nil, call treeMinimum(X.right) and
// return it's value
if (!isNil(x.left)) {
return treeMinimum(x.right);
}
RedBlackNode<T> y = x.parent;
// while X is it's parent's right child...
while (!isNil(y) && x == y.right) {
// Keep moving up in the tree
x = y;
y = y.parent;
}
// Return successor
return y;
}// end treeMinimum(RedBlackNode X)
// @param: z, the RedBlackNode which is to be removed from the the tree
// Remove's z from the RedBlackTree rooted at root
public void remove(RedBlackNode<T> v) {
RedBlackNode<T> z = search(v.key);
// Declare variables
RedBlackNode<T> x = nil;
RedBlackNode<T> y = nil;
// if either one of z's children is nil, then we must remove z
if (isNil(z.left) || isNil(z.right)) {
y = z;
} // else we must remove the successor of z
else {
y = treeSuccessor(z);
}
// Let X be the left or right child of y (y can only have one child)
if (!isNil(y.left)) {
x = y.left;
} else {
x = y.right;
}
// link X's parent to y's parent
x.parent = y.parent;
// If y's parent is nil, then X is the root
if (isNil(y.parent)) {
root = x;
} // else if y is a left child, set X to be y's left sibling
else if (!isNil(y.parent.left) && y.parent.left == y) {
y.parent.left = x;
} // else if y is a right child, set X to be y's right sibling
else if (!isNil(y.parent.right) && y.parent.right == y) {
y.parent.right = x;
}
// if y != z, trasfer y's satellite data into z.
if (y != z) {
z.key = y.key;
}
// Update the numLeft and numRight numbers which might need
// updating due to the deletion of z.key.
fixNodeData(x, y);
// If y's color is black, it is a violation of the
// RedBlackTree properties so call removeFixup()
if (y.color == RedBlackNode.BLACK) {
removeFixup(x);
}
}// end remove(RedBlackNode z)
// @param: y, the RedBlackNode which was actually deleted from the tree
// @param: key, the value of the key that used to be in y
private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) {
// Initialize two variables which will help us traverse the tree
RedBlackNode<T> current = nil;
RedBlackNode<T> track = nil;
// if X is nil, then we will start updating at y.parent
// Set track to y, y.parent's child
if (isNil(x)) {
current = y.parent;
track = y;
} // if X is not nil, then we start updating at X.parent
// Set track to X, X.parent's child
else {
current = x.parent;
track = x;
}
// while we haven't reached the root
while (!isNil(current)) {
// if the node we deleted has a different key than
// the current node
if (y.key != current.key) {
// if the node we deleted is greater than
// current.key then decrement current.numRight
if (y.key.compareTo(current.key) > 0) {
current.numRight--;
}
// if the node we deleted is less than
// current.key thendecrement current.numLeft
if (y.key.compareTo(current.key) < 0) {
current.numLeft--;
}
} // if the node we deleted has the same key as the
// current node we are checking
else {
// the cases where the current node has any nil
// children and update appropriately
if (isNil(current.left)) {
current.numLeft--;
} else if (isNil(current.right)) {
current.numRight--;
} // the cases where current has two children and
// we must determine whether track is it's left
// or right child and update appropriately
else if (track == current.right) {
current.numRight--;
} else if (track == current.left) {
current.numLeft--;
}
}
// update track and current
track = current;
current = current.parent;
}
}//end fixNodeData()
// @param: X, the child of the deleted node from remove(RedBlackNode v)
// Restores the Red Black properties that may have been violated during
// the removal of a node in remove(RedBlackNode v)
private void removeFixup(RedBlackNode<T> x) {
RedBlackNode<T> w;
// While we haven't fixed the tree completely...
while (x != root && x.color == RedBlackNode.BLACK) {
// if X is it's parent's left child
if (x == x.parent.left) {
// set w = X's sibling
w = x.parent.right;
// Case 1, w's color is red.
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
leftRotate(x.parent);
w = x.parent.right;
}
// Case 2, both of w's children are black
if (w.left.color == RedBlackNode.BLACK
&& w.right.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's right child is black
if (w.right.color == RedBlackNode.BLACK) {
w.left.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
rightRotate(w);
w = x.parent.right;
}
// Case 4, w = black, w.right = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.right.color = RedBlackNode.BLACK;
leftRotate(x.parent);
x = root;
}
} // if X is it's parent's right child
else {
// set w to X's sibling
w = x.parent.left;
// Case 1, w's color is red
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
rightRotate(x.parent);
w = x.parent.left;
}
// Case 2, both of w's children are black
if (w.right.color == RedBlackNode.BLACK
&& w.left.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's left child is black
if (w.left.color == RedBlackNode.BLACK) {
w.right.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
leftRotate(w);
w = x.parent.left;
}
// Case 4, w = black, and w.left = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.left.color = RedBlackNode.BLACK;
rightRotate(x.parent);
x = root;
}
}
}// end while
// set X to black to ensure there is no violation of
// RedBlack tree Properties
x.color = RedBlackNode.BLACK;
}// end removeFixup(RedBlackNode X)
// @param: key, the key whose node we want to search for
// @return: returns a node with the key, key, if not found, returns null
// Searches for a node with key k and returns the first such node, if no
// such node is found returns null
public RedBlackNode<T> search(T key) {
// Initialize a pointer to the root to traverse the tree
RedBlackNode<T> current = root;
// While we haven't reached the end of the tree
while (!isNil(current)) {
// If we have found a node with a key equal to key
if (current.key.equals(key)) // return that node and exit search(int)
{
return current;
} // go left or right based on value of current and key
else if (current.key.compareTo(key) < 0) {
current = current.right;
} // go left or right based on value of current and key
else {
current = current.left;
}
}
// we have not found a node whose key is "key"
return null;
}// end search(int key)
// @param: key, any Comparable object
// @return: return's the number of elements greater than key
public int numGreater(T key) {
// Call findNumGreater(root, key) which will return the number
// of nodes whose key is greater than key
return findNumGreater(root, key);
}// end numGreater(int key)
// @param: key, any Comparable object
// @return: return's teh number of elements smaller than key
public int numSmaller(T key) {
// Call findNumSmaller(root,key) which will return
// the number of nodes whose key is greater than key
return findNumSmaller(root, key);
}// end numSmaller(int key)
// @param: node, the root of the tree, the key who we must
// compare other node key's to.
// @return: the number of nodes greater than key.
public int findNumGreater(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, all elements right of node are
// greater than key, add this to our total and look to the left
else if (key.compareTo(node.key) < 0) {
return 1 + node.numRight + findNumGreater(node.left, key);
} // If key is greater than node.key, then look to the right as
// all elements to the left of node are smaller than key
else {
return findNumGreater(node.right, key);
}
}// end findNumGreater(RedBlackNode, int key)
/**
* Returns sorted list of keys greater than key. Size of list will not
* exceed maxReturned
*
* @param key Key to search for
* @param maxReturned Maximum number of results to return
* @return List of keys greater than key. List may not exceed
* maxReturned
*/
public List<T> getGreaterThan(T key, Integer maxReturned) {
List<T> list = new ArrayList<T>();
getGreaterThan(root, key, list);
return list.subList(0, Math.min(maxReturned, list.size()));
}
private void getGreaterThan(RedBlackNode<T> node, T key,
List<T> list) {
if (isNil(node)) {
return;
} else if (node.key.compareTo(key) > 0) {
getGreaterThan(node.left, key, list);
list.add(node.key);
getGreaterThan(node.right, key, list);
} else {
getGreaterThan(node.right, key, list);
}
}
// @param: node, the root of the tree, the key who we must compare other
// node key's to.
// @return: the number of nodes smaller than key.
public int findNumSmaller(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, look to the left as all
// elements on the right of node are greater than key
else if (key.compareTo(node.key) <= 0) {
return findNumSmaller(node.left, key);
} // If key is larger than node.key, all elements to the left of
// node are smaller than key, add this to our total and look
// to the right.
else {
return 1 + node.numLeft + findNumSmaller(node.right, key);
}
}// end findNumSmaller(RedBlackNode nod, int key)
// @param: node, the RedBlackNode we must check to see whether it's nil
// @return: return's true of node is nil and false otherwise
private boolean isNil(RedBlackNode node) {
// return appropriate value
return node == nil;
}// end isNil(RedBlackNode node)
// @return: return's the size of the tree
// Return's the # of nodes including the root which the RedBlackTree
// rooted at root has.
public int size() {
// Return the number of nodes to the root's left + the number of
// nodes on the root's right + the root itself.
return root.numLeft + root.numRight + 1;
}// end size()
}// end class RedBlackTree
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 925438fe8a01d7642934863203755898 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class B1556 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int t=0; t<T; t++) {
int N = in.nextInt();
List<Integer> odd = new ArrayList<>();
List<Integer> even = new ArrayList<>();
for (int n=0; n<N; n++) {
int a = in.nextInt();
((a%2 == 0) ? even : odd).add(n);
}
long answer;
if (odd.size() == even.size()) {
answer = Math.min(count(odd), count(even));
} else if (odd.size()+1 == even.size()) {
answer = count(even);
} else if (even.size()+1 == odd.size()) {
answer = count(odd);
} else {
answer = -1;
}
System.out.println(answer);
}
}
static long count(List<Integer> list) {
long result = 0;
int expected = 0;
for (int value : list) {
result += Math.abs(expected - value);
expected += 2;
}
return result;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a06517427c98108aa4f6748fbc86f429 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class b {
static BufferedReader bf;
static PrintWriter out;
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int t = nextInt();
while(t-->0){
solve();
}
}
public static void solve()throws IOException{
int n = nextInt();
int[]arr = nextIntArray(n);
List<Integer>odd = new ArrayList<>();
List<Integer>even = new ArrayList<>();
for(int i =0;i<n;i++){
if(arr[i]%2 == 0){
even.add(i);
}
else{
odd.add(i);
}
}
if(Math.abs(odd.size() - even.size()) > 1){
println(-1);
return;
}
long count = 0;
if(odd.size() == even.size()){
println(Math.min(count(odd),count(even)));
}
else{
if(odd.size() > even.size()){
println(count(odd));
}
else{
println(count(even));
}
}
}
public static long count(List<Integer>list){
long cnt = 0;
int j = 0;
for(int i = 0;i<list.size();i++){
cnt += (Math.abs(list.get(i) - j));
j += 2;
}
return cnt;
}
public static int forward(int []arr,int j,boolean even,int[]right){
int count = 0;
boolean check = false;
for(int i = j+1;i<arr.length;i++){
if(even && arr[i]%2 == 1){
return right[i]+1;
}
else if(!even && arr[i]%2 == 0){
return right[i]+1;
}
}
return arr.length+1;
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int toInt(String s){
return Integer.parseInt(s);
}
public static long toLong(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static int nextInt()throws IOException{
return Integer.parseInt(bf.readLine());
}
public static long nextLong()throws IOException{
return Long.parseLong(bf.readLine());
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static int[] nextIntArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
int[]arr = new int[n];
for(int i =0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
}
return arr;
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
}
// if a problem is related to binary string it could also be related to parenthesis
// try to use binary search in the question it might work
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+ or a,b,c,d in general
// gcd(1.p1,2.p2,3.p3,4.p4....n.pn) cannot be greater than 2 it has been proved | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 3d197d5cfe0803c175128b2f98a3c945 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static int sum(int idx , int bit[])
{
int sum = 0;
while(idx > 0)
{
sum += bit[idx];
idx -= idx&(-idx);
}
return sum;
}
static void update(int n , int idx , int val , int bit[])
{
while(idx <= n)
{
bit[idx] += val;
idx += idx&(-idx);
}
}
static long mod = 1000000007;
static long pow(long a , long b)
{
if(b == 0)
return 1;
long ans = pow(a,b/2);
if(b%2 == 0)
return ans*ans%mod;
return ans*ans%mod*a%mod;
}
static long f(long v)
{
if(v <= 0)
return 0;
return (v*(v+1)/2);
}
public static void main(String []args) throws IOException
{
Reader sc = new Reader();
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int arr[] = new int[n];
int o = 0 , z = 0;
for(int i = 0 ; i < n ; i++)
{
arr[i] = sc.nextInt();
arr[i] %= 2;
if(arr[i] == 0)
z++;
else
o++;
}
if(Math.abs(o-z) > 1)
System.out.println(-1);
else
{
if(o == z)
{
TreeMap<Integer,Integer> one = new TreeMap<Integer,Integer>();
TreeMap<Integer,Integer> zero = new TreeMap<Integer,Integer>();
for(int i = 0 ; i < n ; i++)
{
if(arr[i] == 0)
zero.put(i,1);
else
one.put(i,1);
}
int start = 0;
int ans = Integer.MAX_VALUE;
int ass = 0 ;
for(int i = 0 ; i < n ; i++)
{
int pos = -1;
if(start == 0 && zero.higherKey(i-1) != null)
pos = zero.higherKey(i-1);
if(start == 1 && one.higherKey(i-1) != null)
pos = one.higherKey(i-1);
if(pos == -1)
break;
ass += pos-i;
if(start == 0)
{
zero.remove(pos);
one.put(pos,1);
}
else
{
one.remove(pos);
zero.put(pos,1);
}
start = 1-start;
}
ans = Math.min(ass,ans);
one.clear();
zero.clear();
for(int i = 0 ; i < n ; i++)
{
if(arr[i] == 0)
zero.put(i,1);
else
one.put(i,1);
}
start = 1;
// int ans = Integer.MAX_VALUE;
ass = 0 ;
for(int i = 0 ; i < n ; i++)
{
int pos = -1;
if(start == 0 && zero.higherKey(i-1) != null)
pos = zero.higherKey(i-1);
if(start == 1 && one.higherKey(i-1) != null)
pos = one.higherKey(i-1);
if(pos == -1)
break;
ass += pos-i;
if(start == 0)
{
zero.remove(pos);
one.put(pos,1);
}
else
{
one.remove(pos);
zero.put(pos,1);
}
start = 1-start;
}
ans = Math.min(ass,ans);
System.out.println(ans);
}
else
{
TreeMap<Integer,Integer> one = new TreeMap<Integer,Integer>();
TreeMap<Integer,Integer> zero = new TreeMap<Integer,Integer>();
for(int i = 0 ; i < n ; i++)
{
if(arr[i] == 0)
zero.put(i,1);
else
one.put(i,1);
}
int start = 0;
if(o > z)
start = 1;
int ans = Integer.MAX_VALUE;
int ass = 0 ;
for(int i = 0 ; i < n ; i++)
{
int pos = -1;
if(start == 0 && zero.higherKey(i-1) != null)
pos = zero.higherKey(i-1);
if(start == 1 && one.higherKey(i-1) != null)
pos = one.higherKey(i-1);
if(pos == -1)
break;
ass += pos-i;
if(start == 0)
{
zero.remove(pos);
one.put(pos,1);
}
else
{
one.remove(pos);
zero.put(pos,1);
}
start = 1-start;
}
ans = Math.min(ass,ans);
System.out.println(ans);
}
}
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 23d13f505116bef06977e54f9307f2ba | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
//import javafx.util.*;
public class Main
{
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static int INF = Integer.MAX_VALUE;
static int NINF = Integer.MIN_VALUE;
public static void main (String[] args) throws java.lang.Exception
{
int t = i();
while(t-- > 0){
int n = i();
int[] arr = input(n);
if(n == 1){
out.println(0);
continue;
}
int odd = 0;
int even = 0;
for(int i = 0;i < n;i++){
if(arr[i]%2 == 0){
even++;
}else{
odd++;
}
}
if(Math.abs(odd - even) > 1){
out.println(-1);
continue;
}
if(odd > even){
out.println(helper(arr,n,1));
}else if(even > odd){
out.println(helper(arr,n,0));
}else{
out.println(Math.min(helper(arr,n,1),helper(arr,n,0)));
}
}
out.close();
}
public static int helper(int[] arr, int n, int index){
int ans = 0;
for(int i = 0;i < n;i++){
if(arr[i]%2 == 0){
ans += Math.abs(i - index);
index += 2;
}
}
return ans;
}
public static void sort(int [] arr){
ArrayList<Integer> ls = new ArrayList<>();
for(int x : arr){
ls.add(x);
}
Collections.sort(ls);
for(int i = 0;i < arr.length;i++){
arr[i] = ls.get(i);
}
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
}
class Pair implements Comparable<Pair>{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair obj)
{
return (this.x - obj.x);
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 104a84ef1590a842fbf24822fcbf82ee | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // package faltu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
public class Main {
static int lower_bound(long array[], long key)
{
int low = 0, high = array.length;
int mid;
while (low < high) {
mid = low + (high - low) / 2;
if (key <= array[mid]) {
high = mid;
}
else {
low = mid + 1;
}
}
if (low < array.length && array[low] < key) {
low++;
}
return low;
}
static int UpperBound(int a[], int x) {// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
public static long getClosest(long val1, long val2,long target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
static void ruffleSort(long[] a) {
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
long oi=r.nextInt(n), temp=a[i];
a[i]=a[(int)oi];
a[(int)oi]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a){
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
Arrays.sort(a);
}
int ceilIndex(int input[], int T[], int end, int s){
int start = 0;
int middle;
int len = end;
while(start <= end){
middle = (start + end)/2;
if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){
return middle+1;
}else if(input[T[middle]] < s){
start = middle+1;
}else{
end = middle-1;
}
}
return -1;
}
public static int findIndex(long arr[], long t)
{
if (arr == null) {
return -1;
}
int len = arr.length;
int i = 0;
while (i < len) {
if (arr[i] == t) {
return i;
}
else {
i = i + 1;
}
}
return -1;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a,long b)
{
return (a / gcd(a, b)) * b;
}
public static int[] swap(int a[], int left, int right)
{
int temp = a[left];
a[left] = a[right];
a[right] = temp;
return a;
}
public static void swap(long x,long max1)
{
long temp=x;
x=max1;
max1=temp;
}
public static int[] reverse(int a[], int left, int right)
{
// Reverse the sub-array
while (left < right) {
int temp = a[left];
a[left++] = a[right];
a[right--] = temp;
}
return a;
}
static int lowerLimitBinarySearch(ArrayList<Integer> A,int B) {
int n =A.size();
int first = 0,second = n;
while(first <second) {
int mid = first + (second-first)/2;
if(A.get(mid) > B) {
second = mid;
}else {
first = mid+1;
}
}
if(first < n && A.get(first) < B) {
first++;
}
return first; //1 index
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// *******----segement tree implement---*****
// -------------START--------------------------
void buildTree (int[] arr,int[] tree,int start,int end,int treeNode)
{
if(start==end)
{
tree[treeNode]=arr[start];
return;
}
buildTree(arr,tree,start,end,2*treeNode);
buildTree(arr,tree,start,end,2*treeNode+1);
tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1];
}
void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value)
{
if(start==end)
{
arr[idx]=value;
tree[treeNode]=value;
return;
}
int mid=(start+end)/2;
if(idx>mid)
{
updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value);
}
else
{
updateTree(arr,tree,start,mid,2*treeNode,idx,value);
}
tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1];
}
// disjoint set implementation --start
static void makeSet(int n)
{
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++)
{
parent[i]=i;
rank[i]=0;
}
}
static void union(int u,int v)
{
u=findpar(u);
v=findpar(v);
if(rank[u]<rank[v])parent[u]=v;
else if(rank[v]<rank[u])parent[v]=u;
else
{
parent[v]=u;
rank[u]++;
}
}
private static int findpar(int node)
{
if(node==parent[node])return node;
return parent[node]=findpar(parent[node]);
}
static int parent[];
static int rank[];
// *************end
static void presumbit(int[][]prebitsum) {
for(int i=1;i<=200000;i++) {
int z=i;
int j=0;
while(z>0) {
if((z&1)==1) {
prebitsum[i][j]+=(prebitsum[i-1][j]+1);
}else {
prebitsum[i][j]=prebitsum[i-1][j];
}
z=z>>1;
j++;
}
}
}
static ArrayList<String>powof2s;
static void powof2S() {
long i=1;
while(i<(long)2e18) {
powof2s.add(String.valueOf(i));
i*=2;
}
}
static boolean coprime(int a, long l){
return (gcd(a, l) == 1);
}
static Long MOD=(long) (1e9+7);
static int prebitsum[][];
static ArrayList<Integer>arr;
static boolean[] vis;
static ArrayList<ArrayList<Integer>>adj;
public static void main(String[] args) throws IOException
{
// sieve();
// prebitsum=new int[200001][18];
// presumbit(prebitsum);
// powof2S();
FastReader s = new FastReader();
long tt = s.nextLong();
while(tt-->0) {
int n=s.nextInt();
int odd=0,even=0;
int[]a=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]%2==0)even++;
}
odd=n-even;
if(Math.abs(odd-even)>1)System.out.println(-1);
else {
long ans=Integer.MAX_VALUE;
if(even>=odd) {
int j=0;
long sum=0;
for(int i=0;i<n;i++) {
if(a[i]%2==0) {
sum+=Math.abs(i-j);
j+=2;
}
}
ans=Math.min(ans, sum);
}
if(odd>=even){
int j=0;
long sum=0;
for(int i=0;i<n;i++) {
if(a[i]%2==1) {
sum+=Math.abs(i-j);
j+=2;
}
}
ans=Math.min(ans, sum);
}
System.out.println(ans);
}
}
}
static void DFSUtil(int v, boolean[] visited)
{
visited[v] = true;
Iterator<Integer> it = adj.get(v).iterator();
while (it.hasNext()) {
int n = it.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
static long DFS(int n)
{
boolean[] visited = new boolean[n+1];
long cnt=0;
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
DFSUtil(i, visited);
cnt++;
}
}
return cnt;
}
public static String revStr(String str){
String input = str;
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1.reverse();
return input1.toString();
}
public static String sortString(String inputString){
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static long myPow(long n, long i){
if(i==0) return 1;
if(i%2==0) return (myPow(n,i/2)%MOD * myPow(n,i/2)%MOD)%MOD;
return (n%MOD* myPow(n,i-i)%MOD)%MOD;
}
static void palindromeSubStrs(String str) {
HashSet<String>set=new HashSet<>();
char[]a =str.toCharArray();
int n=str.length();
int[][]dp=new int[n][n];
for(int g=0;g<n;g++){
for(int i=0,j=g;j<n;j++,i++){
if(!set.contains(str.substring(i,i+1))&&g==0) {
dp[i][j]=1;
set.add(str.substring(i,i+1));
}
else {
if(!set.contains(str.substring(i,j+1))&&isPalindrome(str,i,j)) {
dp[i][j]=1;
set.add(str.substring(i,j+1));
}
}
}
}
int ans=0;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
System.out.print(dp[i][j]+" ");
if(dp[i][j]==1)ans++;
}
System.out.println();
}
System.out.println(ans);
}
static boolean isPalindrome(String str,int i,int j)
{
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}
static boolean sign(long num) {
return num>0;
}
static boolean isSquare(long x){
if(x==1)return true;
long y=(long) Math.sqrt(x);
return y*y==x;
}
static long power1(long a,long b) {
if(b == 0){
return 1;
}
long ans = power(a,b/2);
ans *= ans;
if(b % 2!=0){
ans *= a;
}
return ans;
}
static void swap(StringBuilder sb,int l,int r)
{
char temp = sb.charAt(l);
sb.setCharAt(l,sb.charAt(r));
sb.setCharAt(r,temp);
}
// function to reverse the string between index l and r
static void reverse(StringBuilder sb,int l,int r)
{
while(l < r)
{
swap(sb,l,r);
l++;
r--;
}
}
// function to search a character lying between index l and r
// which is closest greater (just greater) than val
// and return it's index
static int binarySearch(StringBuilder sb,int l,int r,char val)
{
int index = -1;
while (l <= r)
{
int mid = (l+r)/2;
if (sb.charAt(mid) <= val)
{
r = mid - 1;
}
else
{
l = mid + 1;
if (index == -1 || sb.charAt(index) >= sb.charAt(mid))
index = mid;
}
}
return index;
}
// this function generates next permutation (if there exists any such permutation) from the given string
// and returns True
// Else returns false
static boolean nextPermutation(StringBuilder sb)
{
int len = sb.length();
int i = len-2;
while (i >= 0 && sb.charAt(i) >= sb.charAt(i+1))
i--;
if (i < 0)
return false;
else
{
int index = binarySearch(sb,i+1,len-1,sb.charAt(i));
swap(sb,i,index);
reverse(sb,i+1,len-1);
return true;
}
}
private static int lps(int m ,int n,String s1,String s2,int[][]mat)
{
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1.charAt(i-1)==s2.charAt(j-1))mat[i][j]=1+mat[i-1][j-1];
else mat[i][j]=Math.max(mat[i-1][j],mat[i][j-1]);
}
}
return mat[m][n];
}
static int lcs(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
// Following code is used to print LCS
// int index = L[m][n];
// int temp = index;
//
// // Create a character array to store the lcs string
// char[] lcs = new char[index+1];
// lcs[index] = '\u0000'; // Set the terminating character
//
// // Start from the right-most-bottom-most corner and
// // one by one store characters in lcs[]
// int i = m;
// int j = n;
// while (i > 0 && j > 0)
// {
// // If current character in X[] and Y are same, then
// // current character is part of LCS
// if (X.charAt(i-1) == Y.charAt(j-1))
// {
// // Put current character in result
// lcs[index-1] = X.charAt(i-1);
//
// // reduce values of i, j and index
// i--;
// j--;
// index--;
// }
//
// // If not same, then find the larger of two and
// // go in the direction of larger value
// else if (L[i-1][j] > L[i][j-1])
// i--;
// else
// j--;
// }
// return String.valueOf(lcs);
// Print the lcs
// System.out.print("LCS of "+X+" and "+Y+" is ");
// for(int k=0;k<=temp;k++)
// System.out.print(lcs[k]);
}
static long lis(long[] aa2, int n)
{
long lis[] = new long[n];
int i, j;
long max = 0;
for (i = 0; i < n; i++)
lis[i] = 1;
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (aa2[i] >= aa2[j] && lis[i] <= lis[j] + 1)
lis[i] = lis[j] + 1;
for (i = 0; i < n; i++)
if (max < lis[i])
max = lis[i];
return max;
}
static boolean isPalindrome(String str)
{
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}
static boolean issafe(int i, int j, int r,int c, char ch)
{
if (i < 0 || j < 0 || i >= r || j >= c|| ch!= '1')return false;
else return true;
}
static long power(long a, long b)
{
a %=MOD;
long out = 1;
while (b > 0) {
if((b&1)!=0)out = out * a % MOD;
a = a * a % MOD;
b >>= 1;
a*=a;
}
return out;
}
static long[] sieve;
public static void sieve()
{
int nnn=(int) 1e6+1;
long nn=(int) 1e6;
sieve=new long[(int) nnn];
int[] freq=new int[(int) nnn];
sieve[0]=0;
sieve[1]=1;
for(int i=2;i<=nn;i++)
{
sieve[i]=1;
freq[i]=1;
}
for(int i=2;i*i<=nn;i++)
{
if(sieve[i]==1)
{
for(int j=i*i;j<=nn;j+=i)
{
if(sieve[j]==1)
{
sieve[j]=0;
}
}
}
}
}
}
class decrease implements Comparator<Long> {
// Used for sorting in ascending order of
// roll number
public int compare(long a, long b)
{
return (int) (b - a);
}
@Override
public int compare(Long o1, Long o2) {
// TODO Auto-generated method stub
return (int) (o2-o1);
}
}
class pair{
long x;
long y;
long c;
char ch;
public pair(long x,long y) {
this.x=x;
this.y=y;
}
public pair(long x,char ch) {
this.x=x;
this.ch=ch;
}
public pair(long x,long y,long c)
{
this.x=x;
this.y=y;
this.c=c;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 1148e29b594819c4d5b7a6d18e4d4c11 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Ashutosh Patel (ashutoshpatelnoida@gmail.com) Linkedin : ( https://www.linkedin.com/in/ashutosh-patel-7954651ab/ )
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BTakeYourPlaces solver = new BTakeYourPlaces();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BTakeYourPlaces {
public void solve(int testNumber, InputReader sc, OutputWriter out) {
int n = sc.readInt();
int[] arr = new int[n];
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
arr[i] = sc.readInt() % 2;
if (arr[i] == 0) even++;
else odd++;
}
if (Math.abs(odd - even) > 1) {
out.printLine(-1);
return;
}
int res = 0;
ArrayList<Integer> ew = new ArrayList<>();
ArrayList<Integer> ow = new ArrayList<>();
if (even > odd) {
for (int i = 0; i < n; i++) {
if (i % 2 == 0 && arr[i] == 1) ew.add(i);
if (i % 2 != 0 && arr[i] == 0) ow.add(i);
}
for (int i = 0; i < ew.size(); i++) {
res += (Math.abs(ew.get(i) - ow.get(i)));
}
out.printLine(res);
return;
}
if (odd > even) {
for (int i = 0; i < n; i++) {
if (i % 2 == 0 && arr[i] == 0) ew.add(i);
if (i % 2 != 0 && arr[i] == 1) ow.add(i);
}
for (int i = 0; i < ew.size(); i++) {
res += (Math.abs(ew.get(i) - ow.get(i)));
}
out.printLine(res);
return;
}
int res1 = 0;
int res2 = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0 && arr[i] == 1) ew.add(i);
if (i % 2 != 0 && arr[i] == 0) ow.add(i);
}
for (int i = 0; i < ew.size(); i++) {
res1 += (Math.abs(ew.get(i) - ow.get(i)));
}
ew.clear();
ow.clear();
for (int i = 0; i < n; i++) {
if (i % 2 == 0 && arr[i] == 0) ew.add(i);
if (i % 2 != 0 && arr[i] == 1) ow.add(i);
}
for (int i = 0; i < ew.size(); i++) {
res2 += (Math.abs(ew.get(i) - ow.get(i)));
}
out.printLine(Math.min(res1, res2));
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | fda94d94abf1168716983d61143afbd4 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int c = 0;
public static void sort(int[] arr, int l, int r) {
if (l < r) {
int mid = (r + l) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, mid + 1, r);
}
}
public static void merge(int[] arr, int l1, int r1, int l2, int r2) {
int[] temp = new int[r2 - l1 + 1];
int p = 0;
int l = l1;
while (l1 <= r1 && l2 <= r2) {
if (arr[l1] <= arr[l2])
temp[p++] = arr[l1++];
else {
temp[p++] = arr[l2++];
c += r1 - l1 + 1;
}
}
while (l1 <= r1) {
temp[p++] = arr[l1++];
}
while (l2 <= r2) {
temp[p++] = arr[l2++];
}
for (int i = 0; i < p; i++) {
arr[i + l] = temp[i];
}
}
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static int weakness(int[] arr, int i) {
if (i <= 1)
return 0;
if (arr[i] == 2)
return arr[1];
return weakness(arr, i - 1) + arr[i - 1];
}
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int odd = 0, even = 0;
PriorityQueue<Integer> evenP = new PriorityQueue<>();
PriorityQueue<Integer> oddP = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
if ((arr[i] & 1) == 0) {
even++;
evenP.add(i);
} else {
odd++;
oddP.add(i);
}
}
if (Math.abs(even - odd) > 1)
pw.println(-1);
else {
int result = 0;
if (even > odd) {
int c = 1;
while (!oddP.isEmpty()) {
result += Math.abs(oddP.poll() - c);
c += 2;
}
pw.println(result);
} else if (odd > even) {
int c = 1;
while (!evenP.isEmpty()) {
result += Math.abs(evenP.poll() - c);
c += 2;
}
pw.println(result);
} else {
int r1 = 0, r2 = 0;
int c = 1;
while (!oddP.isEmpty()) {
r1 += Math.abs(oddP.poll() - c);
c += 2;
}
c = 1;
while (!evenP.isEmpty()) {
r2 += Math.abs(evenP.poll() - c);
c += 2;
}
pw.println(Math.min(r1, r2));
}
}
}
pw.flush();
}
//
static class Pair implements Comparable<Pair> {
String x;
int y;
public Pair(String x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public int compareTo(Pair p) {
if (x.charAt(0) == p.x.charAt(0)) {
String s1 = x + p.x;
String s2 = p.x + x;
return s1.compareTo(s2);
} else
return x.charAt(0) - p.x.charAt(0);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextlongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] array = new Long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
public char[] nextCharArray(int n) throws IOException {
char[] array = new char[n];
String string = next();
for (int i = 0; i < n; i++) {
array[i] = string.charAt(i);
}
return array;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 29eb9463f4032e8dad6b0bc11687e52e | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static class Pair implements Comparable < Pair > {
int d;
int i;
Pair(int d, int i) {
this.d = d;
this.i = i;
}
public int compareTo(Pair o) {
if (this.d == o.d)
return o.i - this.i;
return this.d - o.d;
}
}
public static class SegmentTree {
long[] st;
long[] lazy;
int n;
SegmentTree(long[] arr, int n) {
this.n = n;
st = new long[4 * n];
lazy = new long[4 * n];
construct(arr, 0, n - 1, 0);
}
public long construct(long[] arr, int si, int ei, int node) {
if (si == ei) {
st[node] = arr[si];
return arr[si];
}
int mid = (si + ei) / 2;
long left = construct(arr, si, mid, 2 * node + 1);
long right = construct(arr, mid + 1, ei, 2 * node + 2);
st[node] = left + right;
return st[node];
}
public long get(int l, int r) {
return get(0, n - 1, l, r, 0);
}
public long get(int si, int ei, int l, int r, int node) {
if (r < si || l > ei)
return 0;
if (lazy[node] != 0) {
st[node] += lazy[node] * (ei - si + 1);
if (si != ei) {
lazy[2 * node + 1] += lazy[node];
lazy[2 * node + 2] += lazy[node];
}
lazy[node] = 0;
}
if (l <= si && r >= ei)
return st[node];
int mid = (si + ei) / 2;
return get(si, mid, l, r, 2 * node + 1) + get(mid + 1, ei, l, r, 2 * node + 2);
}
public void update(int index, int value) {
update(0, n - 1, index, 0, value);
}
public void update(int si, int ei, int index, int node, int val) {
if (si == ei) {
st[node] = val;
return;
}
int mid = (si + ei) / 2;
if (index <= mid) {
update(si, mid, index, 2 * node + 1, val);
} else {
update(mid + 1, ei, index, 2 * node + 2, val);
}
st[node] = st[2 * node + 1] + st[2 * node + 2];
}
public void rangeUpdate(int l, int r, int val) {
rangeUpdate(0, n - 1, l, r, 0, val);
}
public void rangeUpdate(int si, int ei, int l, int r, int node, int val) {
if (r < si || l > ei)
return;
if (lazy[node] != 0) {
st[node] += lazy[node] * (ei - si + 1);
if (si != ei) {
lazy[2 * node + 1] += lazy[node];
lazy[2 * node + 2] += lazy[node];
}
lazy[node] = 0;
}
if (l <= si && r >= ei) {
st[node] += val * (ei - si + 1);
if (si != ei) {
lazy[2 * node + 1] += val;
lazy[2 * node + 2] += val;
}
return;
}
int mid = (si + ei) / 2;
rangeUpdate(si, mid, l, r, 2 * node + 1, val);
rangeUpdate(mid + 1, ei, l, r, 2 * node + 2, val);
st[node] = st[2 * node + 1] + st[2 * node + 2];
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
try {
System.setIn(new FileInputStream(new File("input.txt")));
System.setOut(new PrintStream(new File("output.txt")));
} catch (Exception e) {
}
}
Reader sc = new Reader();
int tc = sc.nextInt();
StringBuilder sb = new StringBuilder();
while (tc-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
int e = 0;
int o = 0;
ArrayList<Integer> even = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
if (arr[i] % 2 == 0) {
e += 1;
even.add(i);
} else {
o += 1;
odd.add(i);
}
}
int ans = Integer.MAX_VALUE;
if (n % 2 == Math.abs(o - e)) {
if (n % 2 == 1) {
int count = 0;
int idx = 0;
if (o > e) {
for (int i = 0; i < odd.size(); i++) {
count += Math.abs(odd.get(i) - idx);
idx += 2;
}
} else {
for (int i = 0; i < even.size(); i++) {
count += Math.abs(even.get(i) - idx);
idx += 2;
}
}
ans = count;
sb.append(ans);
} else {
int count = 0;
int idx = 0;
for (int i = 0; i < odd.size(); i++) {
count += Math.abs(odd.get(i) - idx);
idx += 2;
}
ans = Math.min(ans, count);
count = 0;
idx = 0;
for (int i = 0; i < even.size(); i++) {
count += Math.abs(even.get(i) - idx);
idx += 2;
}
ans = Math.min(ans, count);
sb.append(ans);
}
} else {
sb.append("-1");
}
sb.append("\n");
}
System.out.println(sb);
}
public static int get(int[] dsu, int x) {
if (dsu[x] == x)
return x;
int k = get(dsu, dsu[x]);
dsu[x] = k;
return k;
}
static int gcd(int a, int b) {
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
public static int Xor(int n) {
if (n % 4 == 0)
return n;
// If n%4 gives remainder 1
if (n % 4 == 1)
return 1;
// If n%4 gives remainder 2
if (n % 4 == 2)
return n + 1;
// If n%4 gives remainder 3
return 0;
}
public static long pow(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if ((b & 1) > 0)
res = (res * a) % mod;
b = b >> 1;
a = ((a % mod) * (a % mod)) % mod;
}
return (res % mod + mod) % mod;
}
public static double digit(long num) {
return Math.floor(Math.log10(num) + 1);
}
public static boolean isPos(int idx, long[] arr, long[] diff) {
if (idx == 0) {
for (int i = 0; i <= Math.min(arr[0], arr[1]); i++) {
diff[idx] = i;
arr[0] -= i;
arr[1] -= i;
if (isPos(idx + 1, arr, diff)) {
return true;
}
arr[0] += i;
arr[1] += i;
}
} else if (idx == 1) {
if (arr[2] - arr[1] >= 0) {
long k = arr[1];
diff[idx] = k;
arr[1] = 0;
arr[2] -= k;
if (isPos(idx + 1, arr, diff)) {
return true;
}
arr[1] = k;
arr[2] += k;
} else
return false;
} else {
if (arr[2] == arr[0] && arr[1] == 0) {
diff[2] = arr[2];
return true;
} else {
return false;
}
}
return false;
}
public static boolean isPal(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i))
return false;
}
return true;
}
static int upperBound(ArrayList<Long> arr, long key) {
int mid, N = arr.size();
// Initialise starting index and
// ending index
int low = 0;
int high = N;
// Till low is less than high
while (low < high && low != N) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is greater than or equal
// to arr[mid], then find in
// right subarray
if (key >= arr.get(mid)) {
low = mid + 1;
}
// If key is less than arr[mid]
// then find in left subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then upper bound
// does not exists in the array
return low;
}
static int lowerBound(ArrayList<Long> array, long key) {
// Initialize starting index and
// ending index
int low = 0, high = array.size();
int mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array.get(mid)) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if (low < array.size() && array.get(low) < key) {
low++;
}
// Returning the lower_bound index
return low;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | b5759340038ac68cad0976238ca585d6 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class frogJump {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int cEven = 0;
int cOdd = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0)
cEven++;
else
cOdd++;
}
if(Math.abs(cEven-cOdd)>1) {
//to make sure that the number of even elements equal the number of odd elements, or one of them exceeds the other by one, so that the elements of the resulting array can be alternating between even and odd
pw.println(-1);
}
else {
if(cEven>cOdd) {
int result = 0;
int currentIndex = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0) {
result += Math.abs((i-currentIndex));
currentIndex += 2;
}
}
pw.println(result);
}
else if(cOdd>cEven){
int result = 0;
int currentIndex = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==1) {
result += Math.abs((i-currentIndex));
currentIndex += 2;
}
}
pw.println(result);
}
else {
int result1 = 0;
int currentIndex = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==1) {
result1 += Math.abs((i-currentIndex));
currentIndex += 2;
}
}
int result2 = 0;
currentIndex = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0) {
result2 += Math.abs((i-currentIndex));
currentIndex += 2;
}
}
pw.println(Math.min(result1, result2));
}
}
}
pw.flush();
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5884c6ef1c98fc7f35b7f451202826b5 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
// cd C:\Users\Lenovo\Desktop\New
//ArrayList<Integer> a=new ArrayList<>();
//List<Integer> lis=new ArrayList<>();
//StringBuilder ans = new StringBuilder();
//HashMap<Integer,Integer> map=new HashMap<>();
public class cf {
static FastReader in=new FastReader();
static final Random random=new Random();
static long mod=1000000007L;
public static void main(String args[]) throws IOException {
FastReader sc=new FastReader();
//Scanner s=new Scanner(System.in);
int tt=sc.nextInt();
//int tt=1;
while(tt-->0){
//StringBuilder ar = new StringBuilder();
int n=sc.nextInt();
int odd=0;
int even=0;
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
if(arr[i]%2==0){
even++;
}
}
odd=n-even;
if(Math.abs(odd-even)>1){
System.out.println(-1);
continue;
}
long ans=Integer.MAX_VALUE;
if(even>=odd){
int j=0;
long sum=0l;
for(int i=0;i<n;i++){
if(arr[i]%2==0){
sum+=Math.abs(i-j);
j+=2;
}
}
ans=Math.min(ans,sum);
}
if(odd>=even){
int j=0;
long sum=0l;
for(int i=0;i<n;i++){
if(arr[i]%2==1){
sum+=Math.abs(i-j);
j+=2;
}
}
ans=Math.min(ans,sum);
}
System.out.println(ans);
}
}
static int countprimefactors(int n){
int ans=0;
int z=(int)Math.sqrt(n);
for(int i=2;i<=z;i++){
while(n%i==0){
ans++;
n=n/i;
}
}
if(n>1){
ans++;
}
return ans;
}
static int count(int arr[],int idx,long sum,int []dp){
if(idx>=arr.length){
return 0;
}
if(dp[idx]!=-1){
return dp[idx];
}
if(arr[idx]<0){
return dp[idx]=Math.max(1+count(arr,idx+1,sum+arr[idx],dp),count(arr,idx+1,sum,dp));
}
else{
return dp[idx]=1+count(arr,idx+1,sum+arr[idx],dp);
}
}
static String reverse(String s){
String ans="";
for(int i=s.length()-1;i>=0;i--){
ans+=s.charAt(i);
}
return ans;
}
static int find_max(int []check,int y){
int max=0;
for(int i=y;i>=0;i--){
if(check[i]!=0){
max=i;
break;
}
}
return max;
}
static void dfs(int [][]arr,int row,int col,boolean [][]seen,int n){
if(row<0 || col<0 || row==n || col==n){
return;
}
if(arr[row][col]==1){
return;
}
if(seen[row][col]==true){
return;
}
seen[row][col]=true;
dfs(arr,row+1,col,seen,n);
dfs(arr,row,col+1,seen,n);
dfs(arr,row-1,col,seen,n);
dfs(arr,row,col-1,seen,n);
}
static int msb(int x){
int ans=0;
while(x!=0){
x=x/2;
ans++;
}
return ans;
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
/* static boolean checkprime(int n1)
{
if(n1%2==0||n1%3==0)
return false;
else
{
for(int i=5;i*i<=n1;i+=6)
{
if(n1%i==0||n1%(i+2)==0)
return false;
}
return true;
}
}
*/
/* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, Integer> entry = iterator.next();
int value = entry.getValue();
if(value==1){
iterator.remove();
}
else{
entry.setValue(value-1);
}
}
*/
static class Pair implements Comparable
{
int a,b;
public String toString()
{
return a+" " + b;
}
public Pair(int x , int y)
{
a=x;b=y;
}
@Override
public int compareTo(Object o) {
Pair p = (Pair)o;
if(p.a!=a){
return a-p.a;//in
}
else{
return b-p.b;//
}
}
}
/* public static boolean checkAP(List<Integer> lis){
for(int i=1;i<lis.size()-1;i++){
if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){
return false;
}
}
return true;
}
public static int minBS(int[]arr,int val){
int l=-1;
int r=arr.length;
while(r>l+1){
int mid=(l+r)/2;
if(arr[mid]>=val){
r=mid;
}
else{
l=mid;
}
}
return r;
}
public static int maxBS(int[]arr,int val){
int l=-1;
int r=arr.length;
while(r>l+1){
int mid=(l+r)/2;
if(arr[mid]<=val){
l=mid;
}
else{
r=mid;
}
}
return l;
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 1b8792a6bef8230bfd324b16939931cd | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int getAfter(int[] a , int pos ,int x){
for(int i=pos; i<a.length ;i++){
if(a[i]%2 != x)
return i;
}
return -1;
}
static int getBefore(int[] a , int pos , int x){
for(int i=pos; i>=0 ;i--)
if(a[i]%2 != x)
return i;
return -1;
}
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt() , even = 0;
int[] a = new int[n];
for(int i=0; i<n ;i++) {
a[i] = sc.nextInt();
if (a[i] % 2 == 0)
even++;
}
int odd = n-even;
if(Math.abs(even - odd) > 1)
pw.println(-1);
else{
long ans = (long) 1e+18;
if(even>=odd){
int next = 0;
long c = 0;
for(int i=0; i<n ;i++){
if(a[i]%2 == 0){
c += Math.abs(i-next);
next += 2;
}
}
ans = Math.min(ans , c);
}
if(odd >= even){
int next = 0;
long c = 0;
for(int i=0; i<n ;i++){
if(a[i]%2 == 1){
c += Math.abs(i-next);
next += 2;
}
}
ans = Math.min(ans , c);
}
pw.println(ans);
}
}
pw.flush();
}
static class pair implements Comparable <pair>{
int x , y;
pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(pair p){
if(p.x > x)
return -2;
else if(p.x < x)
return 2;
else{
if(p.y > y)
return -2;
else
return 2;
}
}
public String toString(){
return x+" "+y;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 1ead9efcc82557cf7ae804fbb1cc3dba | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
ArrayList<Integer> odd = new ArrayList<>();
ArrayList<Integer> even = new ArrayList<>();
int oc = 0, ec = 0;
for (int i = 0; i < n; i++) {
int k = in.nextInt();
if (k % 2 == 0) {
even.add(oc);
ec++;
} else {
odd.add(ec);
oc++;
}
}
int ans = -1;
int m1 = odd.size(), m2 = even.size();
if (n % 2 == 1) {
if (Math.min(m1, m2) + 1 == Math.max(m1, m2)) {
if (odd.size() < even.size()) {
odd = even;
}
ans = 0;
for (int i = 0; i < (n + 1) / 2; i++) {
ans += Math.abs(i - odd.get(i));
}
}
} else if (m1 == m2) {
int a1 = 0, a2 = 0;
for (int i = 0; i < (n + 1) / 2; i++) {
a1 += Math.abs(i - odd.get(i));
}
for (int i = 0; i < (n + 1) / 2; i++) {
a2 += Math.abs(i - even.get(i));
}
ans = Math.min(a1, a2);
}
out.println(ans);
}
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c + " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | e3c2ef77e4f50da9d6c305a6c42b6684 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class TakeYourPlace {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a[]=new int[n];
int even=0,odd=0;
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
a[i]=a[i]%2;
if(a[i]==0)even++;
else odd++;
}
if(Math.abs(even-odd)>1)System.out.println(-1);
else if(even>odd)System.out.println(calculate(a,n,0));
else if(odd>even)System.out.println(calculate(a,n,1));
else System.out.println(Math.min(calculate(a,n,1), calculate(a,n,0)));
}
}
static int calculate(int a[],int n,int index) {
int count=0;
for(int i=0;i<n;i++) {
if(a[i]==0) {
count+=Math.abs(i-index);
index+=2;
}
}
return count;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | d570bf26274a3a8eb99bfc20dc67b068 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.awt.Container;
import java.awt.image.SampleModel;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import javax.naming.TimeLimitExceededException;
import java.io.PrintStream;
public class Solution {
static class Pair<T,V>{
T first;
V second;
public Pair(T first, V second) {
super();
this.first = first;
this.second = second;
}
}
// public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static FastScanner fs=new FastScanner();
private static Scanner sc=new Scanner(System.in);
private static int uperBound(long[] arr, long val) {
int start= 0;
int end=arr.length;
while(start<end) {
int mid=(start+end)/2;
if( arr[mid]==val ) {
return mid;
}
if( arr[mid]>val ) {
end=mid-1;
}else {
start=mid+1;
}
}
if( start >= arr.length || arr[start]>val) {
return start;
}else {
return start+1;
}
}
private static void solve(int TC) throws Exception{
/*WRITE CODE HERE*/
int n=fs.nextInt();
long input[]=new long[n];
for(int i=0;i<n;i++) {
input[i]=fs.nextLong();
}
int even=0;
for(int i=0;i<n;i++) {
if( (input[i]&1) ==0 ) {
even++;
}
}
int odd=n-even;
if( Math.abs(odd-even) > 1 ) {
System.out.println(-1);
return ;
}
for(int i=0;i<n;i++) {
input[i]= ( (input[i]&1)==1 )?1 :0;
}
int ans=Integer.MAX_VALUE;
if( (n&1)==0 ) {
int output[]=new int[n];
for(int i=0;i<n;i++) {
output[i] = ( i&1 )==1 ? 1:0;
}
ArrayList<Integer> oddpos=new ArrayList<Integer>();
ArrayList<Integer> evenpos=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if( input[i] != output[i] ) {
if( (i&1)==1 ) oddpos.add(i);
else evenpos.add(i);
}
}
int smallAns=0;
for(int i=0;i<oddpos.size();i++) {
smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i));
}
ans=Math.min(ans, smallAns);
output=new int[n];
for(int i=0;i<n;i++) {
output[i] = ( i&1 )==0 ? 1:0;
}
oddpos=new ArrayList<Integer>();
evenpos=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if( input[i] != output[i] ) {
if( (i&1)==1 ) oddpos.add(i);
else evenpos.add(i);
}
}
smallAns=0;
for(int i=0;i<oddpos.size();i++) {
smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i));
}
ans=Math.min(ans, smallAns);
}else if( odd> even ) {
int output[]=new int[n];
for(int i=0;i<n;i++) {
output[i] = ( i&1 )==0 ? 1:0;
}
ArrayList<Integer> oddpos=new ArrayList<Integer>();
ArrayList<Integer> evenpos=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if( input[i] != output[i] ) {
if( (i&1)==1 ) oddpos.add(i);
else evenpos.add(i);
}
}
int smallAns=0;
for(int i=0;i<oddpos.size();i++) {
smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i));
}
ans=Math.min(ans, smallAns);
}else {
int output[]=new int[n];
for(int i=0;i<n;i++) {
output[i] = ( i&1 )==1 ? 1:0;
}
ArrayList<Integer> oddpos=new ArrayList<Integer>();
ArrayList<Integer> evenpos=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if( input[i] != output[i] ) {
if( (i&1)==1 ) oddpos.add(i);
else evenpos.add(i);
}
}
int smallAns=0;
for(int i=0;i<oddpos.size();i++) {
smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i));
}
ans=Math.min(ans, smallAns);
}
System.out.println(ans);
/*
int len=fs.nextInt();
String row1=fs.next();
String row2=fs.next();
int prev=-1;
int count=0;
for(int i=0;i<len; i++) {
if( row1.charAt(i) != row2.charAt(i) ) {
count+=2;
prev=-1;
}else if ( row1.charAt(i)=='1') {
if(prev==0) {
count++;
prev=-1;
}else {
prev=1;
}
}else {
if(prev==1) {
count+=2;
prev=-1;
}else {
count++;
prev=0;
}
}
}
System.out.println(count);
/*int a=fs.nextInt();
int b=fs.nextInt();
int c=fs.nextInt();
int m=fs.nextInt();
int max=a+b+c-3;
int arr[]= {a,b,c};
Arrays.parallelSort(arr);
int min=arr[2]-arr[1]-arr[0]-1;
if(m>=min && m<=max) {
System.out.println("YES");
}else {
System.out.println("No");
}
*/
/*
int n=fs.nextInt();
long hero[]=new long[n];
long sum=0;
for(int i=0;i<n;i++) {
hero[i]=Long.parseLong(fs.next());
sum+=hero[i];
}
//System.out.println(sum);
Arrays.sort(hero);
//for(long x: hero)
//System.out.print(x+" ");
//System.out.println();
int m=fs.nextInt();
while(m-->0) {
long df=Long.parseLong(fs.next());
long at=Long.parseLong(fs.next());
long nextGrt=(long)Math.pow(10, 18);
long nextSmall=-1;
int index=uperBound(hero, df);
//System.out.println(hero[index]);
//System.out.println(index);
if(index>=n) {
nextSmall=hero[n-1];
}else if(index<=0 ) {
nextGrt=hero[0];
}else {
nextGrt=hero[index];
nextSmall=hero[index-1];
}
/*for(int i=0;i<n;i++) {
if(hero[i]>=df && hero[i]<nextGrt ) {
nextGrt=hero[i];
}
if(hero[i]<=df && hero[i]>nextSmall ) {
nextSmall=hero[i];
}
}
//System.out.println(nextGrt +" : "+nextSmall);
if( nextGrt!= (long) Math.pow(10, 18) && sum-nextGrt >=at ) {
System.out.println(0);
}else {
if(nextGrt==(long)Math.pow(10, 18)) {
long ans= df- nextSmall;
ans+= ( at<= ( sum-nextSmall ) ) ? 0 : (at- sum+nextSmall);
System.out.println(ans);
}
else if(nextSmall==-1) {
long ans= ( at <= sum- nextGrt ) ? 0 : ( at- sum+nextGrt);
System.out.println(ans);
}else {
long ans1=df- nextSmall;
ans1+= ( at<= ( sum-nextSmall ) ) ? 0 : (at- sum+nextSmall);
long ans2= ( at <= sum- nextGrt ) ? 0 : ( at- sum+nextGrt);
System.out.println(Math.min(ans1, ans2));
}
}
}
/*int n=fs.nextInt();
for(int i=1;i<=n;i++) {
String open="";
String close="";
for(int j=1;j<=i;j++) {
open+="(";
close+=")";
}
int j=0;
while( j+2*i <= 2* n) {
System.out.print(open);
System.out.print(close);
j=j+2*i;
}
//System.out.println(j);
if(j<2*n) {
while(j<2*n) {
System.out.print("(");
System.out.print(")");
j+=2;
}
}
System.out.println();
}
*/
}
public static void main(String[] args) throws Exception {
int tcr=1;
//tcr = sc.nextInt();
tcr=fs.nextInt();
while(tcr-->0) {
solve(tcr);
}
System.gc();
}
static int computeXOR(int n)
{
// If n is a multiple of 4
if (n % 4 == 0)
return n;
// If n%4 gives remainder 1
if (n % 4 == 1)
return 1;
// If n%4 gives remainder 2
if (n % 4 == 2)
return n + 1;
// If n%4 gives remainder 3
return 0;
}
static boolean isSorted (int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
static void firstOperation (int[] nums) {
for (int i = 1; i < nums.length; i += 2) {
int temp = nums[i];
nums[i] = nums[i - 1];
nums[i - 1] = temp;
}
}
static void secondOperation (int[] nums) {
int n = nums.length / 2;
for (int i = 0; i < n; i++) {
int temp = nums[i];
nums[i] = nums[i + n];
nums[i + n] = temp;
}
}
private static long numOfDigits(long a) {
long ans=0;
while(a!=0) {
ans++;
a/=10;
}
return ans;
}
private static String reverse(String s) {
String ans="";
for(int i=s.length()-1;i>=0;i--) {
ans+=s.charAt(i);
}
return ans;
}
private static boolean isPalindrome(String s) {
int i=0;
int j=s.length()-1;
while(i<j) {
if(s.charAt(i)!=s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st ;
FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
FastScanner(String file) {
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
st = new StringTokenizer("");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("file not found");
e.printStackTrace();
}
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String readLine() throws IOException{
return br.readLine();
}
}
public static long[] sort(long arr[]){
List<Long> list = new ArrayList<>();
for(long n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
public static int[] sort(int arr[]){
List<Integer> list = new ArrayList<>();
for(int n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
// return the (index + 1)
// where index is the pos of just smaller element
// i.e count of elemets strictly less than num
public static int justSmaller(long arr[],long num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
//return (index of just greater element)
//count of elements smaller than or equal to num
public static int justGreater(long arr[],long num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0) {
return false;
}
}
return true;
}
public static void println(Object obj){
System.out.println(obj.toString());
}
public static void print(Object obj){
System.out.println(obj.toString());
}
public static long gcd(long a,long b){
if(b == 0l){
return a;
}
return gcd(b,a%b);
}
public static int find(int parent[],int v){
if(parent[v] == v){
return v;
}
return parent[v] = find(parent, parent[v]);
}
public static List<Integer> sieve(){
List<Integer> prime = new ArrayList<>();
int arr[] = new int[100001];
Arrays.fill(arr,1);
arr[1] = 0;
arr[2] = 1;
for(int i=2;i<=100000;i++){
if(arr[i] == 1){
prime.add(i);
for(long j = (i*1l*i);j<100001;j+=i){
arr[(int)j] = 0;
}
}
}
return prime;
}
static boolean isPower(long n,long a){
long log = (long)(Math.log(n)/Math.log(a));
long power = (long)Math.pow(a,log);
if(power == n){return true;}
return false;
}
private static int mergeAndCount(int[] arr, int l,int m, int r)
{
// Left subarray
int[] left = Arrays.copyOfRange(arr, l, m + 1);
// Right subarray
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
// Merge sort function
private static int mergeSortAndCount(int[] arr, int l,int r)
{
// Keeps track of the inversion count at a
// particular node of the recursion tree
int count = 0;
if (l < r) {
int m = (l + r) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, l, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, r);
// Merge count
count += mergeAndCount(arr, l, m, r);
}
return count;
}
static class Debug {
//change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) throws Exception {
if(LOCAL) {
PrintStream ps = new PrintStream("src/Debug.txt");
System.setErr(ps);
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 30b591345c160b02ffa024779690fdb4 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m;
int[] nums = new int[100010];
for(int i = 0; i < n; i ++) {
m = sc.nextInt();
int cnt = 0;
for(int j = 0; j < m; j ++) {
nums[j] = sc.nextInt();
nums[j] &= 1;
if(nums[j] == 1) cnt ++;
}
int flag = -1;
if(m % 2 == 1) {
if(cnt == m / 2) flag = 1;
if(cnt == m / 2 + 1) flag = 2;
} else {
if(cnt == m / 2) flag = 3;
}
if(flag == -1) System.out.println(-1);
else {
int c1 = 0, c2 = 0;
int index1 = 0, index2 = 1;
for(int j = 0; j < m; j ++) {
if(nums[j] == 1) {
c1 += Math.abs(j - index1);
c2 += Math.abs(j - index2);
index1 += 2;
index2 += 2;
}
}
int res = 0;
switch (flag) {
case 1: {res = c2; break;}
case 2: {res = c1; break;}
case 3: {res = Integer.min(c1, c2); break;}
default: break;
}
System.out.println(res);
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | d19cd14e742ce34a1b035e4bcb8e8d4d | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | /*==========================================================================
* AUTHOR: RonWonWon
* CREATED: 03.09.2021 10:40:01
/*==========================================================================*/
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException {
/*
in.ini();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
*/
long startTime = System.nanoTime();
int t = in.nextInt(), T = 1;
while(t-->0) {
int n = in.nextInt();
int a[] = in.readArray(n);
List<Integer> even = new ArrayList<>();
for(int i=0;i<n;i++){
if(a[i]%2==0) even.add(i);
}
if(n%2==0){
if(even.size()==n/2){
int c1 = 0;
int i = 0;
for(int k=0;k<n;k++){
if(k%2==0) c1 += Math.abs(even.get(i++) - k);
}
i = 0;
int c2 = 0;
for(int k=0;k<n;k++){
if(k%2==1) c2 += Math.abs(even.get(i++) - k);
}
out.println(Math.min(c1,c2));
}
else out.println(-1);
}
else{
if(even.size()==n/2+1){
int c1 = 0, i = 0;
for(int k=0;k<n;k++){
if(k%2==0) c1 += Math.abs(even.get(i++) - k);
}
out.println(c1);
}
else if(even.size()==n/2){
int c2 = 0, i = 0;
for(int k=0;k<n;k++){
if(k%2==1) c2 += Math.abs(even.get(i++) - k);
}
out.println(c2);
}
else out.println(-1);
}
//out.println("Case #"+T+": "+ans); T++;
}
/*
startTime = System.nanoTime() - startTime;
System.err.println("Time: "+(startTime/1000000));
*/
out.flush();
}
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static int oo = Integer.MAX_VALUE;
static long ooo = Long.MAX_VALUE;
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
void ini() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() {
while(!st.hasMoreTokens())
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readArrayL(int n) {
long a[] = new long[n];
for(int i=0;i<n;i++) a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readArrayD(int n) {
double a[] = new double[n];
for(int i=0;i<n;i++) a[i] = nextDouble();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSortL(long[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n);
long temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 0a2671eab469bdcdb4c2fb26529e90ca | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces {
static String ab,b;
static class Node
{
int val;
Node left;
Node right;
public Node(int x) {
// TODO Auto-generated constructor stub
this.val=x;
this.left=null;
this.right=null;
}
}
static class Pair<U, V> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) x).compareTo(o.x);
if (value != 0) return value;
return ((Comparable<V>) y).compareTo(o.y);
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return x.equals(pair.x) && y.equals(pair.y);
}
public int hashCode() {
return Objects.hash(x, y);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] nextArray(int n)
{
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=nextInt();
return arr;
}
}
static String string;
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
return gcd(b, a % b);
}
static long gcd(long a, long b)
{
// Everything divides 0
for(long i=2;i<=b;i++)
{
if(a%i==0&&b%i==0)
return i;
}
return 1;
}
static int fac(int n)
{
int c=1;
for(int i=2;i<n;i++)
if(n%i==0)
c=i;
return c;
}
static int lcm(int a,int b)
{
for(int i=Math.min(a, b);i<=a*b;i++)
if(i%a==0&&i%b==0)
return i;
return 0;
}
static int maxHeight(char[][] ch,int i,int j,String[] arr)
{
int h=1;
if(i==ch.length-1||j==0||j==ch[0].length-1)
return 1;
while(i+h<ch.length&&j-h>=0&&j+h<ch[0].length&&ch[i+h][j-h]=='*'&&ch[i+h][j+h]=='*')
{
String whole=arr[i+h];
//System.out.println(whole.substring(j-h,j+h+1));
if(whole.substring(j-h,j+h+1).replace("*","").length()>0)
return h;
h++;
}
return h;
}
static boolean all(BigInteger n)
{
BigInteger c=n;
HashSet<Character> hs=new HashSet<>();
while((c+"").compareTo("0")>0)
{
String d=""+c;
char ch=d.charAt(d.length()-1);
if(d.length()==1)
{
c=new BigInteger("0");
}
else
c=new BigInteger(d.substring(0,d.length()-1));
if(hs.contains(ch))
continue;
if(d.charAt(d.length()-1)=='0')
continue;
if(!(n.mod(new BigInteger(""+ch)).equals(new BigInteger("0"))))
return false;
hs.add(ch);
}
return true;
}
static int cal(long n,long k)
{
System.out.println(n+","+k);
if(n==k)
return 2;
if(n<k)
return 1;
if(k==1)
return 1+cal(n, k+1);
if(k>=32)
return 1+cal(n/k, k);
return 1+Math.min(cal(n/k, k),cal(n, k+1));
}
static Node buildTree(int i,int j,int[] arr)
{
if(i==j)
{
//System.out.print(arr[i]);
return new Node(arr[i]);
}
int max=i;
for(int k=i+1;k<=j;k++)
{
if(arr[max]<arr[k])
max=k;
}
Node root=new Node(arr[max]);
//System.out.print(arr[max]);
if(max>i)
root.left=buildTree(i, max-1, arr);
else {
root.left=null;
}
if(max<j)
root.right=buildTree(max+1, j, arr);
else {
root.right=null;
}
return root;
}
static int height(Node root,int val)
{
if(root==null)
return Integer.MAX_VALUE-32;
if(root.val==val)
return 0;
if((root.left==null&&root.right==null))
return Integer.MAX_VALUE-32;
return Math.min(height(root.left, val), height(root.right, val))+1;
}
static void shuffle(int a[], int n)
{
for (int i = 0; i < n; i++) {
// getting the random index
int t = (int)Math.random() * a.length;
// and swapping values a random index
// with the current index
int x = a[t];
a[t] = a[i];
a[i] = x;
}
}
static void sort(int[] arr )
{
shuffle(arr, arr.length);
Arrays.sort(arr);
}
static int helper(int i,boolean flag,int n,int c,int val,int[][][] dp)
{
if(i<=0||i>=n+1)
{
c++;
return 1;
}
int last=flag?1:0;
if(dp[i][val][last]!=0)
return dp[i][val][last];
int ans=0;
if(flag)
{
ans=helper(i+1, flag, n, c, val,dp);
if(val>1)
ans+=helper(i-1, !flag, n, c, val-1,dp);
}
else {
ans=helper(i-1, flag, n, c, val,dp);
if(val>1)
ans+=helper(i+1, !flag, n, c, val-1,dp);
}
return dp[i][val][last]=ans;
}
static boolean valid(char[] arr,int k)
{
int[] count=new int[26];
for(int i=0;i<arr.length;i++)
count[(int)arr[i]-'a']++;
for(int i=0;i<26;i++)
if(count[i]%k!=0)
return false;
return true;
}
static int compute(int c,int r)
{
if(r<c/2)
r=c-r;
int ans=1;
for(int i=c;i>r;i--)
ans*=i;
int fac=fac(c-r);
return ans/fac;
}
static boolean arraySortedInc(int arr[], int n)
{
// Array has one or no element
if (n == 0 || n == 1)
return true;
for (int i = 1; i < n; i++)
// Unsorted pair found
if (arr[i - 1] > arr[i])
return false;
// No unsorted pair found
return true;
}
static boolean arraySortedDec(int arr[], int n)
{
// Array has one or no element
if (n == 0 || n == 1)
return true;
for (int i = 1; i < n; i++)
// Unsorted pair found
if (arr[i - 1] > arr[i])
return false;
// No unsorted pair found
return true;
}
static int largestPower(int n, int p) {
// Initialize result
int x = 0;
// Calculate x = n/p + n/(p^2) + n/(p^3) + ....
while (n > 0) {
n /= p;
x += n;
}
return x;
}
// Utility function to do modular exponentiation.
// It returns (x^y) % p
static int power(int x, int y, int p) {
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0) {
// If y is odd, multiply x with result
if (y % 2 == 1) {
res = (res * x) % p;
}
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n! % p
static int modFact(int n, int p) {
if (n >= p) {
return 0;
}
int res = 1;
// Use Sieve of Eratosthenes to find all primes
// smaller than n
boolean isPrime[] = new boolean[n + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = 2 * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
// Consider all primes found by Sieve
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
// Find the largest power of prime 'i' that divides n
int k = largestPower(n, i);
// Multiply result with (i^k) % p
res = (res * power(i, k, p)) % p;
}
}
return res;
}
static boolean helper(int[][] all,int row,int[] count)
{
// System.out.println(new String(arr)+","+i+","+a+","+b);
if(row==all.length)
return true;
// System.out.println(all[row][row]);
// for(int i=0;i<all.length;i++)
// System.out.println(Arrays.toString(all[i]));
// System.out.println();
// System.out.println();
if(count[all[row][row]]==all[row][row])
return helper(all, row+1, count);
else {
for(int i=0;i<all.length;i++)
{
for(int j=0;j<=i;j++)
{
if(all[i][j]==all[row][row])
{
// System.out.println(row+","+i+","+j);
if(j>0&&all[i][j-1]==0)
{
all[i][j-1]=all[row][row];
count[all[row][row]]++;
if(helper(all, row, count))
return true;
else {
all[i][j-1]=0;
count[all[row][row]]--;
}
}
if(j<i&&all[i][j+1]==0)
{
all[i][j+1]=all[row][row];
count[all[row][row]]++;
if(helper(all, row, count))
return true;
else {
all[i][j+1]=0;
count[all[row][row]]--;
}
}
if(i<all.length-1&&all[i+1][j]==0)
{
all[i+1][j]=all[row][row];
count[all[row][row]]++;
if(helper(all, row, count))
return true;
else {
all[i+1][j]=0;
count[all[row][row]]--;
}
}
if(i>0&&j!=i&&all[i-1][j]==0)
{
all[i-1][j]=all[row][row];
count[all[row][row]]++;
if(helper(all, row, count))
return true;
else {
all[i-1][j]=0;
count[all[row][row]]--;
}
}
}
}
}
return false;
}
}
static List<Integer> helper(List<Integer> list)
{
int sum=0;
for(int i:list)
sum+=i;
sum/=list.size();
boolean in=false;
List<Integer> temp=new ArrayList<>(list);
for(Integer i:list)
{
if(i>sum)
{
in=true;
temp.remove(i);
}
}
if(temp.equals(list))
return temp;
return helper(temp);
}
static int helper(char[] arr,boolean reversed,int alice,int bob,int c)
{
int in=-1,count=0,st=-1;
for(int i=0;i<=arr.length/2;i++)
{
if(arr[i]=='0'&&arr[arr.length-1-i]=='1')
{
in=i;
break;
}
else if(arr[i]=='1'&&arr[arr.length-1-i]=='0')
{
in=arr.length-1-i;
break;
}
if(arr[i]=='0')
{
if(st==-1)
st=i;
count++;
}
if(arr[arr.length-i-1]=='0')
{
if(st==-1)
st=arr.length-1-i;
count++;
}
}
System.out.println(in);
if(count==0)
{
return alice-bob;
}
else if(arr.length%2!=0&&arr[arr.length/2]=='0')
{
arr[arr.length/2]='1';
return helper(arr, false, alice, bob, count);
}
if(in==-1||reversed)
{
arr[st]='1';
if(c%2==0)
return helper(arr, false, alice+1, bob, c+1);
else {
return helper(arr, false, alice, bob+1, c+1);
}
}
else {
arr[in]='1';
return helper(arr, true, alice, bob, c+1);
}
}
static boolean[] seiveOfErathnos(int n2)
{
boolean isPrime[] = new boolean[n2 + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n2; i++) {
if (isPrime[i]) {
for (int j = 2 * i; j <= n2; j += i) {
isPrime[j] = false;
}
}
}
return isPrime;
}
static boolean[] seiveOfErathnos2(int n2,int[] ans)
{
boolean isPrime[] = new boolean[n2 + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n2; i++) {
if (isPrime[i]) {
for (int j = 2 * i; j <= n2; j += i) {
if(isPrime[j])
ans[i]++;
isPrime[j] = false;
}
}
}
return isPrime;
}
static int calculatePower(PriorityQueue<Integer>[] list,int[] alive)
{
// List<Integer> dead=new ArrayList<>();
for(int i=1;i<alive.length;i++)
{
if(alive[i]==1)
{
if(list[i].size()==0)
{
continue;
}
if(list[i].peek()>i)
{
// dead.add(i);
// System.out.println(i);
alive[i]=0;
for(int j:list[i])
{
// list[i].remove((Integer)j);
list[j].remove((Integer)i);
}
list[i].clear();
return 1+calculatePower(list,alive);
}
}
}
return 0;
}
static boolean helper(int i,int j,int[] index,int k,HashMap<String,String> hm)
{
// System.out.println(i+","+j);
if(k<=0)
return false;
if(i==j)
return true;
String key=i+","+j;
if(hm.containsKey(key))
{
String[] all=hm.get(key).split(",");
int prev=Integer.parseInt(all[0]);
// String val=Integer.parseInt(all[1]);
if(prev==k)
return all[1].equals("true")?true:false;
else if(prev>k&&all[1].equals("false"))
return false;
else if(prev<k&&all[1].equals("true"))
return true;
}
if(i+1==j)
{
if(index[i]+1==index[j]||k>=2)
return true;
return false;
}
boolean flag=false;
for(int p=i;p<j;p++)
{
if(index[p]+1!=index[p+1])
{
flag=true;
break;
}
}
if(!flag)
{
hm.put(key,k+","+ true);
return true;
}
if(k==1)
{
hm.put(key,k+","+ false);
return false;
}
for(int p=i;p<j;p++)
{
if(helper(i,p,index,k-1,hm)&&helper(p+1,j,index,k-1,hm))
{
hm.put(key,k+","+ true);
return true;
}
}
hm.put(key, k+","+false);
return false;
}
static int set(int[] arr,int start)
{
int count=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
count+=Math.abs(start-i);
start+=2;
}
}
return count;
}
public static void main(String[] args)throws IOException
{
BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
FastReader fs=new FastReader();
// int[] ans=new int[1000001];
int T=fs.nextInt();
// seiveOfErathnos2(1000000, ans);
StringBuilder sb=new StringBuilder();
while(T-->0)
{
int n=fs.nextInt();
int[] arr=fs.nextArray(n);
// System.out.println();
int odd=0,even=0;
for(int i:arr)
{
if(i%2==0)
even++;
else
odd++;
}
int ans=-1;
if(n==1)
ans=0;
else if(odd==even)
{
// System.out.println(equal);
ans=Math.min(set(arr, 0),set(arr, 1));
}
else if(odd+1==even)
{
ans=set(arr,0);
}
else if(odd==even+1)
{
ans=set(arr,1);
}
sb.append(ans);
sb.append("\n");
}
System.out.println(sb);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 953654e441ac760636e8e434ea2f9cd5 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class Practice {
public static long mod = (long) Math.pow(10, 9) + 7;
// public static long mod2 = 998244353;
// public static int tt = 1;
public static ArrayList<Long> one;
public static ArrayList<Long> two;
// public static long[] fac = new long[200005];
// public static long[] invfac = new long[200005];
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int p = 1;
while (t-- > 0) {
String[] s2 = br.readLine().split(" ");
int n = Integer.valueOf(s2[0]);
long[] arr = new long[n];
String str = (br.readLine());
String[] s1 = str.split(" ");
int a = 0;
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s1[i]);
if (arr[i] % 2 == 0) {
a++;
}
}
if (Math.abs(n - a - a) <= 1) {
if (n - a - a == -1) {
long ans = 0;
int w1 = 0, w2 = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
while (arr[w1] % 2 != 0) {
w1++;
}
ans += (Math.abs(w1 - i));
w1++;
} else {
while (arr[w2] % 2 == 0) {
w2++;
}
ans += (Math.abs(w2 - i));
w2++;
}
}
pw.println(ans / 2);
} else if (n - a - a == 0) {
long ans = 0;
int w1 = 0, w2 = 0;
for (int i = 0; i < n; i++) {
if (i % 2 != 0) {
while (arr[w1] % 2 != 0) {
w1++;
}
ans += (Math.abs(w1 - i));
w1++;
} else {
while (arr[w2] % 2 == 0) {
w2++;
}
ans += (Math.abs(w2 - i));
w2++;
}
}
long b = ans;
ans = 0;
w1 = 0;
w2 = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
while (arr[w1] % 2 != 0) {
w1++;
}
ans += (Math.abs(w1 - i));
w1++;
} else {
while (arr[w2] % 2 == 0) {
w2++;
}
ans += (Math.abs(w2 - i));
w2++;
}
}
pw.println(Math.min(ans / 2, b / 2));
} else {
long ans = 0;
int w1 = 0, w2 = 0;
for (int i = 0; i < n; i++) {
if (i % 2 != 0) {
while (arr[w1] % 2 != 0) {
w1++;
}
ans += (Math.abs(w1 - i));
w1++;
} else {
while (arr[w2] % 2 == 0) {
w2++;
}
ans += (Math.abs(w2 - i));
w2++;
}
}
pw.println(ans / 2);
}
} else {
pw.println(-1);
}
}
pw.close();
}
//
// private static long power(long a, long p) {
// // TODO Auto-generated method stub
// long res = 1;
// while (p > 0) {
// if (p % 2 == 1) {
// res = (res * a) % mod;
// }
// p = p / 2;
// a = (a * a) % mod;
// }
// return res;
// }
// private static int kmp(String str) {
// // TODO Auto-generated method stub
// // System.out.println(str);
// int[] pi = new int[str.length()];
// pi[0] = 0;
// for (int i = 1; i < str.length(); i++) {
// int j = pi[i - 1];
// while (j > 0 && str.charAt(i) != str.charAt(j)) {
// j = pi[j - 1];
// }
// if (str.charAt(j) == str.charAt(i)) {
// j++;
// }
// pi[i] = j;
// System.out.print(pi[i]);
// }
// System.out.println();
// return pi[str.length() - 1];
// }
}
// private static void getFac(long n, PrintWriter pw) {
// // TODO Auto-generated method stub
// int a = 0;
// while (n % 2 == 0) {
// a++;
// n = n / 2;
// }
// if (n == 1) {
// a--;
// }
// for (int i = 3; i <= Math.sqrt(n); i += 2) {
// while (n % i == 0) {
// n = n / i;
// a++;
// }
// }
// if (n > 1) {
// a++;
// }
// if (a % 2 == 0) {
// pw.println("Bob");
// } else {
// pw.println("Alice");
// }
// //System.out.println(a);
// return;
// }
// private static long power(long a, long p) {
// // TODO Auto-generated method stub
// long res = 1;
// while (p > 0) {
// if (p % 2 == 1) {
// res = (res * a) % mod;
// }
// p = p / 2;
// a = (a * a) % mod;
// }
// return res;
// }
//
// private static void fac() {
// fac[0] = 1;
// // TODO Auto-generated method stub
// for (int i = 1; i < fac.length; i++) {
// if (i == 1) {
// fac[i] = 1;
// } else {
// fac[i] = i * fac[i - 1];
// }
// if (fac[i] > mod) {
// fac[i] = fac[i] % mod;
// }
// }
// }
//
// private static int getLower(Long long1, Long[] st) {
// // TODO Auto-generated method stub
// int left = 0, right = st.length - 1;
// int ans = -1;
// while (left <= right) {
// int mid = (left + right) / 2;
// if (st[mid] <= long1) {
// ans = mid;
// left = mid + 1;
// } else {
// right = mid - 1;
// }
// }
// return ans;
// }
//private static long getGCD(long l, long m) {
//
// long t1 = Math.min(l, m);
// long t2 = Math.max(l, m);
// if (t1 == 0) {
// return t2;
// }
// while (true) {
// long temp = t2 % t1;
// if (temp == 0) {
// return t1;
// }
// t2 = t1;
// t1 = temp;
// }
//} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 74d925d6f236fd11aa83f9bb0a6c7c63 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol {
final static int LINE_SIZE = 128;
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), false);
long move(int[] ar, int start) {
long res = 0;
for (int i = 0; i < ar.length; i++) {
if (ar[i] % 2 == 1) {
res += Math.abs(start - i);
start += 2;
}
}
return res;
}
void solve() throws Exception {
int n = in.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++) ar[i] = in.nextInt();
int odd = 0;
for (int i = 0; i < n; i++) {
if (ar[i] % 2 == 1) {
odd++;
}
}
int h = n / 2;
if ((n % 2 == 0 && odd != h) || (n % 2 == 1 && odd != h && odd != h + 1)) {
out.println(-1);
return;
}
if (n % 2 == 0) {
out.println(Math.min(move(ar, 0), move(ar, 1)));
} else {
out.println(move(ar, odd == h ? 1 : 0));
}
}
void runCases() throws Exception {
int tt = 1;
tt = in.nextInt();
while (tt-- > 0) {
solve();
}
in.close();
out.close();
}
public static void main(String[] args) throws Exception {
Sol solver = new Sol();
solver.runCases();
}
static class Pii implements Comparable<Pii> {
public int fi, se;
public Pii(int fi, int se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pii other) {
if (fi == other.fi) return se - other.se;
return fi - other.fi;
}
}
static class Pll implements Comparable<Pll> {
public long fi, se;
public Pll(long fi, long se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pll other) {
if (fi == other.fi) return se < other.se ? -1 : 1;
return fi < other.fi ? -1 : 1;
}
}
static class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
T fi;
U se;
public Pair(T fi, U se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pair<T, U> other) {
if (fi == other.fi) return se.compareTo(other.se);
return fi.compareTo(other.fi);
}
}
static class FastReader {
private final DataInputStream din = new DataInputStream(System.in);
private final byte[] buffer = new byte[65536];
private int bufferPointer = 0, bytesRead = 0;
public String readLine() throws Exception {
byte[] buf = new byte[LINE_SIZE];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) break;
else continue;
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws Exception {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg ? -ret : ret;
}
public long nextLong() throws Exception {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg ? -ret : ret;
}
public double nextDouble() throws Exception {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
return neg ? -ret : ret;
}
private void fillBuffer() throws Exception {
bytesRead = din.read(buffer, bufferPointer = 0, 65536);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws Exception {
din.close();
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 353d4e5d56adf93c8ec1515adeeb5343 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException
{
FastScanner f= new FastScanner();
int ttt=1;
ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
outer: for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
int[] l=new int[n];
int odd=0;
for(int i=0;i<n;i++) {
l[i]=f.nextInt()%2;
odd+=l[i]%2;
}
if(n%2==0) {
if(n/2!=odd) {
System.out.println(-1);
}
else {
int ans=Integer.MAX_VALUE;
int ind=0;
int temp=0;
for(int i=0;i<n;i++) {
if(l[i]==0) {
temp+=Math.abs(ind-i);
ind+=2;
}
}
ans=Math.min(ans, temp);
ind=1;
temp=0;
for(int i=0;i<n;i++) {
if(l[i]==0) {
temp+=Math.abs(ind-i);
ind+=2;
}
}
ans=Math.min(ans, temp);
System.out.println(ans);
}
}
else {
if(odd==n/2) {
int ans=Integer.MAX_VALUE;
int ind=1;
int temp=0;
for(int i=0;i<n;i++) {
if(l[i]==1) {
temp+=Math.abs(ind-i);
ind+=2;
}
}
ans=Math.min(ans, temp);
System.out.println(ans);
}
else if(odd==n/2+1) {
int ans=Integer.MAX_VALUE;
int ind=0;
int temp=0;
for(int i=0;i<n;i++) {
if(l[i]==1) {
temp+=Math.abs(ind-i);
ind+=2;
}
}
ans=Math.min(ans, temp);
System.out.println(ans);
}
else {
System.out.println(-1);
}
}
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a14b8977497a355403e82fd7d4353b37 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
public class cf2 {
static PrintWriter out;
static int MOD = 1000000007;
static FastReader scan;
/*-------- I/O using short named function ---------*/
public static String ns() {
return scan.next();
}
public static int ni() {
return scan.nextInt();
}
public static long nl() {
return scan.nextLong();
}
public static double nd() {
return scan.nextDouble();
}
public static String nln() {
return scan.nextLine();
}
public static void p(Object o) {
out.print(o);
}
public static void ps(Object o) {
out.print(o + " ");
}
public static void pn(Object o) {
out.println(o);
}
/*-------- for output of an array ---------------------*/
static void iPA(int arr[]) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < arr.length; i++) output.append(arr[i] + " ");
out.println(output);
}
static void lPA(long arr[]) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < arr.length; i++) output.append(arr[i] + " ");
out.println(output);
}
static void sPA(String arr[]) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < arr.length; i++) output.append(arr[i] + " ");
out.println(output);
}
static void dPA(double arr[]) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < arr.length; i++) output.append(arr[i] + " ");
out.println(output);
}
/*-------------- for input in an array ---------------------*/
static void iIA(int arr[]) {
for (int i = 0; i < arr.length; i++) arr[i] = ni();
}
static void lIA(long arr[]) {
for (int i = 0; i < arr.length; i++) arr[i] = nl();
}
static void sIA(String arr[]) {
for (int i = 0; i < arr.length; i++) arr[i] = ns();
}
static void dIA(double arr[]) {
for (int i = 0; i < arr.length; i++) arr[i] = nd();
}
/*------------ for taking input faster ----------------*/
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static ArrayList<Integer> sieveOfEratosthenes(int n) {
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
ArrayList<Integer> arr = new ArrayList<>();
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
arr.add(i);
}
return arr;
}
// Method to check if x is power of 2
static boolean isPowerOfTwo(int x) {
return x != 0 && ((x & (x - 1)) == 0);
}
//Method to return lcm of two numbers
static int gcd(int a, int b) {
return a == 0 ? b : gcd(b % a, a);
}
//Method to count digit of a number
static int countDigit(long n) {
String sex = Long.toString(n);
return sex.length();
}
static void reverse(int a[]) {
int i, k, t;
int n = a.length;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long nCr(long n, long r)
{
long p = 1, k = 1;
// C(n, r) == C(n, n-r),
// choosing the smaller value
if (n - r < r) {
r = n - r;
}
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
// gcd of p, k
long m = __gcd(p, k);
// dividing by gcd, to simplify
// product division by their gcd
// saves from the overflow
p /= m;
k /= m;
n--;
r--;
}
// k should be simplified to 1
// as C(n, r) is a natural number
// (denominator should be 1 ) .
}
else {
p = 1;
}
// if our approach is correct p = ans and k =1
return p;
}
static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
// Get all prime numbers till N using seive of Eratosthenes
public static List<Integer> getPrimesTill(int n){
boolean[] arr = new boolean[n+1];
List<Integer> primes = new LinkedList<>();
for(int i=2; i<=n; i++){
if(!arr[i]){
primes.add(i);
for(long j=(i*i); j<=n; j+=i){
arr[(int)j] = true;
}
}
}
return primes;
}
static final Random random = new Random();
//Method for sorting
static void ruffleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = random.nextInt(n);
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void sortadv(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long value : a) {
l.add(value);
}
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a[i] = l.get(i);
}
//Method for checking if a number is prime or not
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main(String[] args) throws java.lang.Exception {
OutputStream outputStream = System.out;
out = new PrintWriter(outputStream);
scan = new FastReader();
//for fast output sometimes
StringBuilder sb1 = new StringBuilder();
// prefix sum, *dp , odd-even segregate , *brute force(n=100)(jo bola wo kar) , 2 pointer , pattern , see contraints
// but first observe! maybe just watch i-o like ans-x-1,y for input x,y;
// divide wale ques me always check whether divisor 1? || probability mei mostly (1-p)...
int t = ni();
while (t-- != 0) {
int n=ni();
int a[]=new int[n];
iIA(a);
ArrayList<Integer> odd=new ArrayList<>();
ArrayList<Integer> even=new ArrayList<>();
ArrayList<Integer> ar1=new ArrayList<>();
ArrayList<Integer> ar2=new ArrayList<>();
int c=0;
for(int i:a){
if(i%2==0)
c++;
else c--;
}
if(c<-1||c>1)
{
pn(-1);
continue;
}
for(int i=0;i<n;i++){
if(a[i]%2==0)
a[i]=0;
else a[i]=1;
}
long count=0;long count2=0;
ArrayList<Integer> ans=new ArrayList<>();
ArrayList<Integer> ans2=new ArrayList<>();
if(c==-1){
int temp=1;
for(int i=0;i<n;i++){
ans.add(temp);
temp=1-temp;
}
for(int i=0;i<n;i++){
if(a[i]!=ans.get(i)){
if(i%2==0)
even.add(i);
else odd.add(i);
}
}
if(even.size()==0||odd.size()==0)
count=0;
else {
for(int i=0;i<even.size();i++)
count+=Math.abs(even.get(i)-odd.get(i));
}
pn(count);
}
else if(c==1){
int temp=0;
for(int i=0;i<n;i++){
ans.add(temp);
temp=1-temp;
}
for(int i=0;i<n;i++){
if(a[i]!=ans.get(i)){
if(i%2==0)
even.add(i);
else odd.add(i);
}
}
if(even.size()==0||odd.size()==0)
count=0;
else {
for(int i=0;i<even.size();i++)
count+=Math.abs(even.get(i)-odd.get(i));
}
pn(count);
}
else{
int temp=1;
for(int i=0;i<n;i++){
ans.add(temp);
temp=1-temp;
}
for(int i=0;i<n;i++){
if(a[i]!=ans.get(i)){
if(i%2==0)
even.add(i);
else odd.add(i);
}
}
if(even.size()==0||odd.size()==0)
count=0;
else {
for(int i=0;i<even.size();i++)
count+=Math.abs(even.get(i)-odd.get(i));
}
//pn(count);
temp=0;even.clear();odd.clear();
//int temp=1;
for(int i=0;i<n;i++){
ans2.add(temp);
temp=1-temp;
}
for(int i=0;i<n;i++){
if(a[i]!=ans2.get(i)){
if(i%2==0)
even.add(i);
else odd.add(i);
}
}
if(even.size()==0||odd.size()==0)
count2=0;
else {
for(int i=0;i<even.size();i++)
count2+=Math.abs(even.get(i)-odd.get(i));
}
pn(Math.min(count,count2));
}
}
out.flush();
out.close();
}
public static class Pair implements Comparable<Pair>{
int a, b;
public Pair(int x,int y){
a=x;b=y;
}
@Override
public int compareTo(Pair o) {
if(this.a!=o.a)
return this.a-o.a;
else
return o.b-this.b;
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 09f08699d4e35260cf9221710a4028f0 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.util.*;
//import com.sun.management.internal.GcInfoCompositeData;
import java.io.*;
public class Solution {
static FastScanner scr=new FastScanner();
// static Scanner scr=new Scanner(System.in);
static PrintStream out=new PrintStream(System.out);
static StringBuilder sb=new StringBuilder();
static class pair{
long x;int y;
pair(long x,int y){
this.x=x;this.y=y;
}
}
static class triplet{
long x;
long y;
long z;
triplet(long x,long y,long z){
this.x=x;
this.y=y;
this.z=z;
}
} static class DSU{
int []a=new int[26];
int []rank=new int[26];
void start() {
for(int i=0;i<26;i++) {
a[i]=i;
}
}
int find(int x) {
if(a[x]==x) {
return x;
}
return find(a[x]);
}
void union(int x,int y) {
int xx=find(x);
int yy=find(y);
a[xx]=yy;
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
} long gcd(long a,long b){
if(b==0) {
return a;
}
return gcd(b,a%b);
}
int[] sort(int a[]) {
int multiplier = 1, len = a.length, max = Integer.MIN_VALUE;
int b[] = new int[len];
int bucket[];
for (int i = 0; i < len; i++) if (max < a[i]) max = a[i];
while (max / multiplier > 0) {
bucket = new int[10];
for (int i = 0; i < len; i++) bucket[(a[i] / multiplier) % 10]++;
for (int i = 1; i < 10; i++) bucket[i] += (bucket[i - 1]);
for (int i = len - 1; i >= 0; i--) b[--bucket[(a[i] / multiplier) % 10]] = a[i];
for (int i = 0; i < len; i++) a[i] = b[i];
multiplier *= 10;
}
return a;
}
long modPow(long base,long exp) {
if(exp==0) {
return 1;
}
if(exp%2==0) {
long res=(modPow(base,exp/2));
return (res*res);
}
return (base*modPow(base,exp-1));
}
long []reverse(long[] count){
long b[]=new long[count.length];
int index=0;
for(int i=count.length-1;i>=0;i--) {
b[index++]=count[i];
}
return b;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long [] a=new long [n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static ArrayList<Integer>list[];
static int l[];
static int r[];
static void solve() {
int n=scr.nextInt();
int []a=scr.readArray(n);
for(int i=0;i<n;i++) {
a[i]=a[i]%2;
}
int ans=MAX;
for(int start=0;start<2;start++) {
ArrayList<Integer>x=new ArrayList<>();
ArrayList<Integer>y=new ArrayList<>();
for(int i=start;i<n;i+=2) {
x.add(i);
}
for(int i=0;i<n;i++) {
if(a[i]==0) {
y.add(i);
}
}
int cnt=0;
if(x.size()==y.size()) {
for(int i=0;i<x.size();i++) {
cnt+=Math.abs(x.get(i)-y.get(i));
}
ans=Math.min(ans, cnt);
}
}
ans=(ans==MAX)?-1:ans;
out.println(ans);
}
static int MAX = Integer.MAX_VALUE;
static int MIN = Integer.MIN_VALUE;
static int mod=(int)1e9+7;
public static void main(String []args) {
int t=scr.nextInt();
while(t-->0) {
solve();
}
out.println(sb);
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6d7d496e6545b12ed800393bd50cc37d | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class new1
{
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int i = 0; i < t; i++) {
int n = s.nextInt();
int[] arr = new int[n];
int[] arr2 = new int[n];
ArrayList<Integer> odd = new ArrayList<Integer>();
ArrayList<Integer> even = new ArrayList<Integer>();
for(int j = 0; j < n; j++) {
arr[j] = s.nextInt() % 2;
if(arr[j] == 0) even.add(j);
else odd.add(j);
arr2[j] = arr[j];
}
int count1 = 0;
int j = 0; int x = 0; int y = 0; int k = 0;
while(j < n) {
// System.out.println(k);
if(arr[k] == -1) {
k++;
continue;
}
int val = j % 2;
if(val == arr[k]) {
k++;
}
else {
if(val == 0) {
while(y < even.size() && (even.get(y) < j || even.get(y) >=j && arr[even.get(y)] == -1)) {
y++;
}
if(y == even.size()) {
count1 = Integer.MAX_VALUE;
break;
}
arr[even.get(y)] = -1;
count1 = count1 + (even.get(y) - j);
}
else {
while(x < odd.size() && (odd.get(x) < j || odd.get(x) >=j && arr[odd.get(x)] == -1)) {
x++;
}
if(x == odd.size()) {
count1 = Integer.MAX_VALUE;
break;
}
arr[odd.get(x)] = -1;
count1 = count1 + (odd.get(x) - j);
}
}
j++;
}
int count2 = 0;
j = 0; x = 0; y = 0; k = 0;
while(j < n) {
// System.out.println(k);
if(arr2[k] == -1) {
k++;
continue;
}
int val = (j + 1)% 2;
if(val == arr2[k]) {
k++;
}
else {
if(val == 0) {
while(y < even.size() && (even.get(y) < j || even.get(y) >=j && arr2[even.get(y)] == -1)) {
y++;
}
if(y == even.size()) {
count2 = Integer.MAX_VALUE;
break;
}
arr2[even.get(y)] = -1;
count2 = count2 + (even.get(y) - j);
}
else {
while(x < odd.size() && (odd.get(x) < j || odd.get(x) >=j && arr2[odd.get(x)] == -1)) {
x++;
}
if(x == odd.size()) {
count2 = Integer.MAX_VALUE;
break;
}
arr2[odd.get(x)] = -1;
count2 = count2 + (odd.get(x) - j);
}
}
j++;
}
int ans = Math.min(count1, count2);
if(ans == Integer.MAX_VALUE) ans = -1;
System.out.println(ans);
}
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | f575c8228d0bef7edd0d8164961823e3 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B__Take_Your_Places {
static Scanner in=new Scanner();
static PrintWriter out=new PrintWriter( new OutputStreamWriter(System.out) );
static int testCases,n;
static long a[];
static void merge(long a[],int left,int right,int mid){
int n1=mid-left+1,n2=right-mid;
long L[]=new long[n1];
long R[]=new long[n2];
for(int i=0;i<n1;i++){
L[i]=a[left+i];
}
for(int i=0;i<n2;i++){
R[i]=a[mid+1+i];
}
int i=0,j=0,k=left;
while(i<n1 && j<n2){
if(L[i]<=R[j]){
a[k]=L[i];
i++;
}else{
a[k]=R[j];
j++;
}
k++;
}
while(i<n1){
a[k]=L[i];
i++;
k++;
}
while(j<n2){
a[k]=R[j];
j++;
k++;
}
}
static void sort(long a[],int left,int right){
if(left>=right){
return;
}
int mid=(left+right)/2;
sort(a,left,mid);
sort(a,mid+1,right);
merge(a,left,right,mid);
}
static void solve(){
int even=0,odd=0,ans1=0,ans2=0,pos1=0,pos2=1,index=0;
for(long i: a){
if(i%2==1){
even++;
ans1+=(int) Math.abs( pos1-index );
ans2+=(int) Math.abs( pos2-index );
pos1+=2;
pos2+=2;
}else{
odd++;
}
index++;
}
if(even==odd){
out.println( Math.min(ans1,ans2) );
out.flush();
}else if(even==odd+1){
out.println(ans1);
out.flush();
}else if(even+1==odd){
out.println(ans2);
out.flush();
}else{
out.println(-1);
out.flush();
}
}
public static void main(String[] amit) throws IOException {
testCases=in.nextInt();
for(int t=0;t<testCases;t++){
n=in.nextInt();
a=new long[n];
for(int i=0;i<n;i++){
a[i]=in.nextLong();
}
solve();
}
in.close();
}
static class Scanner{
BufferedReader in;
StringTokenizer st;
public Scanner() {
in=new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException{
while(st==null || !st.hasMoreElements()){
st=new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException{
return Integer.parseInt(next());
}
long nextLong() throws IOException{
return Long.parseLong(next());
}
String nextLine() throws IOException{
return in.readLine();
}
char nextChar() throws IOException{
return next().charAt(0);
}
double nextDouble() throws IOException{
return Double.parseDouble(next());
}
float nextFloat() throws IOException{
return Float.parseFloat(next());
}
boolean nextBoolean() throws IOException{
return Boolean.parseBoolean(next());
}
void close() throws IOException{
in.close();
}
}
}
/*
5
3
6 6 1
1
9
6
1 1 1 2 2 2
2
8 6
6
6 2 3 4 5 1
*/
/*
1
9
1 1 1 2 2 2 3 3 3
*/ | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6c7b83ddafb87b769d5c1dee131dcf33 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class B {
static class RealScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
// public static final class Pair<T1, T2> {
// public T1 first;
// public T2 second;
//
// public Pair() {
// first = null;
// second = null;
// }
//
// public Pair(T1 firstValue, T2 secondValue) {
// first = firstValue;
// second = secondValue;
// }
//
// public Pair(Sum_of2050.RealScanner.Pair<T1, T2> pair) {
// first = pair.first;
// second = pair.second;
// }
//
// }
public static void main(String[] args) {
RealScanner sc = new RealScanner();
int t = sc.nextInt();
while (t-- > 0) {
int nIn = sc.nextInt();
List<Long> odd_val = new ArrayList<>();
List<Long> even_val = new ArrayList<>();
for (int i = 0; i < nIn; i++) {
int x = sc.nextInt();
if (x % 2 != 0) {
odd_val.add((long) i);
} else {
even_val.add((long) i);
}
}
long p = even_val.size(), q = odd_val.size();
if (Math.abs(p - q) > 1) {
System.out.println(-1);
} else {
long sum_val = 0, ans = Long.MAX_VALUE;
long j = 0, k = 0;
if (p > q) {
for (int i = 0; i < nIn; i++) { //1
if (i % 2 == 0) {
long addval = j++;
sum_val += Math.abs(i - even_val.get((int) addval));//2
} else {
long addval = k++;
sum_val += Math.abs(i - odd_val.get((int) addval));//3
}
}
ans = Math.min(ans, sum_val / 2);//4
} else if (p < q) {
long j_val = 0;
long k_val = 0;
sum_val = 0;
for (int i = 0; i < nIn; i++) {//5
if (i % 2 == 0) {
long addval = j_val++;
sum_val += Math.abs(i - odd_val.get((int) addval));//6
} else {
long addval = k_val++;
sum_val += Math.abs(i - even_val.get((int) addval));
}
}
ans = Math.min(ans, sum_val / 2);//7
} else {
//sum_by even odd
long j_val1 = 0;
long k_val1 = 0;
sum_val = 0;
for (int i = 0; i < nIn; i++) {//8
if (i % 2 == 0) {
long addval = j_val1++;
sum_val += Math.abs(i - even_val.get((int) addval));//9 to 10 extract
} else {
long addval = k_val1++;
sum_val += Math.abs(i - odd_val.get((int) addval));
}
}
ans = Math.min(sum_val / 2,ans);
//sum_by even odd
long j_val = 0;
long k_val = 0;
sum_val = 0;
for (int i = 0; i < nIn; i++) {//11 to 12 extract
if (i % 2 == 0) {
long addval = j_val++;
sum_val += Math.abs(i - odd_val.get((int) addval));
} else {
long addval = k_val++;
sum_val += Math.abs(i - even_val.get((int) addval));
}
}
ans = Math.min(ans, sum_val / 2);//min value
}
//res //debug
System.out.println(ans);
}
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6e5b00dcab8941aa1aeb900f3080e0f8 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader in = new FastReader();
int test=in.nextInt();
while(test-->0)
{
int n=in.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
}
Stack<Integer>nodd1=new Stack<>();
Stack<Integer>neven1=new Stack<>();
Stack<Integer>nodd2=new Stack<>();
Stack<Integer>neven2=new Stack<>();
int ne=0,no=0;
for(int i=n-1;i>=0;i--)
{
if(arr[i]%2==0) {
ne++;
neven1.push(i);
neven2.push(i);
}
else {
no++;
nodd1.push(i);
nodd2.push(i);
}
}
int anse=0,anso=0;
if(Math.abs(ne-no)>1)
System.out.println(-1);
else if(n%2==0)
{
for(int i=0;i<n;i++)
{
if(i%2==0)
{
if(i<neven1.peek())
anse+=neven1.peek()-i;
neven1.pop();
}
else
{
if(i<nodd1.peek())
anse+=nodd1.peek()-i;
nodd1.pop();
}
}
for(int i=0;i<n;i++)
{
if(i%2==0)
{
if(i<nodd2.peek())
anso+=nodd2.peek()-i;
nodd2.pop();
}
else
{
if(i<neven2.peek())
{
anso+=neven2.peek()-i;
}
neven2.pop();
}
}
// System.out.println(anse);
System.out.println(Math.min(anso,anse));
}
else
if(ne>no)
{
for(int i=0;i<n;i++)
{
if(i%2==0)
{
if(i<neven1.peek()) {
// System.out.println(i+" "+neven1.peek());
anse+=neven1.peek()-i;
}
//System.out.println(i+" "+neven1.peek());
neven1.pop();
}
else
{
if(i<nodd1.peek()) {//System.out.println(i+" "+nodd1.peek());
anse+=nodd1.peek()-i;
}
nodd1.pop();
}
}
System.out.println(anse);
}
else
{
for(int i=0;i<n;i++)
{
if(i%2==0)
{
if(i<nodd2.peek())
anso+=nodd2.peek()-i;
nodd2.pop();
}
else
{
if(i<neven2.peek())
{
anso+=neven2.peek()-i;
}
neven2.pop();
}
}
System.out.println(anso);
}
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 18fc1681d0ca94d34b7eb7ee5f900859 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
private static final FastScanner fs = new FastScanner();
private static final int MOD = 1000000007;
public static void main(String[] args) throws IOException {
int cases = fs.nextInt();
while (cases-- > 0)
solve();
}
static void solve() throws IOException {
int n = fs.nextInt();
int[]a = fs.nextInts(n);
int cntO = 0;
int cntE = 0;
for (int i :a) {
if (i%2==0) cntO++;
else cntE++;
}
if (Math.abs(cntE-cntO) > 1) {
System.out.println(-1);
return;
}
int res = Integer.MAX_VALUE;
if (cntE == cntO) {
{
int r = 0;
int target = 0;
for (int i = 0; i < n; i++) {
if (a[i]%2==0) {
r+= Math.abs(i-target);
target+=2;
}
}
res = Math.min(r,res);
}
{
int r = 0;
int target = 1;
for (int i = 0; i < n; i++) {
if (a[i]%2==0) {
r+= Math.abs(i-target);
target+=2;
}
}
res = Math.min(r,res);
}
} else {
if (cntE > cntO) {
int r =0;
int target = 0;
for (int i = 0; i < n; i++) {
if (a[i]%2==1) {
r+= Math.abs(i-target);
target+=2;
}
}
res = Math.min(r,res);
} else {
int r =0;
int target = 0;
for (int i = 0; i < n; i++) {
if (a[i]%2==0) {
r+= Math.abs(i-target);
target+=2;
}
}
res = Math.min(r,res);
}
}
System.out.println(res);
}
static class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public ArrayList<Integer> nextIntsArrayList(int N) {
ArrayList<Integer> res = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
res.add((int) nextLong());
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 409e661e3730acbc10d4adf6f6592316 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class Deltix2021B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while (t -- > 0) {
int n = sc.nextInt();
int[] a = new int[n];
int[] f = new int[2];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt() % 2;
f[a[i]]++;
}
if (Math.abs(f[0] - f[1]) > 1) {
System.out.println(-1);
} else if (f[0] == f[1]) {
// even
int[] b = new int[n];
for (int i = 0; i < n; i += 2) {
b[i] = 1;
}
int ans = solve(a, b);
b = new int[n];
for (int i = 1; i < n; i += 2) {
b[i] = 1;
}
ans = Math.min(ans, solve(a, b));
System.out.println(ans);
} else {
int first = f[0] > f[1] ? 0 : 1;
int[] b = new int[n];
for (int i = 1 - first; i < n; i += 2) {
b[i] = 1;
}
System.out.println(solve(a, b));
}
}
}
private static int solve(int[] a, int[] b) {
List<Integer> x = new ArrayList<>();
List<Integer> y = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i] == 0 && b[i] == 1) {
x.add(i);
}
if (a[i] == 1 && b[i] == 0) {
y.add(i);
}
}
int ans = 0;
for (int i = 0; i < x.size(); i++) {
ans += Math.abs(x.get(i) - y.get(i));
}
return ans;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 32ad4412a87a6931819d5695c8db4914 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // MyPackage;
import java.io.*;
import java.util.*;
public class MyClass {
final static long mod = 1_000_000_007;
final static int mini = Integer.MIN_VALUE;
final static int maxi = Integer.MAX_VALUE;
static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static long ncr(long n, long r) {
if (r > n - r) r = n - r;
long[] C = new long[(int) r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (long j = Math.min(i, r); j > 0; j--)
C[(int) j] = (C[(int) j] + C[(int) j - 1]) % mod;
}
return C[(int) r];
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static int digits(long n) {
int count = 0;
long temp = n;
while (temp > 0) {
temp /= 10;
count++;
}
return count;
}
static boolean isPalindrome(String s, int k) {
int i = 0, j = s.length() - 1;
while(i < k) {
if(s.charAt(i) != s.charAt(j)) return false;
i++;
j--;
}
return true;
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long value : a) {
l.add(value);
}
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a[i] = l.get(i);
}
static int ceil(int a, int b) {
return a % b == 0 ? a / b : a / b + 1;
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int value : a) {
l.add(value);
}
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a[i] = l.get(i);
}
static void reverse(int[] arr) {
int l = 0;
int h = arr.length - 1;
while (l < h) {
swap(arr, l, h);
l++;
h--;
}
}
static String reverse(String s) {
StringBuilder res = new StringBuilder(s);
return res.reverse().toString();
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String n() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nint() {
return Integer.parseInt(n());
}
long nlong() {
return Long.parseLong(n());
}
double ndouble() {
return Double.parseDouble(n());
}
int[] narr(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nint();
return a;
}
int[][] narr(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = nint();
return a;
}
String nline() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class Pair {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nint();
while(t-- > 0) {
int n = sc.nint();
int[] arr = sc.narr(n);
int e = 0, o = 0;
for(int i : arr) {
if(i % 2 == 0) e++;
else o++;
}
if(n % 2 == 0 && e != o) out.println(-1);
else if(n % 2 == 1 && Math.abs(e - o) != 1) out.println(-1);
else {
int[] even = new int[e];
int[] odd = new int[o];
int j = 0;
for(int i = 0; i < n; i++) {
if(arr[i] % 2 == 0) even[j++] = i;
}
j = 0;
for(int i = 0; i < n; i++) {
if(arr[i] % 2 == 1) odd[j++] = i;
}
int[] tempe = new int[e];
int[] tempo = new int[o];
j = 0;
if(n % 2 == 1) {
int count = 0;
if(e > o) {
for(int i = 0; i < e; i++) {
tempe[i] = j;
j += 2;
}
j = 1;
for(int i = 0; i < o; i++) {
tempo[i] = j;
j += 2;
}
for(int i = 0; i < e; i++) {
count += Math.abs(tempe[i] - even[i]);
}
}
else {
for(int i = 0; i < o; i++) {
tempo[i] = j;
j += 2;
}
j = 1;
for(int i = 0; i < e; i++) {
tempe[i] = j;
j += 2;
}
for(int i = 0; i < o; i++) {
count += Math.abs(tempo[i] - odd[i]);
}
}
out.println(count);
}
else {
for(int i = 0; i < e; i++) {
tempe[i] = j;
j += 2;
}
j = 1;
for(int i = 0; i < o; i++) {
tempo[i] = j;
j += 2;
}
int count = 0;
for(int i = 0; i < e; i++) {
count += Math.abs(tempe[i] - even[i]);
}
int count2 = 0;
j = 0;
for(int i = 0; i < o; i++) {
tempo[i] = j;
j += 2;
}
j = 1;
for(int i = 0; i < e; i++) {
tempe[i] = j;
j += 2;
}
for(int i = 0; i < o; i++) {
count2 += Math.abs(tempo[i] - odd[i]);
}
out.println(Math.min(count, count2));
}
}
}
out.flush();
out.close();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 72a89002bfb71046826d2b834aac9de8 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
private static FastScanner in = new FastScanner();
private static FastOutput out = new FastOutput();
public void run() throws Exception {
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
boolean[] isEven = new boolean[n];
for (int j = 0; j < n; j++) {
isEven[j] = in.nextInt() % 2 == 1;
}
int bestRes = 0;
int falseRes = res(false, isEven);
int trueRes = res(true, isEven);
if (falseRes < 0 && trueRes < 0) {
bestRes = -1;
} else if (falseRes < 0) {
bestRes = trueRes;
} else if (trueRes < 0) {
bestRes = falseRes;
} else {
bestRes = Math.min(falseRes, trueRes);
}
out.println(bestRes);
}
}
private int res(boolean currentShouldBe, boolean[] isEven) {
boolean[] removed = new boolean[isEven.length];
int operations = 0;
int[] closest = { 0, 0 };
int removedCount = 0;
for (int j = 0; j < isEven.length; j++) {
if (removed[j]) {
removedCount--;
continue;
}
if (currentShouldBe == isEven[j]) {
currentShouldBe = !currentShouldBe;
continue;
}
int closestI = closest[currentShouldBe? 1 : 0];
if (closestI <= j) {
closestI = j + 1;
}
for (; closestI < isEven.length; closestI++) {
if (isEven[closestI] == currentShouldBe) {
break;
}
}
closest[currentShouldBe? 1 : 0] = closestI + 1;
if (closestI >= isEven.length) {
//not found
return -1;
}
operations += (closestI - j - removedCount);
removed[closestI] = true;
removedCount++;
}
return operations;
}
public static void main(String[] args) throws Exception {
new Main().run();
out.flush();
out.close();
}
}
@SuppressWarnings("unused")
class FastScanner {
private final BufferedReader br;
private StringTokenizer st;
FastScanner() {
this(System.in);
}
FastScanner(File file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastScanner(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = nextInt();
}
return arr;
}
long[] nextLongArray(int size) {
long[] arr = new long[size];
for (int i = 0; i < size; i++) {
arr[i] = nextLong();
}
return arr;
}
String[] nextStringArray(int size) {
String[] arr = new String[size];
for (int i = 0; i < size; i++) {
arr[i] = next();
}
return arr;
}
}
class FastOutput {
private final BufferedWriter bf;
public FastOutput(OutputStream outputStream) {
bf = new BufferedWriter(new OutputStreamWriter(outputStream));
}
public FastOutput() {
this(System.out);
}
private void printOne(Object s) {
try {
bf.write(s.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void println(Object s) {
printOne(s);
printOne("\n");
}
public void print(Object... os) {
printd("", os);
}
public void printd(String delimiter, Object... os) {
for (Object o : os) {
printOne(o);
printOne(delimiter);
}
}
public void flush() {
try {
bf.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close() {
try {
bf.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 8 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 01df597bf22821e137106b7ba095ea70 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import com.sun.security.jgss.GSSUtil;
import java.io.*;
import java.net.Inet4Address;
import java.util.*;
public class Main {
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private FastWriter wr;
private Reader rd;
public final int MOD = 1000000007;
/************************************************** FAST INPUT IMPLEMENTATION *********************************************/
class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
public Reader(String path) throws FileNotFoundException {
br = new BufferedReader(
new InputStreamReader(new FileInputStream(path)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public int ni() throws IOException {
return rd.nextInt();
}
public long nl() throws IOException {
return rd.nextLong();
}
public void yOrn(boolean flag) {
if (flag) {
wr.println("YES");
} else {
wr.println("NO");
}
}
char nc() throws IOException {
return rd.next().charAt(0);
}
public String ns() throws IOException {
return rd.nextLine();
}
public Double nd() throws IOException {
return rd.nextDouble();
}
public int[] nai(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
public long[] nal(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
/************************************************** FAST OUTPUT IMPLEMENTATION *********************************************/
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
/********************************************************* USEFUL CODE **************************************************/
boolean[] SAPrimeGenerator(int n) {
// TC-N*LOG(LOG N)
//Create Prime Marking Array and fill it with true value
boolean[] primeMarker = new boolean[n + 1];
Arrays.fill(primeMarker, true);
primeMarker[0] = false;
primeMarker[1] = false;
for (int i = 2; i <= n; i++) {
if (primeMarker[i]) {
// we start from 2*i because i*1 must be prime
for (int j = 2 * i; j <= n; j += i) {
primeMarker[j] = false;
}
}
}
return primeMarker;
}
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
class Pair<F, S> {
private F first;
private S second;
Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<F, S> pair = (Pair<F, S>) o;
return first == pair.first && second == pair.second;
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
}
class PairThree<F, S, X> {
private F first;
private S second;
private X third;
PairThree(F first, S second, X third) {
this.first = first;
this.second = second;
this.third = third;
}
public F getFirst() {
return first;
}
public void setFirst(F first) {
this.first = first;
}
public S getSecond() {
return second;
}
public void setSecond(S second) {
this.second = second;
}
public X getThird() {
return third;
}
public void setThird(X third) {
this.third = third;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PairThree<?, ?, ?> pair = (PairThree<?, ?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second) && third.equals(pair.third);
}
@Override
public int hashCode() {
return Objects.hash(first, second, third);
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
public void run() throws IOException {
if (oj) {
rd = new Reader();
wr = new FastWriter(System.out);
} else {
File input = new File("input.txt");
File output = new File("output.txt");
if (input.exists() && output.exists()) {
rd = new Reader(input.getPath());
wr = new FastWriter(output.getPath());
} else {
rd = new Reader();
wr = new FastWriter(System.out);
oj = true;
}
}
long s = System.currentTimeMillis();
solve();
wr.flush();
tr(System.currentTimeMillis() - s + "ms");
}
/***************************************************************************************************************************
*********************************************************** MAIN CODE ******************************************************
****************************************************************************************************************************/
boolean[] sieve;
public void solve() throws IOException {
int t = 1;
t = ni();
while (t-- > 0) {
go();
}
}
/********************************************************* MAIN LOGIC HERE ****************************************************/
long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lower_bound(int array[], int key) {
int low = 0, high = array.length;
int mid;
while (low < high) {
mid = low + (high - low) / 2;
if (key <= array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
if (low < array.length && array[low] < key) {
low++;
}
return low;
}
boolean isPowerOfTwo(int n) {
int counter = 0;
while (n != 0) {
if ((n & 1) == 1) {
counter++;
}
n = n >> 1;
}
return counter <= 1;
}
void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
void printList(ArrayList<Integer> al){
for(int i=0;i<al.size();i++){
wr.print(al.get(i)+" ");
}
wr.println("");
}
void rotateLeft(int[] arr,int end,int no){
for(int i = 0; i <no; i++){
int j, first_element;
first_element = arr[0];
for(j = 0; j < end; j++){
arr[j] = arr[j+1];
}
arr[j] = first_element;
}
}
int revNo(int n){
int ld=n%10;
int fd=n/10;
if(ld==2){
ld=5;
}else if(ld==5){
ld=2;
}
if(fd==2){
fd=5;
}else if(fd==5){
fd=2;
}
return (ld*10)+fd;
}
public static boolean check(long[] a,long inc, long k) {
a[0] += inc;
boolean v = valid(a, k);
a[0] -= inc;
return v;
}
public static boolean valid(long[] a, long k) {
int n = a.length;
long sum = a[0];
for(int i = 1; i<n; i++) {
if(k*sum<a[i]*100) return false;
sum+=a[i];
}
return true;
}
int getDis(int[] arr,boolean isEven){
int dis=0;
int d=0;
boolean check=isEven;
for(int i=0;i<arr.length;i++){
if(check){
if(arr[i]==1){
d++;
}
}else {
if(arr[i]==0){
d--;
}
}
dis+=Math.abs(d);
check=!check;
}
return dis;
}
public void go() throws IOException {
int n=ni();
int[] arr=new int[n];
int evenCnt=0,oddCnt=0;
for(int i=0;i<n;i++){
arr[i]=ni()%2;
if(arr[i]==1){
oddCnt++;
}else {
evenCnt++;
}
}
if(Math.abs(evenCnt-oddCnt)>1){
wr.println(-1);
return;
}
int ans=0;
if(n%2==0){
ans=Math.min(getDis(arr,true),getDis(arr,false));
}else {
if(evenCnt>oddCnt){
ans=getDis(arr,true);
}else {
ans=getDis(arr,false);
}
}
wr.println( ans);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 9caa02c3f43cc3703bd846d3f0d7a91c | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | /*
ID: abdelra29
LANG: JAVA
PROG: zerosum
*/
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.util.stream.Collectors;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static boolean isprime(int x)
{
if(x%2==0)
return false;
if(x==1)
return false;
if(x==2||x==3)
return true;
for(int i=3;i*i<=x;i+=2)
if(x%i==0)
return false;
return true;
}
static int hidden[]={0,181,21,53};
static Pair askand(int x)
{
System.out.println("and "+x+" "+(x-1));
//int fi=scan.nextInt();
int fi=hidden[x]&hidden[x-1];
System.out.println("and "+x+" "+(x-2));
int sec=hidden[x]&hidden[x-2];
//int sec=scan.nextInt();
return new Pair(fi,sec);
}
static Pair askor(int x)
{
System.out.println("or "+x+" "+(x-1));
//int fi=scan.nextInt();
int fi=hidden[x]|hidden[x-1];
System.out.println("or "+x+" "+(x-2));
int sec=hidden[x]|hidden[x-2];
//int sec=scan.nextInt();
return new Pair(fi,sec);
}
static int binaryToDecimal(String n)
{
String num = n;
int dec_value = 0;
// Initializing base value to 1,
// i.e 2^0
int base = 1;
int len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num.charAt(i) == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
public static void main(String[] args) throws Exception
{
/*
very important tips
1-just fucking think backwards once in your shitty life
2-consider brute forcing and finding some patterns and observations
3-when you're in contest don't get out because you think there is no enough time
4-don't get stuck on one approach
*/
// File file=new File("D:\\input\\out.txt");
// scan=new FastScanner("D:\\input\\xs_and_os_input.txt");
// out = new PrintWriter(new File("D:\\input\\out.txt"));
/*
READING
3-Introduction to DP with Bitmasking codefoces
4-Bit Manipulation hackerearth
5-read more about mobious and inculsion-exclusion
*/
/*
1-
*/
/*for(int i=3;i<=30;i++)
{
int sh=(i%3==0)?i/3:i/3+1;
System.out.println(i*2+" "+(sh*4));
}*/
int tt =1;
tt=scan.nextInt();
int T=1;
outer:while(tt-->0)
{
int n=scan.nextInt();
ArrayList<Integer>arr[]=new ArrayList[2];
arr[0]=new ArrayList();
arr[1]=new ArrayList();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
int x=scan.nextInt();
a[i]=x;
arr[x%2].add(i);
}
//if(tt==6000-17)
// out.println(a[4]);
if(n%2==0&&Math.abs(arr[0].size()-arr[1].size())>0)
{
out.println(-1);
continue outer;
}
if(n%2==1&&Math.abs(arr[0].size()-arr[1].size())>1)
{
out.println(-1);
continue outer;
}
//start with one
int cnt=0,idx=0,res1=0,res2=0;
for(int i=0;i<n&&idx<arr[1].size();i+=2)
{
if(i>=arr[1].get(idx))
{
res1+=i-arr[1].get(idx);
idx++;
continue;
}
res1+=((arr[1].get(idx++)-i));
cnt++;
}
idx=0;
cnt=0;
for(int i=0;i<n&&idx<arr[0].size();i+=2)
{
if(i>=arr[0].get(idx))
{
res2+=i-arr[0].get(idx);
idx++;
continue;
}
//out.println((arr[0].get(idx)-i));
res2+=((arr[0].get(idx++)-i));
cnt++;
}
//out.println(res1+" "+res2);
if(n%2==1)
{
if(arr[0].size()>arr[1].size())
out.println(res2);
else out.println(res1);
continue outer;
}
out.println(Math.min(res1,res2));
}
out.close();
}
static class special implements Comparable<special>{
int cnt,idx;
String s;
public special(int cnt,int idx,String s)
{
this.cnt=cnt;
this.idx=idx;
this.s=s;
}
@Override
public int hashCode() {
return (int)42;
}
@Override
public boolean equals(Object o){
// System.out.println("FUCK");
if (o == this) return true;
if (o.getClass() != getClass()) return false;
special t = (special)o;
return t.cnt == cnt && t.idx == idx;
}
public int compareTo(special o1)
{
if(o1.cnt==cnt)
{
return o1.idx-idx;
}
return o1.cnt-cnt;
}
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(x-o.x);
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a9f679fd1b01bddebf63348b6cc131cd | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static int bSearchDiff(long[] a, int low, int high) {
int mid = low + ((high - low) / 2);
int hight = high;
int lowt = low;
while (lowt < hight) {
mid = lowt + (hight - lowt) / 2;
if (a[high] - a[mid] <= 5) {
hight = mid;
} else {
lowt = mid + 1;
}
}
return lowt;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
// if (a[(int) mid] == ddp) {
// return mid;
// }
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long lowerbound(long a[], long ddp, long factor) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if ((a[(int) mid] + (mid * factor)) == ddp) {
return mid;
}
if ((a[(int) mid] + (mid * factor)) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp - (low * factor) && low != 0) {
low--;
}
return low;
}
public static long lowerbound(List<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a.get((int) mid) == ddp) {
return mid;
}
if (a.get((int) mid) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.size() && low != 0) {
low--;
return low;
}
if (a.get((int) low) > ddp && low != 0) {
low--;
}
return low;
}
public static long lowerboundforpairs(pair a[], double pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.length) {
return a.length - 1;
}
return low;
}
public static long upperbound(ArrayList<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a.get((int) mid) <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
// public static class pair implements Comparable<pair> {
// long w;
// long h;
// public pair(long w, long h) {
// this.w = w;
// this.h = h;
// }
// public int compareTo(pair b) {
// if (this.w != b.w)
// return (int) (this.w - b.w);
// else
// return (int) (this.h - b.h);
// }
// }
public static class pairs {
char w;
int h;
public pairs(char w, int h) {
this.w = w;
this.h = h;
}
}
public static class pair {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
@Override
public int hashCode() {
return Objects.hash(w, h);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof pair)) {
return false;
}
pair c = (pair) o;
return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0;
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
if (p1.w != p2.w) {
return (int) (p1.w - p2.w);
}
return (int) (p1.h - p2.h);
}
});
return a;
}
public static trinary[] sortpair(trinary[] a) {
Arrays.sort(a, new Comparator<trinary>() {
public int compare(trinary p1, trinary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.c != p2.c) {
return (int) (p1.c - p2.c);
}
return (int) (p1.a - p2.a);
}
});
return a;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(pair[] arr) {
ArrayList<pair> a = new ArrayList<>();
for (pair i : arr) {
a.add(i);
}
Collections.sort(a, new Comparator<pair>() {
@Override
public int compare(pair a, pair b) {
return (int) (a.h - b.h);
}
});
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static long power(long base, long pow, long mod) {
long result = base;
long temp = 1;
while (pow > 1) {
if (pow % 2 == 0) {
result = ((result % mod) * (result % mod)) % mod;
pow /= 2;
} else {
temp = temp * base;
pow--;
}
}
result = ((result % mod) * (temp % mod));
// System.out.println(result);
return result;
}
public static long sqrt(long n) {
long res = 1;
long l = 1, r = (long) 10e9;
while (l <= r) {
long mid = (l + r) / 2;
if (mid * mid <= n) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
return res;
}
public static boolean is[] = new boolean[10001];
public static int a[] = new int[10001];
public static Vector<Integer> seiveOfEratosthenes() {
Vector<Integer> listA = new Vector<>();
for (int i = 2; i * i <= a.length; i++) {
if (a[i] != 1) {
for (long j = i * i; j < a.length; j += i) {
a[(int) j] = 1;
}
}
}
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
is[i] = true;
listA.add(i);
}
}
return listA;
}
public static Vector<Integer> ans = seiveOfEratosthenes();
public static long sumOfDigits(long n) {
long ans = 0;
while (n != 0) {
ans += n % 10;
n /= 10;
}
return ans;
}
public static long gcdTotal(long a[]) {
long t = a[0];
for (int i = 1; i < a.length; i++) {
t = gcd(t, a[i]);
}
return t;
}
public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception {
int n = sc.nextInt();
long a[] = new long[n];
ArrayList<Integer> o = new ArrayList<>();
ArrayList<Integer> e = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
if (a[i] % 2 == 0) {
e.add(i);
} else {
o.add(i);
}
}
if (n == 1) {
sb.append(0 + "\n");
return;
}
int ans = 0;
if (Math.abs(e.size() - o.size()) == 1 || e.size() - o.size() == 0) {
if (n % 2 != 0) {
int ans1 = 0;
int ans2 = 0;
if (e.size() > o.size()) {
int s = 0;
for (int i = 0; i < e.size(); i++) {
// System.out.println(s + " " + Math.abs(s - e.get(i)) + " " + e.get(i));
ans1 += Math.abs(s - e.get(i));
s += 2;
}
s = 1;
for (int i = 0; i < o.size(); i++) {
ans2 += Math.abs(s - o.get(i));
s += 2;
}
} else {
int s = 0;
for (int i = 0; i < o.size(); i++) {
// System.out.println(s + " " + Math.abs(s - e.get(i)) + " " + e.get(i));
ans1 += Math.abs(s - o.get(i));
s += 2;
}
s = 1;
for (int i = 0; i < e.size(); i++) {
ans2 += Math.abs(s - e.get(i));
s += 2;
}
}
ans = Math.min(ans1, ans2);
} else {
int s = 1;
int ans1 = 0;
int ans2 = 0;
for (int i = 0; i < e.size(); i++) {
// System.out.println(s + " " + Math.abs(s - e.get(i)) + " " + e.get(i));
ans1 += Math.abs(s - e.get(i));
ans2 += Math.abs(s - o.get(i));
s += 2;
}
ans = Math.min(ans1, ans2);
}
sb.append(ans + "\n");
} else {
sb.append(-1 + "\n");
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
long o = sc.nextLong();
while (o > 0) {
solve(sc, w, sb);
o--;
}
System.out.print(sb.toString());
w.close();
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 93bb43cb5e17c70ca4a64de0d29847cc | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | // package codeForces.deltix;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class TestB {
private static final long INF = (long) 1e14;
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
var sb = new StringBuilder();
while(t-- > 0){
int n = Integer.parseInt(br.readLine().trim());
int arr[] = nextIntArray(n, br);
sb.append(getOps(arr)).append("\n");
}
br.close();
System.out.println(sb);
}
private static long getOps(int arr[]){
if(arr.length <= 1) return 0;
PriorityQueue<Integer> evenNums = new PriorityQueue<>();
PriorityQueue<Integer> oddNums = new PriorityQueue<>();
for(int i = 0; i < arr.length; i++){
if(arr[i]%2 == 0) evenNums.add(i);
else oddNums.add(i);
}
if(Math.abs(evenNums.size() - oddNums.size()) > 1) return -1;
long ret = INF;
for(int i = 0; i < 2; i++){
long cur = 0; int temp = 0;
int tempArr[] = Arrays.copyOf(arr, arr.length);
PriorityQueue<Integer> dummyEven = new PriorityQueue<>(evenNums);
PriorityQueue<Integer> dummyOdd = new PriorityQueue<>(oddNums);
if(i%2 == 0 && arr[0]%2 != 0){
temp = dummyEven.remove();
dummyOdd.add(temp);
}else if(i%2 != 0 && arr[0]%2 != 1){
temp = dummyOdd.remove();
dummyEven.add(temp);
}
cur += temp;
swap(tempArr, 0, temp);
cur = getOpsValue(dummyEven, dummyOdd, tempArr, temp, cur);
ret = Math.min(ret, cur);
}
return ret;
}
private static long getOpsValue(PriorityQueue<Integer> dummyEven, PriorityQueue<Integer> dummyOdd, int tempArr[], int temp, long cur ){
for(int j = 1; j < tempArr.length; j++){
while(!dummyEven.isEmpty() && dummyEven.peek() <= j) dummyEven.remove();
while(!dummyOdd.isEmpty() && dummyOdd.peek() <= j) dummyOdd.remove();
if(tempArr[j-1]%2 == tempArr[j]%2){
if(tempArr[j]%2 == 0){
if(dummyOdd.isEmpty()) return INF;
temp = dummyOdd.remove();
dummyEven.add(temp);
}else{
if(dummyEven.isEmpty()) return INF;
temp = dummyEven.remove();
dummyOdd.add(temp);
}
cur += Math.abs(j-temp);
swap(tempArr, j, temp);
}
}
return cur;
}
private static void swap(int arr[], int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static int[] nextIntArray(int N, BufferedReader br) throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine().trim()," ");
int arr[] = new int[N];
for(int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 20d64567f5af80ab420033c257fee79a | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static long mod = (int)1e9+7;
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc =new FastReader();
int t=sc.nextInt();
// int t=1;
while(t-->0)
{
int n=sc.nextInt();
int arr[] = sc.readArray(n);
int e = 0, o = 0;
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
e++;
}
else
{
o++;
}
}
if(n==1)
{
System.out.println(0);
continue;
}
if(Math.abs(e - o)>1)
{
System.out.println(-1);
continue;
}
for(int i=0;i<n;i++)
{
arr[i] = arr[i]%2;
}
int ans1 = 0 , ans2 = 0;
boolean f1 = true , f2 = true;
{
ArrayList<Integer> eve = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(i%2==0 && arr[i]==1)
{
eve.add(i);
}
else if(i%2==1 && arr[i]==0)
{
odd.add(i);
}
}
if(eve.size()==odd.size())
{
while(eve.size()!=0)
{
ans1+=Math.abs(eve.get(0) - odd.get(0));
eve.remove(0);
odd.remove(0);
}
}
else
{
f1 = false;
}
}
{
ArrayList<Integer> eve = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(i%2==0 && arr[i]==0)
{
eve.add(i);
}
else if(i%2==1 && arr[i]==1)
{
odd.add(i);
}
}
if(eve.size()==odd.size())
{
while(eve.size()!=0)
{
ans2+=Math.abs(eve.get(0) - odd.get(0));
eve.remove(0);
odd.remove(0);
}
}
else
{
f2 = false;
}
}
if(f1==false && f2==true)
{
System.out.println(ans2);
}
else if(f1==true && f2==false)
{
System.out.println(ans1);
}
else if(f1==true && f2==true)
{
System.out.println(Math.min(ans1 , ans2));
}
else
{
System.out.println(-1);
}
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
float nextFloat()
{
return Float.parseFloat(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
public static int[] radixSort2(int[] a)
{
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for(int v : a) {
c0[(v&0xff)+1]++;
c1[(v>>>8&0xff)+1]++;
c2[(v>>>16&0xff)+1]++;
c3[(v>>>24^0x80)+1]++;
}
for(int i = 0;i < 0xff;i++) {
c0[i+1] += c0[i];
c1[i+1] += c1[i];
c2[i+1] += c2[i];
c3[i+1] += c3[i];
}
int[] t = new int[n];
for(int v : a)t[c0[v&0xff]++] = v;
for(int v : t)a[c1[v>>>8&0xff]++] = v;
for(int v : a)t[c2[v>>>16&0xff]++] = v;
for(int v : t)a[c3[v>>>24^0x80]++] = v;
return a;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
static void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static boolean palindrome_array(char arr[], int n)
{
// Initialise flag to zero.
int flag = 0;
// Loop till array size n/2.
for (int i = 0; i <= n / 2 && n != 0; i++) {
// Check if first and last element are different
// Then set flag to 1.
if (arr[i] != arr[n - i - 1]) {
flag = 1;
break;
}
}
// If flag is set then print Not Palindrome
// else print Palindrome.
if (flag == 1)
return false;
else
return true;
}
static boolean allElementsEqual(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
static boolean allElementsDistinct(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]!=arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
public static void reverse(int[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
public static void reverse_Long(long[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
long temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static boolean isReverseSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] < a[i + 1]) {
return false;
}
}
return true;
}
static int[] rearrangeEvenAndOdd(int arr[], int n)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
int[] array = list.stream().mapToInt(i->i).toArray();
return array;
}
static long[] rearrangeEvenAndOddLong(long arr[], int n)
{
ArrayList<Long> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
long[] array = list.stream().mapToLong(i->i).toArray();
return array;
}
static boolean isPrime(long n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (long i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcdLong(long a, long b)
{
if (b == 0)
return a;
return gcdLong(b, a % b);
}
static void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 667b73265b8d243de3019dd98c7559ce | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class cf {
static Reader sc = new Reader();
static PrintWriter out = new PrintWriter(System.out);
static long mod = (long) 1e9 + 7;
public static void main(String[] args) {
int tc = sc.ni();
while (tc-- > 0) {
int n=sc.ni();
int[] a=sc.nai(n);
int ce=0,co=0;
for(int i=0;i<n;i++){
a[i]=a[i]%2;
if(a[i]==0) ce++;
else co++;
}
if(n%2==0){
if(Math.abs(ce-co)!=0){
out.println(-1);
continue;
}
}else{
if (Math.abs(ce - co) != 1) {
out.println(-1);
continue;
}
}
long res1=0,res2=0;
int v1=0,idx1=0;
int i1=0,j1=0;
while(idx1<n){
while(i1<n && a[i1]==1) i1++;
while (j1 < n && a[j1] == 0) j1++;
if(v1==0){
res1+=Math.abs(idx1-i1);
i1++;
}
else{
res1+=Math.abs(idx1-j1);
j1++;
}
v1=1-v1;
idx1++;
}
int v2 = 1, idx2 = 0;
int i2 = 0, j2 = 0;
while (idx2 < n) {
while (i2 < n && a[i2] == 1)
i2++;
while (j2 < n && a[j2] == 0)
j2++;
if (v2 == 0) {
res2 += Math.abs(idx2 - i2);
i2++;
} else {
res2 += Math.abs(idx2 - j2);
j2++;
}
v2 = 1 - v2;
idx2++;
}
if(n%2==0){
out.println(min(res1/2,res2/2));
}else{
out.println((ce>co)?res1/2:res2/2);
}
}
out.close();
}
public static long pow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 0) {
return pow((a * a) % m, b / 2, m) % m;
} else {
return (a * pow((a * a) % m, b / 2, m)) % m;
}
}
// snippets
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (this.x > o.x)
return 1;
else if (this.x < o.x)
return -1;
else {
if (this.y > o.y)
return 1;
else if (this.y < o.y)
return -1;
else
return 0;
}
}
public int hashCode() {
int ans = 1;
ans = x * 31 + y * 13;
return ans;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Pair other = (Pair) o;
if (this.x == other.x && this.y == other.y) {
return true;
}
return false;
}
}
static void add_map(HashMap<Integer, Integer> map, int v) {
if (!map.containsKey(v)) {
map.put(v, 1);
} else {
map.put(v, map.get(v) + 1);
}
}
static void remove_map(HashMap<Integer, Integer> map, int v) {
if (map.containsKey(v)) {
map.put(v, map.get(v) - 1);
if (map.get(v) == 0)
map.remove(v);
}
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] arr) {
// shuffle
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int j = rand.nextInt(i + 1);
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
// shuffle
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int j = rand.nextInt(i + 1);
long tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Arrays.sort(arr);
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq = Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq = Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static void print_arr(int A[]) {
for (int i : A) {
System.out.print(i + " ");
}
System.out.println();
}
static void print_arr(long A[]) {
for (long i : A) {
System.out.print(i + " ");
}
System.out.println();
}
static void print_arr(char A[]) {
for (char i : A) {
System.out.print(i + " ");
}
System.out.println();
}
static int min(int a, int b) {
return Math.min(a, b);
}
static int min(int a, int b, int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a, int b, int c, int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int max(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a, int b, int c, int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a, long b) {
return Math.min(a, b);
}
static long min(long a, long b, long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a, long b, long c, long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a, long b) {
return Math.max(a, b);
}
static long max(long a, long b, long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a, long b, long c, long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static int max(int A[]) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
max = Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < A.length; i++) {
min = Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max = Long.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
max = Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min = Long.MAX_VALUE;
for (int i = 0; i < A.length; i++) {
min = Math.min(min, A[i]);
}
return min;
}
static long sum(int A[]) {
long sum = 0;
for (int i : A) {
sum += i;
}
return sum;
}
static long sum(long A[]) {
long sum = 0;
for (long i : A) {
sum += i;
}
return sum;
}
static ArrayList<Integer> sieve(int n) {
ArrayList<Integer> primes = new ArrayList<>();
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i < n; i++) {
if (isPrime[i])
primes.add(i);
}
return primes;
}
static class Reader {
BufferedReader br;
StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
Reader(File f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] nai(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | c69a8577888bb9a002f22027196ab54f | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class G {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
int countEven = 0, countOdd = 0;
LinkedList<Integer> evens = new LinkedList<>();
LinkedList<Integer> odds = new LinkedList<>();
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
if (arr[i] % 2 == 0) {
countEven++;
evens.addLast(i);
} else {
countOdd++;
odds.addLast(i);
}
}
int[] arrClone = arr.clone();
if ((n % 2 == 0 && countEven != countOdd) || (n % 2 != 0 && Math.abs(countEven - countOdd) != 1)) {
pw.println(-1);
continue;
}
if (n == 1) {
pw.println(0);
continue;
}
int min1 = 0;
boolean even = true;
for (int i = 0; i < n; i++) {
if (n % 2 != 0 && countOdd > countEven)
break;
if (even && arr[i] % 2 != 0) {
// System.out.println(i + " here1");
// System.out.println(Arrays.toString(arr));
int nextEven = evens.removeFirst();
odds.removeFirst();
odds.addFirst(nextEven);
min1 += nextEven - i;
int tmp = arr[i];
arr[i] = arr[nextEven];
arr[nextEven] = tmp;
} else if (!even && arr[i] % 2 == 0) {
// System.out.println(i + " here2");
// System.out.println(Arrays.toString(arr));
int nextOdd = odds.removeFirst();
evens.removeFirst();
evens.addFirst(nextOdd);
min1 += nextOdd - i;
int tmp = arr[i];
arr[i] = arr[nextOdd];
arr[nextOdd] = tmp;
} else if (even && arr[i] % 2 == 0) {
evens.removeFirst();
} else if (!even && arr[i] % 2 != 0) {
odds.removeFirst();
}
even = !even;
}
if (n % 2 != 0 && countOdd < countEven) {
pw.println(min1);
continue;
}
evens = new LinkedList<>();
odds = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (arrClone[i] % 2 == 0) {
evens.addLast(i);
} else {
odds.addLast(i);
}
}
int min2 = 0;
even = false;
for (int i = 0; i < n; i++) {
if (even && arrClone[i] % 2 != 0) {
int nextEven = evens.removeFirst();
odds.removeFirst();
odds.addFirst(nextEven);
min2 += nextEven - i;
int tmp = arrClone[i];
arrClone[i] = arrClone[nextEven];
arrClone[nextEven] = tmp;
} else if (!even && arrClone[i] % 2 == 0) {
int nextOdd = odds.removeFirst();
evens.removeFirst();
evens.addFirst(nextOdd);
min2 += nextOdd - i;
int tmp = arrClone[i];
arrClone[i] = arrClone[nextOdd];
arrClone[nextOdd] = tmp;
} else if (even && arrClone[i] % 2 == 0) {
evens.removeFirst();
} else if (!even && arrClone[i] % 2 != 0) {
odds.removeFirst();
}
even = !even;
}
if (n % 2 != 0 && countOdd > countEven) {
pw.println(min2);
continue;
}
pw.println(min1 < 0 ? min2 : min2 < 0 ? min1 : Math.min(min1, min2));
}
pw.flush();
pw.close();
}
}
class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 535c1cbc0526ab16d7d705110c530469 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.util.*;
import java.io.*;
public class B {
static int solve(int n, int arr[], int parity) {
int ans = 0;
for (int i = 0, j = 0; i < n; i++) {
if (j < i)
j = i;
if ((arr[i] & 1) != parity) {
while (j < n && ((arr[j] & 1) != parity))
j++;
if (j >= n) {
return Integer.MAX_VALUE;
} else {
ans += j - i;
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
parity = (parity == 0) ? 1 : 0;
}
// if ((arr[n - 1] & 1) == (arr[n - 2] & 1)) {
// return Integer.MAX_VALUE;
// }
return ans;
}
public static void main(String[] args) throws IOException {
// File file = new File("input.txt");
// BufferedReader br = new BufferedReader(new FileReader(file));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine().trim()), ans = 0, one = 0, zero = 0;
String Arr[] = br.readLine().split(" ");
int arr[] = new int[n], brr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(Arr[i].trim());
brr[i] = arr[i];
if ((arr[i] & 1) == 1) {
one++;
} else {
zero++;
}
}
if (Math.abs(one - zero) > 1) {
ans = -1;
} else if (n > 1) {
if (one == zero) {
ans = Math.min(solve(n, arr, 0), solve(n, brr, 1));
} else {
ans = solve(n, arr, (one > zero) ? 1 : 0);
}
if (ans == Integer.MAX_VALUE) {
ans = -1;
}
}
log.write(ans + "\n");
}
br.close();
log.flush();
} // end-main
} // end-class
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 68d6bf14907a5353124c6a8597bad70f | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void solve(InputReader in, PrintWriter out) {
int test = in.nextInt();
while (test-- > 0) {
int n = in.nextInt();
int[] A = new int[n];
int[] B = new int[n];
int[] C = new int[n];
int odd = 0, even = 0;
for (int i = 0; i < n; i++) {
A[i] = in.nextInt();
if (A[i] % 2 == 1) {
odd++;
} else {
even++;
}
}
if (Math.abs(odd - even) > 1) {
out.println(-1);
continue;
}
int l = 0, r = 0;
for (int i = 0; i < n; i++) {
if (A[i] % 2 != i % 2) {
if (A[i] % 2 == 1) {
B[l++] = i;
} else {
C[r++] = i;
}
}
}
int ans = Integer.MAX_VALUE;
int oddPos = 0, evenPos = 0;
if (l == r) {
odd = 0;
while (oddPos < l && evenPos < r) {
odd += Math.abs(B[oddPos++] - C[evenPos++]);
}
ans = Math.min(ans, odd);
}
l = 0;
r = 0;
for (int i = 0; i < n; i++) {
if (A[i] % 2 == i % 2) {
if (A[i] % 2 == 0) {
B[l++] = i;
} else {
C[r++] = i;
}
}
}
if (l == r) {
oddPos = 0;
evenPos = 0;
even = 0;
while (oddPos < l && evenPos < r) {
even += Math.abs(B[oddPos++] - C[evenPos++]);
}
ans = Math.min(ans, even);
}
out.println(ans);
}
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 5a60bd86f71cc92837ab2892b34a6872 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
// Sachin_2961 submission //
public class Codeforces {
static void solve() {
int n = fs.nInt();
int[]ar = new int[n],ar2 = new int[n];
for(int i=0;i<n;i++)
ar[i] = fs.nInt();
for(int i=0;i<n;i++){
ar2[i] = ar[i] = ar[i]%2;
}
if( n == 0 ){
out.println("0");
return;
}
ArrayList<Integer> even = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
long ans = 0,move = 0;
int e = 0, o = 0;
for(int i=0;i<n;i++){
if(ar[i] == 0)
even.add(i);
else
odd.add(i);
}
for(int i=0;i<n;i++){
if( ar[i] == i%2 ){
if(i%2 == 0)
e++;
else
o++;
}else if( i%2 == 1 ){
if( o == odd.size() ){
move = Integer.MAX_VALUE;
break;
}
move += abs(odd.get(o)-i);
ar[i] = 1;
ar[odd.get(o)] = 0;
o++;
}else{
if( e == even.size() ){
move = Integer.MAX_VALUE;
break;
}
move += abs(even.get(e)-i);
ar[i] = 0;
ar[even.get(e)] = 1;
e++;
}
}
ans = move;
move = 0; e = 0;o =0;
for(int i=1;i<=n;i++){
if( ar2[i-1] == i%2 ){
if(i%2 == 0)
e++;
else
o++;
}else if( i%2 == 1 ){
if( o == odd.size() ){
move = Integer.MAX_VALUE;
break;
}
move += abs(odd.get(o)-i+1);
ar2[i-1] = 1;
ar2[odd.get(o)] = 0;
o++;
}else{
if( e == even.size() ){
move = Integer.MAX_VALUE;
break;
}
move += abs(even.get(e)-i+1);
ar2[i-1] = 0;
ar2[even.get(e)] = 1;
e++;
}
}
ans = min(ans,move);
if(ans == Integer.MAX_VALUE)
ans = -1;
out.println(ans);
}
static boolean multipleTestCase = true; static FastScanner fs; static PrintWriter out;
public static void main(String[]args){
try{
fs = new FastScanner();
out = new PrintWriter(System.out);
int tc = (multipleTestCase)?fs.nInt():1;
while (tc-->0)solve();
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String n() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String Line()
{
String str = "";
try
{
str = br.readLine();
}catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int nInt() {return Integer.parseInt(n()); }
long nLong() {return Long.parseLong(n());}
double nDouble(){return Double.parseDouble(n());}
int[]aI(int n){
int[]ar = new int[n];
for(int i=0;i<n;i++)
ar[i] = nInt();
return ar;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 222f5901825e1eab53313f8e4994b45f | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Solution {
public static long gcd(long a,long b) {
if(a==0) return b;
return gcd(b%a,a);
}
public static long lcm(long a,long b) {
return (a*b)/gcd(a,b);
}
public static long [] input(BufferedReader br,int n) throws java.lang.Exception{
long ans[]=new long[n];
String input[]=br.readLine().split(" ");
for(int i=0;i<n;i++) {
ans[i]=Long.parseLong(input[i]);
}
return ans;
}
static class Node{
long left_Size;
long right_Size;
long total_Size;
long ans;
public Node() {
left_Size=0;
right_Size=0;
total_Size=0;
ans=0;
}
}
public static int oddCount(long arr[],int n) {
int j1=0;
int j2=0;
int count=0;
for(int i=0;i<n;i++) {
if(i%2==0) {
if(arr[i]%2!=0) continue;
else {
j1=Math.max(j1, i);
while(j1<n&&arr[j1]%2==0) {
j1++;
}
count+=j1-i;
long temp=arr[j1];
arr[j1]=arr[i];
arr[i]=temp;
}
}else {
if(arr[i]%2==0) continue;
else {
j2=Math.max(j2, i);
while(j2<n&&arr[j2]%2!=0) {
j2++;
}
count+=j2-i;
long temp=arr[j2];
arr[j2]=arr[i];
arr[i]=temp;
}
}
}
return count;
}
public static int evenCount(long arr[],int n) {
int j1=0;
int j2=0;
int count=0;
for(int i=0;i<n;i++) {
if(i%2==0) {
if(arr[i]%2==0) continue;
else {
j1=Math.max(j1, i) ;
while(j1<n&&arr[j1]%2!=0) {
j1++;
}
count+=j1-i;
long temp=arr[j1];
arr[j1]=arr[i];
arr[i]=temp;
}
}else {
if(arr[i]%2!=0) continue;
else {
j2=Math.max(j2, i) ;
while(j2<n&&arr[j2]%2==0) {
j2++;
}
count+=j2-i;
long temp=arr[j2];
arr[j2]=arr[i];
arr[i]=temp;
}
}
}
return count;
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int testCases=Integer.parseInt(br.readLine());
// int testCases=1;
while(testCases-->0) {
int n=(int)input(br,1)[0];
long arr[]=input(br,n);
long even=0;
long odd=0;
for(long a:arr) {
if(a%2==0) even++;
else odd++;
}
if(Math.abs(even-odd)>1) out.println(-1);
else if(even>odd) {
out.println(evenCount(arr,n));
}else if(odd>even) {
out.println(oddCount(arr,n));
}else {
long copy[]=Arrays.copyOf(arr, n);
out.println(Math.min(evenCount(copy,n),oddCount(arr,n)));
}
}
out.close();
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 686552c75bd53167ccf0d3f7add117a6 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
static long mod=((long)1e9)+7;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
sc=new FastReader();
int t=sc.nextInt();
// boolean[] seave=sieveOfEratosthenes((int)(1e7));
// int[] seave2=sieveOfEratosthenesInt((int)(1e4));
// int tp=1;
while(t--!=0){
int n=sc.nextInt();
long[] arr1=new long[n];
long[] arr2=new long[n];
for(int i=0;i<n;i++){
arr1[i]=sc.nextInt();
arr2[i]=arr1[i];
}
List<Integer> evenv=new ArrayList<>();
List<Integer> odd=new ArrayList<>();
List<Integer> evenv2=new ArrayList<>();
List<Integer> odd2=new ArrayList<>();
for(int i=0;i<n;i++){
if(arr1[i]%2==0){
evenv.add(i);
evenv2.add(i);
}else{
odd.add(i);
odd2.add(i);
}
}
int min=Integer.MAX_VALUE;
// debug(arr);
if(abs(evenv.size()-odd.size())>1){
print(-1);
continue;
}
int a=count(true,evenv,odd,arr1);
// int a=9;
// debug(arr);
int b=count(false,evenv2,odd2,arr2);
// debug(a+" "+b);
print(min(a,b)==Integer.MAX_VALUE?-1:min(a,b));
}
// System.out.println(String.format("%.9f", max));
}
private static int count(boolean even,List<Integer> evenv,List<Integer> odd,long[] arr){
int c=0;
boolean done=true;
int n=arr.length;
int e=0;
int o=0;
for(int i=0;i<n;i++){
while(evenv.size()>e&&evenv.get(e)<=i)e++;
while(odd.size()>o&&odd.get(o)<=i)o++;
// debug(evenv+" "+odd+" "+i);
// debug("go");
if(arr[i]%2==0&&!even){
if(odd.size()<=o){
done=false;
break;
}
swap(arr,odd.get(o),i);
// debug(i+" "+odd+" up");
c+=abs(odd.get(o)-i);
o++;
}else if(arr[i]%2!=0&&even){
if(evenv.size()<=e){
done=false;
break;
}
swap(arr,evenv.get(e),i);
// debug(i+" "+evenv+" down ");
c+=abs(evenv.get(e)-i);
e++;
}
even=(even==false)?true:false;
}
if(!done)return Integer.MAX_VALUE;
return c;
}
private static void swap(long arr[],int i,int j){
long t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
private static int lessThen(long[] nums,long val){
int i=0,l=0,r=nums.length-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int greaterThen(long[] nums,long val){
int i=nums.length-1,l=0,r=nums.length-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static long sumOfAp(long a,long n,long d){
long val=(n*( 2*a+((n-1)*d)));
return val/2;
}
//geometrics
private static double areaOftriangle(double x1,double y1,double x2,double y2,double x3,double y3){
double[] mid_point=midOfaLine(x1,y1,x2,y2);
// debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+" "+y3);
double height=distanceBetweenPoints(mid_point[0],mid_point[1],x3,y3);
double wight=distanceBetweenPoints(x1,y1,x2,y2);
// debug(height+" "+wight);
return (height*wight)/2;
}
private static double distanceBetweenPoints(double x1,double y1,double x2,double y2){
double x=x2-x1;
double y=y2-y1;
return sqrt(Math.pow(x,2)+Math.pow(y,2));
}
private static double[] midOfaLine(double x1,double y1,double x2,double y2){
double[] mid=new double[2];
mid[0]=(x1+x2)/2;
mid[1]=(y1+y2)/2;
return mid;
}
private static long sumOfN(long n){
return (n*(n+1))/2;
}
private static long power(long x,long y,long p){
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0){
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
/* Function to calculate x raised to the power y in O(logn)*/
static long power(long x, long y){
long temp;
if( y == 0)
return 1l;
temp = power(x, y / 2);
if (y % 2 == 0)
return (temp*temp);
else
return (x*temp*temp);
}
private static StringBuilder reverseString(String s){
StringBuilder sb=new StringBuilder(s);
int l=0,r=sb.length()-1;
while(l<=r){
char ch=sb.charAt(l);
sb.setCharAt(l,sb.charAt(r));
sb.setCharAt(r,ch);
l++;
r--;
}
return sb;
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static long lcm(long a, long b){
return (a / gcd(a, b)) * b;
}
private static String decimalToString(int x){
return Integer.toBinaryString(x);
}
private static boolean isPallindrome(String s){
int l=0,r=s.length()-1;
while(l<r){
if(s.charAt(l)!=s.charAt(r))return false;
l++;
r--;
}
return true;
}
private static StringBuilder removeLeadingZero(StringBuilder sb){
int i=0;
while(i<sb.length()&&sb.charAt(i)=='0')i++;
// debug("remove "+i);
if(i==sb.length())return new StringBuilder();
return new StringBuilder(sb.substring(i,sb.length()));
}
private static int stringToDecimal(String binaryString){
// debug(decimalToString(n<<1));
return Integer.parseInt(binaryString,2);
}
private static int stringToInt(String s){
return Integer.parseInt(s);
}
private static String toString(int val){
return String.valueOf(val);
}
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToInt(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
//read graph
private static List<List<Integer>> readUndirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readUndirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static int[] sieveOfEratosthenesInt(long n){
boolean prime[] = new boolean[(int)n + 1];
Set<Integer> li=new HashSet<>();
for (int i = 1; i <= n; i++){
prime[i] = true;
li.add(i);
}
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true){
for (int i = p * p; i <= n; i += p){
li.remove(i);
prime[i] = false;
}
}
}
int[] arr=new int[li.size()+1];
int i=0;
for(int x:li){
arr[i++]=x;
}
return arr;
}
public static long Kadens(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
// System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] readIntIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][i]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] readIntArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static void print(int[] arr){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
return true;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | a25a5038ec01c9d8e0d4304d2a41a318 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | //package Codeforces.Practice1300;
import java.io.*;
import java.util.*;
public class TakeYourPlaces {
public static void main(String[] args) throws Exception {new TakeYourPlaces().run();}
long mod = 1000000000 + 7;
int[][] dp= new int[32][200001];
// int[][] ar;
void solve() throws Exception {
int t=ni();
while(t-->0){
int n = ni();
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i] = ni();
}
int ce =0;
int co =0;
for(int i:a){
if(i%2==0)ce++;
else co++;
}
if(n==1){
out.println(0);
continue;
}
for(int i=0;i<n;i++){
a[i] = a[i]%2;
}
if(n%2==0){
if(co==ce){
out.println(Math.min(checkCount(0,a),checkCount(1,a)));
}else out.println(-1);
}else{
if(co==ce+1){
out.println(checkCount(1,a));
}else if(ce==co+1){
out.println(checkCount(0,a));
}else out.println(-1);
}
}
}
int checkCount(int x,int[] a){
int cnt=0;
int d=0;
int n = a.length;
for(int i=0;i<n;i++){
if(a[i]%2!=x)d+=(x-a[i]);
cnt+=Math.abs(d);
x^=1;
}
return cnt;
}
int[] sort(int[] a){
List<Integer> l= new ArrayList<>();
for(int i:a) l.add(i);
int[] res = new int[l.size()];
for(int i=0;i<l.size();i++){
res[i] = l.get(i);
}
return res;
}
void formDP(){
for(int i=0;i<32;i++){
for(int j=1;j<200001;j++){
if((j&(1<<i))==0){
dp[i][j] = dp[i][j-1];
}else{
dp[i][j]=1+dp[i][j-1];
}
}
}
}
// void buildMatrix(){
//
// for(int i=1;i<=1000;i++){
//
// ar[i][1] = (i*(i+1))/2;
//
// for(int j=2;j<=1000;j++){
// ar[i][j] = ar[i][j-1]+(j-1)+i-1;
// }
// }
// }
/* FAST INPUT OUTPUT & METHODS BELOW */
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar) {
int min = Integer.MAX_VALUE;
for (int i : ar)
min = Math.min(min, i);
return min;
}
long min(long... ar) {
long min = Long.MAX_VALUE;
for (long i : ar)
min = Math.min(min, i);
return min;
}
int max(int... ar) {
int max = Integer.MIN_VALUE;
for (int i : ar)
max = Math.max(max, i);
return max;
}
long max(long... ar) {
long max = Long.MIN_VALUE;
for (long i : ar)
max = Math.max(max, i);
return max;
}
void shuffle(int a[]) {
ArrayList<Integer> al = new ArrayList<>();
for (int i = 0; i < a.length; i++)
al.add(a[i]);
Collections.sort(al);
for (int i = 0; i < a.length; i++)
a[i] = al.get(i);
}
long lcm(long a, long b) {
return (a * b) / (gcd(a, b));
}
int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
/*
* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2))
*/
long expo(long p, long q) /* (p^q)%mod */
{
long z = 1;
while (q > 0) {
if (q % 2 == 1) {
z = (z * p) % mod;
}
p = (p * p) % mod;
q >>= 1;
}
return z;
}
void run() throws Exception {
in = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException {
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException {
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 2722964f32e620fa54842e93c12a5515 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.io.*;
public class Eshan {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) throws IOException {
int t = readInt();
while (t-- > 0) {
int n = readInt(), o = 0;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = (readInt() & 1);
o += arr[i];
}
if (Math.abs(n - 2 * o) > 1)
out.println(-1);
else if ((n & 1) == 0)
out.println(Math.min(helper(arr, 0, n), helper(arr, 1, n)));
else if (o + 1 == n - o)
out.println(helper(arr, 0, n));
else if (o == n - o + 1)
out.println(helper(arr, 1, n));
}
out.flush();
}
private static int helper(int[] arr, int curr, int n) {
int ans = 0, del = 0;
for (int i = 0; i < n; i++) {
del += curr - arr[i];
ans += Math.abs(del);
curr = 1 - curr;
}
return ans;
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_power(int a, int b, int mod) {
if (b == 0)
return 1;
int temp = mod_power(a, b / 2, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static boolean isPalindrome(String str, int n) {
int i = 0, j = n - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 6ad05179242090079c373657c3b5725d | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.io.*;
public class Eshan {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) throws IOException {
int t = readInt();
while (t-- > 0) {
int n = readInt(), o = 0;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = (readInt() & 1);
o += arr[i];
}
if ((n & 1) == 0) {
if (o == n - o)
out.println(Math.min(helper(arr, 0, n), helper(arr, 1, n)));
else
out.println(-1);
} else {
if (o + 1 == n - o)
out.println(helper(arr, 0, n));
else if (o == n - o + 1)
out.println(helper(arr, 1, n));
else
out.println(-1);
}
}
out.flush();
}
private static int helper(int[] arr, int curr, int n) {
int ans = 0, del = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != curr)
del += curr - arr[i];
ans += Math.abs(del);
curr = 1 - curr;
}
return ans;
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_power(int a, int b, int mod) {
if (b == 0)
return 1;
int temp = mod_power(a, b / 2, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static boolean isPalindrome(String str, int n) {
int i = 0, j = n - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | acb5627ec5e71ff341d60cc406d448d1 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int o = 0, e = 0;
int n = sc.nextInt();
int[] arr = new int[n];
ArrayList<Integer> odd = new ArrayList<>();
ArrayList<Integer> even = new ArrayList<>();
for(int i = 0 ; i< n ; i++) {
arr[i] = sc.nextInt();
if(arr[i]%2 == 0) {
e++;
even.add(i);
}
else {
o++;
odd.add(i);
}
}
if(Math.abs(o-e) > 1) {
System.out.println("-1");
}else if( o-e == 1) {
int ans = 0;
int idx = 0;
for(int i = 0 ; i < n ; i+= 2) {
ans += Math.abs(odd.get(idx++) - i);
}
System.out.println(ans);
}else if(e-o == 1) {
int ans = 0;
int idx = 0;
for(int i = 0 ; i < n ; i+= 2) {
ans += Math.abs(even.get(idx++) - i);
}
System.out.println(ans);
}else {
int ans = Integer.MAX_VALUE;
int cur=0;
int idx = 0;
for(int i = 0 ; i < n ; i+= 2) {
cur += Math.abs(odd.get(idx++) - i);
}
ans = Math.min(cur,ans);
cur = 0;
idx = 0;
for(int i = 1 ; i < n ; i+= 2) {
cur += Math.abs(odd.get(idx++) - i);
}
ans = Math.min(cur,ans);
System.out.println(ans);
}
}
System.exit(0);
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | b2ff75b3764b2d5a8d979b84fbf156bd | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*; // Implicit import
import java.io.*;
import java.math.BigInteger; // Explicit import
public class A {
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
int t = sc.ni();
while (t-- > 0) {
A.go();
}
out.flush();
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static void go() {
int n=sc.ni();
int a[]=sc.intArray(n);
int odd=0;
int even=0;
for(int i=0;i<n;i++) {
if(a[i]%2!=0) {
odd++;
}else {
even++;
}
}
if(n%2==0) {
if(odd!=even) {
out.println(-1);
return;
}
}
if(n%2!=0) {
if(Math.abs(odd-even)!=1) {
out.println(-1);
return;
}
}
int val1=2;
int val2=1;
int aa[]=a.clone();
for(int i=0;i<n;i++) {
if(a[i]%2==0) {
a[i]=val1;
val1+=2;
}else {
a[i]=val2;
val2+=2;
}
}
int x=countSwaps(a,n);
val1=2;
val2=3;
for(int i=0;i<n;i++) {
if(aa[i]%2==0) {
aa[i]=val1;
val1+=2;
}else {
aa[i]=val2;
val2+=2;
}
}
int xx=countSwaps(aa,n);
boolean f=false,ff=false;
for(int i=0;i<n-1;i++) {
int diff=Math.abs(a[i]-a[i+1]);
if(diff%2==0) {
f=true;
break;
}
}
for(int i=0;i<n-1;i++) {
int diff=Math.abs(aa[i]-aa[i+1]);
if(diff%2==0) {
ff=true;
break;
}
}
if(f==true && ff==true) {
out.println(-1);
return;
}
if(f==false && ff==true) {
out.println(x);
}else if(f==true && ff==false) {
out.println(xx);
}else {
out.println(Math.min(xx, x));
}
}
static int merge(int arr[], int temp[],
int left, int mid, int right)
{
int inv_count = 0;
/* i is index for left subarray*/
int i = left;
/* j is index for right subarray*/
int j = mid;
/* k is index for resultant merged subarray*/
int k = left;
while ((i <= mid - 1) && (j <= right))
{
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else
{
temp[k++] = arr[j++];
/* this is tricky -- see above /
explanation diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left
subarray (if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right
subarray (if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements
to original array*/
for (i=left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
//An auxiliary recursive function that
//sorts the input array and returns
//the number of inversions in the array.
static int _mergeSort(int arr[], int temp[],
int left, int right)
{
int mid, inv_count = 0;
if (right > left)
{
// Divide the array into two parts and
// call _mergeSortAndCountInv() for
// each of the parts
mid = (right + left)/2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp,
left, mid);
inv_count += _mergeSort(arr, temp,
mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp,
left, mid+1, right);
}
return inv_count;
}
//This function sorts the input
//array and returns the number
//of inversions in the array
static int countSwaps(int arr[], int n)
{
int temp[] = new int[n];
return _mergeSort(arr, temp, 0, n - 1);
}
static class helper{
int x,y;
helper(int x,int y){
this.x=x;
this.y=y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
helper other = (helper) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static long fact[];
static long invfact[];
static long ncr(int n, int k) {
if (k < 0 || k > n) {
return 0;
}
long x = fact[n] % mod;
long y = invfact[k] % mod;
long yy = invfact[n - k] % mod;
long ans = (x * y) % mod;
ans = (ans * yy) % mod;
return ans;
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static int prime[] = new int[200005];
static int N = 200005;
static void sieve() {
for (int i = 0; i < N; i++) {
prime[i] = i;
}
for (int i = 2; i * i <= N; i++) {
if (prime[i] == i) {
prime[i] = i;
for (int j = i; j < N; j += i) {
prime[j] = i;
}
}
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> aa = new ArrayList<>();
for (Integer i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (Long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static int mod = (int) 1000000007;
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = (x % mod * res % mod) % mod;
}
y /= 2;
x = (x % mod * x % mod) % mod;
}
return res % mod;
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] intArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.ni();
return a;
}
long[] longArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nl();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 55f4f68feffd52fc06933b422ab4cad8 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t--!=0) {
int n=sc.nextInt();
long arr[]=new long[n];
int even=0,odd=0;
for(int i=0;i<n;i++) {
if(sc.nextLong()%2==0) {//even
arr[i]=0;
even++;
}else {//odd
arr[i]=1;
odd++;
}
}
// System.out.println(Arrays.toString(arr));
if(n==1)
System.out.println(0);
else if(Math.abs(even-odd)>1){
System.out.println(-1);
}else {
if(even>odd) {
System.out.println(countFun(arr, 0));
}else if(odd>even) {
System.out.println(countFun(arr, 1));
}else { //odd=even
long res=Math.min(countFun(arr, 0),countFun(arr, 1));
System.out.println(res);
}
}
}
}
private static long countFun(long[] a, long ind) {
long count = 0;
for(int i = 0; i < a.length; i++){
if(a[i] == 0){
count += Math.abs(i - ind);
ind += 2;
}
}
return count;
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | 599a08b58099026f8f6c9e8ce0a3ba81 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final int inf = Integer.MAX_VALUE / 2;
static final long infL = Long.MAX_VALUE / 3;
static final double infD = Double.MAX_VALUE / 3;
static final double eps = 1e-10;
static final double pi = Math.PI;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int test= sc.nextInt();
while(test -- > 0){
int n = sc.nextInt();
int[] arr = new int[n];
int[] second = new int[n];
for(int i = 0; i < n ;i++){
arr[i] = sc.nextInt();
second[i] = arr[i];
}
int odd = 0;
int even = 0;
for(int i: arr){
if(i%2 ==1 ) odd++;
}
even = n-odd;
//the worst condition to happen for sure
if(Math.abs(even-odd)>1){
out.println(-1);
continue;
}
long pri = 0;
//assuming odd position
int j = 0;
for(int i= 0;i < n ;i++){
if((i%2 == 0 && arr[i]%2 == 1 )|| (arr[i]%2 == 0 && i%2 == 1)) continue;
if(j < i) j = i+1;
while(true){
if(j >= n) break;
if(arr[i]%2 == arr[j]%2){
j++;
}else{
swap(arr, i, j);
pri += j-i;
break;
}
}
}
long sec = 0;
j = 0;
for(int i= 0;i < n ;i++){
// System.out.println(Arrays.toString(second));
if((i%2 == 0 && second[i]%2 == 0 ) || (second[i]%2 == 1 && i%2 == 1)) continue;
if(j < i) j = i+1;
while(true){
if(j >= n) break;
if(second[i]%2 == second[j]%2){
j++;
}else{
swap(second, i, j);
sec += j-i;
break;
}
}
}
//for printing the right format for right conditions
//never doubt yourself in here
// out.println(sec+ " "+ pri);
if(n%2 == 1 && even > odd){
out.println(sec);
continue;
}
if(n%2 == 1 && odd > even){
out.println(pri);
continue;
}
long answer = Math.min(sec, pri);
out.println(answer);
}
out.close();
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//two add two big numbers with some mod
public static int add(int a, int b) {
a+=b;
if (a>=mod) return a-mod;
return a;
}
//two sub two numbers
public static int sub(int a, int b) {
a-=b;
if (a<0) a+=mod;
else if (a>=mod) a-=mod;
return a;
}
//to sort the array with better method
public static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | f0223e64d3091ab7387e5731975ffcd9 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class B{
public static void main(String[] args) throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
//new Thread(null, new (), "peepee", 1<<28).start();
int t =readInt();
while(t-->0) {
int n =readInt();
int[] a= new int[n];
int ct0 = 0, ct1 = 0;
List<Integer> p0 = new ArrayList<Integer>();
List<Integer> p1 = new ArrayList<Integer>();
for (int i = 0; i< n; i++) {
a[i] =readInt()%2;
if (a[i]==1) {
ct1++;
p1.add(i);
}
else {
ct0++;
p0.add(i);
}
}
if (abs(ct1-ct0) >= 2) {
out.println(-1);
continue;
}
// Minimum to get 01010101 or 10101010 should be shitty brtue force?
long min = n;
min *= n;
long v;
if (ct0 >= ct1) {
v = 0;
for(int i = 0; i <n; i+=2) {
v += abs(i-p0.get(i/2));
}
//System.out.println("yo " + v);
min = min(v,min);
//System.out.println("Yo " + v);
v = 0;
for (int i =1; i < n; i+=2) {
v += abs(i-p1.get(i/2));
// System.out.println("Added " + abs(i-p0.get(i/2)) + " " + i + " " + p0.get(i/2));
}
//System.out.println("Yo " + v);
min = min(v,min);
}
if (ct1 >= ct0){
v = 0;
for(int i = 0; i <n; i+=2) {
v += abs(i-p1.get(i/2));
}
min = min(v,min);
v = 0;
for (int i =1; i < n; i+=2) {
v += abs(i-p0.get(i/2));
}
//System.out.println("Yo " + v);
min = min(v,min);
}
out.println(min);
}
out.close();
}
/* Stupid things to try if stuck:
* n=1, expand bsearch range
* brute force small patterns
* submit stupid intuition
*/
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st = new StringTokenizer("");
static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();}
static int readInt() throws IOException{return Integer.parseInt(read());}
static long readLong() throws IOException{return Long.parseLong(read());}
static double readDouble() throws IOException{return Double.parseDouble(read());}
} | Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output | |
PASSED | c312c895a88961676670a512bdc23397 | train_107.jsonl | 1630247700 | William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Queue;
import java.util.LinkedList;
public class string {
class Par {
int vr;
int ind;
public Par(int vr, int ind) {
this.vr = vr;
this.ind = ind;
}
}
public static void main(String[] args) throws IOException {
class Par {
int vr;
int ind;
public Par(int vr, int ind) {
this.vr = vr;
this.ind = ind;
}
}
Scanner in = new Scanner(System.in);
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int tt = in.nextInt();
for(int w = 0; w<tt; w++) {
int n = in.nextInt();
int[] a = new int[n];
Queue<Par> q1 = new LinkedList<>();
Queue<Par> q2 = new LinkedList<>();
Queue<Par> q3 = new LinkedList<>();
Queue<Par> q4 = new LinkedList<>();
int parni = 0;
int neparni = 0;
for(int i = 0; i<n; i++) {
a[i] = in.nextInt();
if(a[i]%2==0) {
q1.add(new Par(a[i],i));
q3.add(new Par(a[i],i));
}
else {
q2.add(new Par(a[i],i));
q4.add(new Par(a[i],i));
}
}
if(neparni>(n+1)/2 || parni>(n+1)/2) {
log.write(-1+"\n");
log.flush();
continue;
}
boolean[] zauzeto = new boolean[n];
int[] b = Arrays.copyOf(a, n);
int ans1 = 0;
int ans2 = 0;
for(int i = 0; i<n; i++) {
if(a[i]%2==i%2) {
if(i%2==0) {
q1.poll();
}
else {
q2.poll();
}
continue;
}
if(q2.isEmpty() || q1.isEmpty()) {
ans1 = -1;
break;
}
if(a[i]%2==0) {
int tmp = a[i];
a[i] = q2.peek().vr;
a[q2.peek().ind] = tmp;
ans1+=Math.abs(i-q2.peek().ind);
q2.poll();
}
else {
int tmp = a[i];
a[i] = q1.peek().vr;
a[q1.peek().ind] = tmp;
ans1+=Math.abs(i-q1.peek().ind);
q1.poll();
}
}
for(int i = 0; i<n; i++) {
if(b[i]%2!=i%2) {
if(i%2==0) {
q4.poll();
}
else {
q3.poll();
}
continue;
}
if(q3.isEmpty() || q4.isEmpty()) {
ans2 = -1;
break;
}
if(b[i]%2==0) {
int tmp = b[i];
b[i] = q4.peek().vr;
b[q4.peek().ind] = tmp;
ans2+=Math.abs(i-q4.peek().ind);
q4.poll();
}
else {
int tmp = b[i];
b[i] = q3.peek().vr;
b[q3.peek().ind] = tmp;
ans2+=Math.abs(i-q3.peek().ind);
q3.poll();
}
}
if(ans1==-1) {
log.write(ans2+"\n");
}
else if(ans2==-1) {
log.write(ans1+"\n");
}
else {
log.write(Math.min(ans1, ans2)+"\n");
}
log.flush();
}
}
}
| Java | ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"] | 1 second | ["1\n0\n3\n-1\n2"] | NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ | Java 11 | standard input | [
"implementation"
] | be51a3e4038bd9a3f6d4993b75a20d1c | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,300 | For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.