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
b79f765114c550a2a25545c847d4a195
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
/*LoudSilence*/ import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ static FastScanner s = new FastScanner(); static FastWriter out = new FastWriter(); final static int mod = (int)1e9 + 7; final static int INT_MAX = Integer.MAX_VALUE; final static int INT_MIN = Integer.MIN_VALUE; final static long LONG_MAX = Long.MAX_VALUE; final static long LONG_MIN = Long.MIN_VALUE; final static double DOUBLE_MAX = Double.MAX_VALUE; final static double DOUBLE_MIN = Double.MIN_VALUE; final static float FLOAT_MAX = Float.MAX_VALUE; final static float FLOAT_MIN = Float.MIN_VALUE; /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ static class FastScanner{BufferedReader br;StringTokenizer st; public FastScanner() {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());} List<Integer> readIntList(int n){List<Integer> arr = new ArrayList<>(); for(int i = 0; i < n; i++) arr.add(s.nextInt()); return arr;} List<Long> readLongList(int n){List<Long> arr = new ArrayList<>(); for(int i = 0; i < n; i++) arr.add(s.nextLong()); return arr;} int[] readIntArr(int n){int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = s.nextInt(); return arr;} long[] readLongArr(int n){long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = s.nextLong(); return arr;} String nextLine(){String str = "";try{str = br.readLine();}catch (IOException 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 debug(int object[]) throws IOException{bw.append("["); for(int i = 0; i < object.length; i++){if(i != object.length-1){print(object[i]+", ");}else{print(object[i]);}}bw.append("]\n");} public void debug(long object[]) throws IOException{bw.append("["); for(int i = 0; i < object.length; i++){if(i != object.length-1){print(object[i]+", ");}else{print(object[i]);}}bw.append("]\n");} public void close() throws IOException{bw.close();}} /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ public static ArrayList<Integer> seive(int n){ArrayList<Integer> list = new ArrayList<>();int arr[] = new int[n+1];for(int i = 2; i <= n; i++) {if(arr[i] == 1) {continue;}else {list.add(i);for(int j = i*i; j <= n; j = j + i) {arr[j] = 1;}}}return list;} 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 void swap(int[] arr, int i, int j) {arr[i] = arr[i] ^ arr[j]; arr[j] = arr[j] ^ arr[i]; arr[i] = arr[i] ^ arr[j];} 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 mod_add(long a, long b){ return (a%mod + b%mod)%mod;} public static long mod_sub(long a, long b){ return (a%mod - b%mod + mod)%mod;} public static long mod_mul(long a, long b){ return (a%mod * b%mod)%mod;} public static long modInv(long a, long b){ return expo(a, b-2)%b;} public static long mod_div(long a, long b){return mod_mul(a, modInv(b, mod));} public static long expo (long a, long n){if(n == 0){return 1;}long recAns = expo(mod_mul(a,a), n/2);if(n % 2 == 0){return recAns;}else{return mod_mul(a, recAns);}} /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ // Pair class public static class Pair<X extends Comparable<X>,Y extends Comparable<Y>> implements Comparable<Pair<X, Y>>{ X first; Y second; public Pair(X first, Y second){ this.first = first; this.second = second; } public String toString(){ return "( " + first+" , "+second+" )"; } @Override public int compareTo(Pair<X, Y> o) { int t = first.compareTo(o.first); if(t == 0) return second.compareTo(o.second); return t; } } /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ // Code begins public static void solve() throws IOException { int n = s.nextInt(); int arr[] = s.readIntArr(n); if(n == 1){ out.println(0); return; } List<Pair<Integer, Integer>> e = new ArrayList<>(); List<Pair<Integer, Integer>> o = new ArrayList<>(); for(int i = 0; i < n; i++){ int ele = arr[i]; if((ele & 1) == 1) o.add(new Pair<>(ele, i)); else e.add(new Pair<>(ele, i)); } for(int ele : arr){ } if((n&1) == 1){ // Odd if(abs(o.size() - e.size()) > 1){ out.println(-1); return; } List<Pair<Integer, Integer>> ans = new ArrayList<>(); int ei = 0; int oi = 0; boolean even = false; if(e.size() > o.size()){ even = true; } for(int i = 0; i < n; i++){ if(even){ ans.add(e.get(ei)); ei++; even = !even; }else{ ans.add(o.get(oi)); oi++; even = !even; } } long op = 0; for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans.get(i); if(p.first % 2 == 1){ op += abs(p.second - i); } } out.println(op); }else{ // Even if(e.size() != o.size()){ out.println(-1); return; }else{ List<Pair<Integer, Integer>> ans1 = new ArrayList<>(); List<Pair<Integer, Integer>> ans2 = new ArrayList<>(); int ei = 0; int oi = 0; boolean even = true; for(int i = 0; i < n; i++){ if(even){ ans1.add(e.get(ei)); ei++; even = !even; }else{ ans1.add(o.get(oi)); oi++; even = !even; } } ei = 0; oi = 0; even = false; for(int i = 0; i < n; i++){ if(even){ ans2.add(e.get(ei)); ei++; even = !even; }else{ ans2.add(o.get(oi)); oi++; even = !even; } } long op1 = 0; long op2 = 0; for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans1.get(i); if(p.first % 2 == 1){ op1 += abs(p.second - i); } } for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans2.get(i); if(p.first % 2 == 1){ op2 += abs(p.second - i); } } out.println(min(op1, op2)); } } } /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ public static void main(String[] args) throws IOException { int test = s.nextInt(); for(int tt = 1; tt <= test; tt++) { solve(); } 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
52e3162e32f1bd655261f6846a680623
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 long mod = 1000000007; public static int len; public static void main(String[] args) { PrintWriter pr = new PrintWriter(System.out); FastScanner input = new FastScanner(); int num = input.nextInt(); for (int i = 0; i < num; i ++) { len = input.nextInt(); int[] arr = new int[len]; int odd = 0; for (int k = 0; k < len; k ++) { int hold = input.nextInt(); if (hold % 2 == 0) arr[k] = 0; else { arr[k] = 1; odd += 1; } } if (Math.abs((len - odd) - odd) > 1) System.out.println(-1); else { int[] ar = new int[len]; for (int k = 0; k < len; k ++) ar[k] = arr[k]; if (len - odd == odd) System.out.println(Math.min(check(arr, 1), check(ar, 0))); else if (len - odd == odd + 1) System.out.println(check(arr, 0)); else System.out.println(check(arr, 1)); } } } public static int check(int[] arr, int r) { int p2 = 0; int ans = 0; for (int p1 = 0; p1 < len; p1 ++) { if (arr[p1] != r) { if (p2 < p1) p2 = p1; while (p2 + 1 < len) { if (arr[p2] == r) break; else p2 += 1; } if (arr[p2] != r) ans = 99999999; ans += p2 - p1; arr[p2] = arr[p1]; arr[p1] = r; } if (r == 1) r = 0; else r = 1; } return ans; } public static class point implements Comparable<point> { public int x, y; public point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(point a) { if (this.x > a.x) return 1; else if (this.x == a.x) return 0; else return -1; } } public static long modexp(long a, long b) { return modexp(a, b, mod); } public static long modexp(long a, long b, long m) { long res = 1; while (b > 0) { if (b % 2 != 0) res = (res * a) % m; a = (a * a) % m; b /= 2; } return res; } public static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, 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()); } 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 Graph { public int V; public LinkedList<Integer> adj[]; @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; i ++) adj[i] = new LinkedList(); } void addEdge(int v, int w) { adj[v].add(w); } void DFS(int v, boolean visited[]) { visited[v] = true; System.out.print(v + " "); Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFS(n, visited); } } }
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
2471bbc9957bcff0a480d09a4b5befa9
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.math.BigInteger; import java.io.*; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "whatever", 1 << 26).start(); } private FastScanner sc; private PrintWriter pw; public void run() { try { // pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // sc = new FastScanner(new BufferedReader(new FileReader("input.txt"))); pw = new PrintWriter(System.out); sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); } catch (Exception e) { throw new RuntimeException(); } int t = sc.nextInt(); // int t = 1; while (t-- > 0) { // sc.nextLine(); solve(); } pw.close(); } public long mod = 1_000_000_007; public void solve() { int n = sc.nextInt(); int[] arr = new int[n]; int odds = 0, evens = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt() % 2; if (arr[i] == 1) odds++; } evens = n - odds; if (!((n % 2 == 0 && odds == evens) || (n % 2 != 0 && (odds == evens + 1 || odds + 1 == evens)))) { // pw.println("HERE 2"); pw.println(-1); return; } if (odds == evens) { //010...01 //or //101..10 int ans1 = 0, ans2 = 0; int temp = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) { ans1 += Math.abs(i - temp); temp += 2; } } temp = 0; for (int i = 0; i < n; i++) { if (arr[i] == 1) { ans2 += Math.abs(i - temp); temp += 2; } } pw.println(Math.min(ans1, ans2)); return; } if (odds == evens + 1) { // 101010...01 int ans = 0; int temp = 0; for (int i = 0; i < n; i++) { if (arr[i] == 1) { ans += Math.abs(i - temp); temp += 2; } } pw.println(ans); return; } if (odds + 1 == evens) { // 01010...10 int ans = 0; int temp = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) { ans += Math.abs(i - temp); temp += 2; } } pw.println(ans); return; } } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(BufferedReader bf) { reader = bf; tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String[] nextStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } public long[] nextLongArray(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 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
5813b5a1ea8f600369bb49275f86e8a9
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.File; import java.io.*; import java.util.*; public class Main { // static final File ip = new File("input.txt"); // static final File op = new File("output.txt"); // static { // try { // System.setOut(new PrintStream(op)); // System.setIn(new FileInputStream(ip)); // } catch (Exception e) { // } // } static long MOD = (long) 1e9 + 7; static int fun(int x, long[] arr) { int ans = 0; int delta = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] != x) delta += (x - arr[i]); ans += Math.abs(delta); x ^= 1; } return ans; } public static void main(String[] args) { FastReader sc = new FastReader(); int test = sc.nextInt(); while (test-- != 0) { int n = sc.nextInt(); long[] a = new long[n]; int[] f = new int[2]; for (int i = 0; i < n; i++) { a[i] = sc.nextLong(); a[i] = a[i] % 2; if (a[i] == 0) f[0]++; else f[1]++; } if(Math.abs(f[0]-f[1]) > 1) System.out.println("-1"); else if (n % 2 == 0) { if (f[0] == f[1]) { int ans = Math.min(fun(0, a), fun(1, a)); System.out.println(ans); } else System.out.println("-1"); } else { if (f[0] == f[1] + 1) System.out.println(fun(0, a)); else if (f[1] == f[0] + 1) System.out.println(fun(1, a)); else System.out.println("-1"); } } } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static int countSetBits(long number) { int count = 0; while (number > 0) { ++count; number &= number - 1; } return count; } private static <T> void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class pair { long a, b; pair(long x, long y) { this.a = x; this.b = y; } // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof pair)) return false; // pair key = (pair) o; // return a == key.a && b == key.b; // } // @Override // public int hashCode() { // int result = a; // result = 31 * result + b; // return result; // } // public int compare(pair p1, pair p2) { // if(p1.a - p2.a > 0) return -1; // if(p1.a - p2.a < 0) return 1; // return 0; // } } static class comparator implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.a - p2.a > 0) return 1; if (p1.a - p2.a < 0) return -1; if (p1.a == p2.a) { if (p1.b > p2.b) return -1; else if (p1.b < p2.b) return 1; } return 0; } } private static long getSum(int[] array) { long sum = 0; for (int value : array) { sum += value; } return sum; } private static boolean isPrime(Long x) { if (x < 2) return false; for (long d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } static int[] reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a; } private static boolean isPrimeInt(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } public static String reverse(String input) { StringBuilder str = new StringBuilder(""); for (int i = input.length() - 1; i >= 0; i--) { str.append(input.charAt(i)); } return str.toString(); } private static int[] getPrimes(int n) { boolean[] used = new boolean[n + 1]; used[0] = used[1] = true; int size = 0; for (int i = 2; i <= n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j <= n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i <= n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } static void sortI(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 void shuffleList(ArrayList<Long> arr) { int n = arr.size(); Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr.get(i); int randomPos = i + rnd.nextInt(n - i); arr.set(i, arr.get(randomPos)); arr.set(randomPos, tmp); } } static void factorize(long n) { int count = 0; while (!(n % 2 > 0)) { n >>= 1; count++; } if (count > 0) { // System.out.println("2" + " " + count); } long i = 0; for (i = 3; i <= (long) Math.sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) { // System.out.println(i + " " + count); } } if (n > 2) { // System.out.println(i + " " + count); } } static void sortL(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public boolean hasNext() { return false; } 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
a7ad1c85c9462f87818b6a8a6b20fc98
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.*; import java.text.DecimalFormat; public final class Solution{ static int inf = Integer.MAX_VALUE; static long mod=1000000000+7; static long fun(ArrayList<Integer> list , ArrayList<Integer> l){ long ans=0L; if(l.size()!=list.size()){ return (long) inf; } // System.out.println(list); // System.out.println(l); for(int i=0;i<list.size();i++){ ans+=Math.abs(list.get(i)-l.get(i)); } return ans; } static void ne(Reader sc , BufferedWriter op) throws Exception{ int n=sc.nextInt(); long[] arr= new long[n]; long ev=0; long od=0; for(int i=0;i<n;i++){ arr[i]=sc.nextLong(); if(arr[i]%2==0){ ev++; }else{ od++; } } if(n==1){ op.write("0\n"); return; } if(ev!=od && n%2==0){ op.write("-1\n"); return; } ArrayList<Integer> l = new ArrayList<>(); for(int i=0;i<n;i++){ arr[i]=arr[i]%2; if(arr[i]==0){ l.add(i); } } ArrayList<Integer> odd= new ArrayList<>(); ArrayList<Integer> even= new ArrayList<>(); for(int i=0;i<n;i++){ if(i%2==0){ even.add(i); }else{ odd.add(i); } } long a1=fun(odd,l); long a2=fun(even,l); long ans=Math.min(a1,a2); if(ans==(long)inf) ans=-1; op.write(ans+"\n"); } public static void main (String[] args) throws Exception { BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); Reader sc = new Reader(); int t=sc.nextInt(); while(t-->0) { ne(sc,op); op.flush(); } } } class pair{ int xx; int yy; pair(int xx, int yy){ this.xx=xx; this.yy=yy; } } class sortY implements Comparator<pair>{ public int compare(pair p1, pair p2){ if(p1.yy> p2.yy){ return 1; }else if(p1.yy==p2.yy){ if(p1.xx>p2.xx){ return 1; }else if(p1.xx < p2.xx){ return -1; } return 0; } return -1; } } class sortX implements Comparator<pair>{ public int compare(pair p1, pair p2){ if(p1.xx> p2.xx){ return 1; }else if(p1.xx==p2.xx){ if(p1.yy>p2.yy){ return 1; }else if(p1.yy < p2.yy){ return -1; } return 0; } return -1; } } class debug{ static void print1d(long [] arr){ System.out.println(); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } static void print1d(int [] arr){ System.out.println(); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } static void print2d(int[][] arr){ System.out.println(); int n=arr.length; int n2=arr[0].length; for(int i=0;i<n;i++){ for(int j=0;j<n2;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } static void print2d(long[][] arr){ System.out.println(); int n=arr.length; int n2=arr[0].length; for(int i=0;i<n;i++){ for(int j=0;j<n2;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } } 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 void ne(Reader sc , BufferedWriter op) throws Exception{ // int n=sc.nextInt(); // n++; // long [] arr= new long[n]; // for(int i=1;i<n;i++){ // arr[i]=sc.nextInt(); // } // long[][] dp= new long[n][n]; // int ind=1; // for(int j=2; j<n;j+=2){ // dp[ind][j]=Math.min(arr[ind],arr[j]); // // System.out.print(arr[ind]+"-"+arr[j]+" "+dp[ind][j]); // ind+=2; // } // ind=1; // int j=4; // while(j<n){ // ind=1; // int y=j; // for(int k=j;k<n;k+=2){ // // System.out.println(ind+" "+k); // dp[ind][k]=dp[ind+2][k]+dp[ind][k-2]+1; // // long val =Math.min(Math.abs(arr[ind+2]-arr[k]),Math.abs(arr[ind]-arr[k-2])); // // // dp[ind][k]+=val; // ind+=2; // } // j+=2; // } // if((n-1)%2==0){ // // System.out.println(n-1); // System.out.println(dp[1][n-1]); // }else{ // System.out.println(dp[1][n-2]); // } // debug.print2d(dp); // }
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
265a72e3683e98c5b304525b847a3bc3
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.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class B{ // author: Tarun Verma static FastScanner sc = new FastScanner(); static int inf = Integer.MAX_VALUE; static long mod = 1000000007; public static void solve() { int n = sc.nextInt(); int arr[] = new int[n]; int even = 0; int odd = 0; for(int i =0;i<n;i++) { arr[i] = sc.nextInt(); if((arr[i] & 1) == 0) even ++; else odd++; } if(abs(even - odd) > 1) { System.out.println(-1); return; } Queue<Integer> eq = new LinkedList<>(); Queue<Integer> oq = new LinkedList<>(); for(int i =0;i<n;i++) { if((arr[i] & 1) == 1) { oq.add(i); } else { eq.add(i); } } long ans = (long)1e18; // System.out.println(eq); // System.out.println(oq); Queue<Integer> eq1 = new LinkedList<>(eq); Queue<Integer> oq1 = new LinkedList<>(oq); ans = min(ans, getAns(oq, eq)); ans = min(ans, getAns(eq1, oq1)); System.out.println(ans/2); } static long getAns(Queue<Integer> a, Queue<Integer> b) { int p = 0; if(a.size() < b.size()) return (long)1e18; long ans = 0; int f = 0; while(!a.isEmpty() || !b.isEmpty()) { int z = (f == 0) ? a.peek() : b.peek(); if(f == 0) a.poll(); else b.poll(); f = f ^ 1; ans += abs(p - z); ++p; } // System.out.println("ans: " + ans); return ans; } public static void main(String[] args) { int t = 1; t = sc.nextInt(); outer: for (int tt = 0; tt < t; tt++) { solve(); } } /* Common Mistakes By Me * make sure to read the bottom part of question * special cases (n=1?) * In Game Theory Check your solution and consider all the solutions * Always initialise value to the declare array in local scope * don't use debugs in interactive problems * Always Reset vis,adj array upto n+1 otherwise can cause TLE */ //////////////////////////////////////////////////////////////////////////////////// ////////////////////DO NOT BELOW BEFORE THIS LINE ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// static boolean isPalindrom(char[] arr, int i, int j) { boolean ok = true; while (i <= j) { if (arr[i] != arr[j]) { ok = false; break; } i++; j--; } return ok; } static int max(int a, int b) { return Math.max(a, b); } static int min(int a, int b) { return Math.min(a, b); } static long max(long a, long b) { return Math.max(a, b); } static long min(long a, long b) { return Math.min(a, b); } static int abs(int a) { return Math.abs(a); } static long abs(long a) { return Math.abs(a); } static void swap(long arr[], int i, int j) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int maxArr(int arr[]) { int maxi = Integer.MIN_VALUE; for (int x : arr) maxi = max(maxi, x); return maxi; } static int minArr(int arr[]) { int mini = Integer.MAX_VALUE; for (int x : arr) mini = min(mini, x); return mini; } static long maxArr(long arr[]) { long maxi = Long.MIN_VALUE; for (long x : arr) maxi = max(maxi, x); return maxi; } static long minArr(long arr[]) { long mini = Long.MAX_VALUE; for (long x : arr) mini = min(mini, x); return mini; } 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 ruffleSort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); int temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } public static int binarySearch(int a[], int target) { int left = 0; int right = a.length - 1; int mid = (left + right) / 2; int i = 0; while (left <= right) { if (a[mid] <= target) { i = mid + 1; left = mid + 1; } else { right = mid - 1; } mid = (left + right) / 2; } return 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[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); arr.add(a); } return arr; } long nextLong() { return Long.parseLong(next()); } } static class pair { int fr, sc; pair(int fr, int sc) { this.fr = fr; this.sc = sc; } } //////////////////////////////////////////////////////////////////////////////////// }
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
4a9d0deeb969e8cea019f0fb71f5d73a
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 BDeltix { public static void main(String[] args) throws java.lang.Exception { // your code goes here //try { // Scanner sc=new Scanner(System.in); FastReader sc = new FastReader(); int t =sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); int[] arr=new int[n]; int[] arr1=new int[n]; int ec=0; int oc=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); arr1[i]=arr[i]; if(arr[i]%2==0){ ec++; } else{ oc++; } } boolean pos=true; if(n%2==0 && ec!=oc){ System.out.println(-1); pos=false; } else if(n%2==1 && Math.abs(ec-oc)>1){ System.out.println(-1); pos=false; } if(!pos)continue; int cnt=0; if(n%2==0){ //even position even value int s=0; for(int i=0;i<n;i++){ if(arr[i]%2==0){ cnt+=Math.abs(i-s); s+=2; } } //even values odd position s=1; int cnt1=0; for(int i=0;i<n;i++){ if(arr[i]%2==0){ cnt1+=Math.abs(i-s); s+=2; } } cnt=Math.min(cnt,cnt1); } else{ if(ec>oc){ //even position even values int s=0; for(int i=0;i<n;i++){ if(arr[i]%2==0){ cnt+=Math.abs(i-s); s+=2; } } } else{ //even position odd values i.e even values odd position int s=1; for(int i=0;i<n;i++){ if(arr[i]%2==0){ cnt+=Math.abs(i-s); s+=2; } } } } System.out.println(cnt); } /* } catch (Exception e) { return; }*/ } public static void swap(int[] arr,int i,int j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } public static class pair{ int ff; int ss; pair(int ff,int ss){ this.ff=ff; this.ss=ss; } } static int BS(int[] arr, int l, int r, int element) { int low = l; int high = r; while (high - low > 1) { int mid = low + (high - low) / 2; if (arr[mid] < element) { low = mid + 1; } else { high = mid; } } if (arr[low] == element) { return low; } else if (arr[high] == element) { return high; } return -1; } static int lower_bound(int[] arr, int l, int r, int element) { int low = l; int high = r; while (high - low > 1) { int mid = low + (high - low) / 2; if (arr[mid] < element) { low = mid + 1; } else { high = mid; } } if (arr[low] >= element) { return low; } else if (arr[high] >= element) { return high; } return -1; } static int upper_bound(int[] arr, int l, int r, int element) { int low = l; int high = r; while (high - low > 1) { int mid = low + (high - low) / 2; if (arr[mid] <= element) { low = mid + 1; } else { high = mid; } } if (arr[low] > element) { return low; } else if (arr[high] > element) { return high; } return -1; } public static long gcd_long(long a,long b){ //a/b,a-> dividant b-> divisor if(b==0)return a; return gcd_long(b, a%b); } public static int gcd_int(int a,int b){ //a/b,a-> dividant b-> divisor if(b==0)return a; return gcd_int(b, a%b); } public static int lcm(int a,int b){ int gcd=gcd_int(a, b); return (a*b)/gcd; } 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()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } Long nextLong() { return Long.parseLong(next()); } } } /* * public static boolean lie(int n,int m,int k){ if(n==1 && m==1 && k==0){ * return true; } if(n<1 || m<1 || k<0){ return false; } boolean * tc=lie(n-1,m,k-m); boolean lc=lie(n,m-1,k-n); if(tc || lc){ return true; } * return false; } */
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
f8aa39f9dd040f34de1abd6706171acf
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 TakeYourPlaces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); long a[] = new long[n]; int oddC = 0; int evenC = 0; for(int i = 0; i < n; i++){ a[i] = sc.nextLong() % 2; if(a[i] == 0){ evenC++; }else{ oddC++; } } if(Math.abs(evenC - oddC) > 1){ System.out.println(-1); }else if(oddC > evenC){ long res = countFunc(a, 1); System.out.println(res); }else if(evenC > oddC){ long res = countFunc(a, 0); System.out.println(res); }else{ long res = Math.min(countFunc(a, 1), countFunc(a, 0)); System.out.println(res); } } } private static long countFunc(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
a0746a2811dd8bf3f4fec30cdd2147d4
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) { Scanner scn = new Scanner(System.in); int test = scn.nextInt(); outer: while (test-- > 0) { int n = scn.nextInt(); int[] arr = new int[n]; long nrOne = 0; for (int i = 0; i < n; i++) { arr[i] = scn.nextInt() % 2; if (arr[i] == 1) { nrOne++; } } if (nrOne > (n + 1) / 2 || nrOne < n / 2) { System.out.println(-1); continue; } long ans = 0; long count1 = 0; long ans1 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 1) { if (count1 * 2 >= n) { ans = (long) 1e18; break; } ans += Math.abs(i - 1l * count1 * 2); count1++; } } long count11 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 1) { if (count11 * 2 + 1 >= n) { ans1 = (long) 1e18; break; } ans1 += Math.abs(i - (1l * count11 * 2 + 1)); count11++; } } long finalAns = 0; if (n % 2 == 0) { finalAns = Math.min(ans, ans1); } else { if (nrOne == n / 2+1) { finalAns = ans; } else { finalAns = ans1; } } System.out.println(finalAns); } } }
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
4cc178ca10d001ed7270d3f4804dc97a
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 check4 { public static int find(int n,int arr[],int a[],List<Integer> zero,List<Integer> one) { int res=0; int zi=0,oi=0; for(int i=0;i<n;i++) { if(arr[i]==a[i]) continue; if(a[i]==0){ while(zero.get(zi)<i) { zi++; } int ind=zero.get(zi); zi++; arr[ind]=1; arr[i]=0; res+=ind-i; } else if(a[i]==1){ while(one.get(oi)<i) { oi++; } int ind=one.get(oi); oi++; arr[ind]=0; arr[i]=1; res+=ind-i; } } return res; } public static void main(String[] args) throws IOException{ Reader sc=new Reader(); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int arr[]=new int[n]; int arr1[]=new int[n]; int arr2[]=new int[n]; int a[]=new int[n]; int b[]=new int[n]; List<Integer> zero = new ArrayList<>(); List<Integer> one = new ArrayList<>(); for(int i=0;i<n;i++){ int t1 = sc.nextInt(); t1%=2; arr[i]=arr1[i]=arr2[i]=t1; a[i]=i%2; b[i]=(i+1)%2; if(t1==0) zero.add(i); else one.add(i); } int n1 = zero.size(); int m1 = one.size(); if(Math.abs(n1-m1)>=2) { out.println(-1); continue; } int ans = Integer.MAX_VALUE; if(n1>=m1) ans = Math.min(ans,find(n,arr1,a,zero,one)); if(m1>=n1) ans = Math.min(ans,find(n,arr2,b,zero,one)); out.println(ans); } out.flush(); } public static long power(long x,long power) { if(power==0) return 1; long ans1 = power(x,power/2); ans1=ans1*ans1; if(power%2==0) return ans1; return x*ans1; } // (a*a_inverse) = 1(mod m) // finding a_inverse public static long modInverse(long a,long m) { // works only when m is prime long g=gcd(a,m); if(g==1) return power(a,m-2,m); else return -1; } // (x^power)mod(m) public static long power(long x,long power,long m) { if(power==0) return 1; long p = power(x,power/2,m)%m; p = (p*p)%m; if(power%2==0) return p; return (x*p)%m; } public static long gcd(long small,long large) { if(small==0) return large; return gcd(large % small,small); } public static boolean isprime(long no) { if(no<=1) return false; if(no<=3) return true; if(no%2==0 || no%3==0) return false; // 6k+1 6k+5 can be prime for(long i=5;i*i<=no;i+=6) { if(no%(i)==0 || no%(i+2)==0) return false; } return true; } // prime no smaller than or equal to n public static boolean[] prime_nos_till_no(int no) { boolean prime[]=new boolean[no+1]; // prime[i]== true means prime // prime[i]== false means not a prime // initialize prime array as true Arrays.fill(prime,true); prime[0]=false; for(int i=2;i*i<=no;i++) { if(prime[i]==true) { for(int j=i*i;j<=no;j+=i) { prime[j]=false; } } } return prime; } public static void shufflearray(long arr[]) { int n=arr.length; Random rand=new Random(); for(int i=0;i<n;i++) { long temp=arr[i]; int randomPos=i+rand.nextInt(n-i); arr[i]=arr[randomPos]; arr[randomPos]=temp; } } // Arrays.sort(arr, new Comparator<pair>() { // //@Override // public int compare(pair o1, pair o2) { // long l1=o1.a-o2.a; // if(l1<0L) return -1; // if(l1==0) return 0; // return 1; // } // }); 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 nextLine() 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() throws IOException{ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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(); } } }
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
636e7543027329efad6a42f36ddb84a5
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.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.*; public class B { private static final FastReader fs = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); private static long m = 1_000_000_009; private static long p = 31; private static long mod = 1_000_000_007; private static long oo = 1_000_000_000_000_000_009l; private static long minSwaps(int[] res, int start) { long ans = 0; TreeSet<Integer> one = new TreeSet<>(), zero = new TreeSet<>(); for(int i = 0; i < res.length; i++) if(res[i] == 0) zero.add(i); else one.add(i); for(int i = 0; i < res.length; i++) { if(res[i] != start) { if(start == 1) { if(one.higher(i) == null) return oo; int next = one.higher(i); one.remove(next); zero.add(next); res[i] = 1; res[next] = 0; ans += (long)abs(next-i); } else { if(zero.higher(i) == null) return oo; int next = zero.higher(i); zero.remove(next); one.add(next); res[i] = 0; res[next] = 1; ans += (long)abs(next - i); } } start = 1 - start; } return ans; } private static void solve() { int n = fs.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = fs.nextInt()%2; long ans = min(minSwaps(a.clone(), 0), minSwaps(a.clone(), 1)); if(ans == oo) out.println(-1); else { out.println(ans); } } public static void main(String[] args) { Thread t = new Thread(null, null, "", 1 << 28) { public void run() { int test_case = 1; test_case = fs.nextInt(); for (int cs = 1; cs <= test_case; cs++) solve(); out.close(); } }; t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private 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[] readintarray(int n) { int res[] = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] readlongarray(int n) { long res[] = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } } private static int max(int... arg) { int length = arg.length; if(length == 0) throw null; int maxVal = arg[0]; for(int i = 1; i < length; i++) maxVal = Math.max(maxVal, arg[i]); return maxVal; } private static int min(int... arg) { int length = arg.length; if(length == 0) throw null; int maxVal = arg[0]; for(int i = 1; i < length; i++) maxVal = Math.min(maxVal, arg[i]); return maxVal; } private static long max(long... arg) { int length = arg.length; if(length == 0) throw null; long maxVal = arg[0]; for(int i = 1; i < length; i++) maxVal = Math.max(maxVal, arg[i]); return maxVal; } private static long min(long... arg) { int length = arg.length; if(length == 0) throw null; long maxVal = arg[0]; for(int i = 1; i < length; i++) maxVal = Math.min(maxVal, arg[i]); return maxVal; } private static int abs(int a) { return a >= 0 ? a : -a; } private static int abs(int a, int b) { return a-b >= 0 ? a-b : b-a; } private static long abs(long a) { return a >= 0 ? a : -a; } private static long abs(long a, long b) { return a-b >= 0 ? a-b : b-a; } private static int power(int base, int exponent) { int res = 1; while(exponent > 0) { if((exponent & 1) != 0) res *= base; exponent >>= 1; base *= base; } return res; } private static long power(long base, long exponent) { long res = 1; while(exponent > 0) { if((exponent & 1) != 0) res *= base; exponent >>= 1; base *= base; } return res; } private static long mPower(long base, long exponent) throws Exception { long res = 1; base %= mod; while(exponent > 0) { if((exponent & 1) != 0) res = mul(res, base); exponent >>= 1; base = mul(base, base); } return res; } private static long mul(long a, long b) { return a*b % mod; } private static long add(long a, long b) { return (a+b) % mod; } private static long sub(long a, long b) { long res = (a - b) % mod; if(res < 0) res += mod; return 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 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
23f6cf6f9488628caf257db2a2ff7605
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 IncString { public static int minFunc(int arr[], int n, boolean flag) { int strt1 = 0, strt2 = 0, redpos = 0, cnt = 0; int i = 0; boolean ans = true; while(i<n) { if(arr[i] == -1) { i++; redpos--; continue; } if(flag) { if(arr[i]%2 != 0) { boolean flag1 = false; for(int j=Math.max(strt1, i);j<n;j++) { if(arr[j] != -1) { if(arr[j]%2 == 0) { cnt += Math.abs((j-i)) - redpos; redpos++; arr[j] = -1; flag1 = true; strt1 = j; break; } } } if(!flag1) { ans = false; break; } } else i++; flag = false; } else { if(arr[i]%2 == 0) { boolean flag1 = false; for(int j=Math.max(strt2, i);j<n;j++) { if(arr[j] != -1) { if(arr[j]%2 != 0) { cnt += Math.abs((j-i)) - redpos; redpos++; arr[j] = -1; flag1 = true; strt2 = j; break; } } } if(!flag1) { ans = false; break; } } else i++; flag = true; } } if(!ans) return Integer.MAX_VALUE; return cnt; } public static void main(String[] args) { int t; Scanner sc = new Scanner(System.in); t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int arr[] = new int[n]; int temp[] = new int[n]; int cnteven = 0, cntodd = 0; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); temp[i] = arr[i]; if(arr[i]%2 == 0) cnteven += 1; else cntodd += 1; } if(Math.abs(cnteven - cntodd) <= 1) { int min1 = minFunc(arr, n, false); int min2 = minFunc(temp, n, true); System.out.println(Math.min(min1, min2)); } 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 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
7b5919c691980525b2ed14efb73e0916
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.codeforces.Practise; import java.io.*; import java.util.ArrayList; import java.util.List; public class TakeYourPlaces { private static long compareAndGet(int[] arr,int[] compare) { List<Integer> even=new ArrayList<>(); List<Integer> odd=new ArrayList<>(); long res=0; for (int i = 0; i < arr.length; i++) { if(arr[i]!=compare[i]){ if(arr[i]==0){ even.add(i); } else { odd.add(i); } } } int i=0; int j=0; while (i<even.size() && j<odd.size()){ res+=Math.abs(even.get(i)-odd.get(j)); i++; j++; } return res; } public static void main(String[] args)throws IOException { Reader scan=new Reader(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t=scan.nextInt(); while (t-->0) { int n=scan.nextInt(); int[] arr=new int[n]; int even=0; int odd=0; for (int i = 0; i < n; i++) { int val=scan.nextInt(); arr[i]=val%2; if(arr[i] == 0) even++; else odd++; } int diff=Math.abs(even-odd); long ans=-1; if(diff==0){ int[] startwithodd=new int[n]; int[] startwitheven=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwithodd[i]=1; startwitheven[i]=0; flag=false; } else { startwithodd[i]=0; startwitheven[i]=1; flag=true; } } long ans1=compareAndGet(arr,startwithodd); long ans2=compareAndGet(arr,startwitheven); ans=Math.min(ans1,ans2); } else if(diff==1 && even>odd) { int[] startwitheven=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwitheven[i]=0; flag=false; } else { startwitheven[i]=1; flag=true; } } ans=compareAndGet(arr,startwitheven); } else if(diff==1 && odd>even) { int[] startwithodd=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwithodd[i]=1; flag=false; } else { startwithodd[i]=0; flag=true; } } ans=compareAndGet(arr,startwithodd); } bw.write(ans+""); bw.newLine(); bw.flush(); } } //FAST READER static class Reader { 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 Reader() { in = new BufferedInputStream(System.in, BS); } public Reader(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+(cur < 0 ? -1*nextLong()/num : 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(); } } }
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
802ac69136f48bed3702ddb756578a15
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.PrintStream; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class A2 { void solve() { int n = cint(); long[] a = carr_long(n); // int n = 100_000; // long[] a = new long[n]; // for (int i = 0; i < n / 2; i++) { // a[i] = i * 2; // } // for (int i = n / 2; i < n; i++) { // a[i] = (i - n / 2) * 2 + 1; // } // //shuffle(a); int c0 = 0, c1 = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { c0++; } else { c1++; } } if (Math.abs(c1 - c0) > 1) { cout(-1); return; } if (c0 > c1) { cout(count(a, true)); } else if (c1 > c0) { cout(count(a, false)); } else { long[] b = Arrays.copyOf(a, a.length); cout(Math.min(count(a, true), count(b, false))); } } long count(long[] a, boolean oddFirst) { // long[] b = new long[a.length]; long result = 0; for (int i = 0, j = 0, k = 0; k < a.length; k++) { boolean shouldBeOddValue = (k % 2 == 0) ^ !oddFirst; if (shouldBeOddValue) { while (a[i] % 2 != 0) i++; // b[k] = a[i]; result += Math.abs(k-i); i++; } else { while (a[j] % 2 == 0) j++; // b[k] = a[j]; result += Math.abs(k-j); j++; } } return result/2; // // long result = 0; // int jodd = 0, jeven = 0; // for (int i = 0; i < a.length - 1; i++) { // boolean shouldBeOddValue = (i % 2 == 0) ^ !oddFirst; // // if (shouldBeOddValue ^ (a[i] % 2 == 0)) { // int j; // if (shouldBeOddValue) { // j = jodd == 0 ? i + 1 : jodd; // } else { // j = jeven == 0 ? i + 1 : jeven; // } // for (; j < a.length; j++) { // if (!shouldBeOddValue ^ (a[j] % 2 == 0)) { // break; // } // } // swap(a, i, j); // result += j-i; // if (shouldBeOddValue) { // jodd = j; // } else { // jeven = j; // } //// for (; i < j; j--) { //// swap(a, j, j - 1); //// result++; //// } // } // } // return result; } static void shuffle(long[] a) { Random rnd = new Random(); for (int i = a.length; i > 1; i--) { swap(a, i - 1, rnd.nextInt(i)); } } static void swap(long[] x, int a, int b) { long tmp = x[a]; x[a] = x[b]; x[b] = tmp; } public static void main(String... args) { int t = in.nextInt(); in.nextLine(); for (int test = 0; test < t; test++) { new A2().solve(); } } static final Scanner in = new Scanner(System.in); static final PrintStream out = System.out; static int cint() { return in.nextInt(); } static long clong() { return in.nextLong(); } static String cstr() { return in.nextLine(); } static int[] carr_int(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } static long[] carr_long(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); } return a; } static void cout(int... a) { for (int i = 0; i < a.length; i++) { if (i != 0) { out.print(' '); } out.print(a[i]); } out.println(); } static void cout(long... a) { for (int i = 0; i < a.length; i++) { if (i != 0) { out.print(' '); } out.print(a[i]); } out.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 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
2482c3771dd6eca8354a165f2d08c145
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) { Scanner sn = new Scanner(System.in); int t = sn.nextInt(); while(t-- >0) { int n=sn.nextInt(); int[] a= new int[n]; int[] b= new int[n]; int cnt=0; for(int i=0;i<n;i++) { a[i]=sn.nextInt(); if(a[i]%2==0) cnt++; b[i]=a[i]; } int v=n-2*cnt; if(v<0) v=-v; if(v>1) { System.out.print(-1+"\n"); continue; } int p2=0; int ans=0; int par=0; for(int i=0;i<n;i++) { if(a[i]%2==par) { if(p2==i) p2++; par=1-par; continue; } while(p2<n && a[i]%2==a[p2]%2) { p2++; } if(p2==n) { ans=-1; break; } ans=ans+p2-i; int tmp=a[p2]; a[p2]=a[i]; a[i]=tmp; par=1-par; } int cur=0; p2=0; par=1; for(int i=0;i<n;i++) { if(b[i]%2==par) { if(p2==i) p2++; par=1-par; continue; } while(p2<n && b[i]%2==b[p2]%2) { p2++; } if(p2==n) { cur=-1; break; } cur=cur+p2-i; int tmp=b[p2]; b[p2]=b[i]; b[i]=tmp; par=1-par; } if(ans==-1) ans=cur+1; if(cur==-1) cur=ans+1; ans=min(ans,cur); System.out.print(ans+"\n"); } } private static int min(int x, int y) { if(x<=y) return x; return 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
8ebbed56a36037f1a2e6a0f41eaf0eb8
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_Take_Your_Places_ { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t>0) { int n=Integer.parseInt(br.readLine()); String []s=br.readLine().split(" "); int ar[]=new int[n]; for(int i=0;i<s.length;i++) ar[i]=Integer.parseInt(s[i]); int odd=0; int even=0; for(int i=0;i<s.length;i++) if(ar[i]%2==0) even++; else odd++; int diff=Math.abs(even-odd); if(diff>1) System.out.println("-1"); else{ String st=""; if(even >odd){ ArrayList<Integer> al1=new ArrayList<Integer>(); ArrayList<Integer> al2=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(i%2==0 && ar[i]%2==1) al1.add(i); if(i%2!=0 && ar[i]%2==0)al2.add(i); } int val=0; for(int i=0;i<al1.size();i++){ val+=Math.abs(al1.get(i)-al2.get(i)); } System.out.println(val); } else if(even <odd){ ArrayList<Integer> al1=new ArrayList<Integer>(); ArrayList<Integer> al2=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(i%2==0 && ar[i]%2==0) al1.add(i); if(i%2!=0 && ar[i]%2==1)al2.add(i); } int val=0; for(int i=0;i<al1.size();i++){ val+=Math.abs(al1.get(i)-al2.get(i)); } System.out.println(val); } else{ ArrayList<Integer> al1=new ArrayList<Integer>(); ArrayList<Integer> al2=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(i%2==0 && ar[i]%2==1) al1.add(i); if(i%2!=0 && ar[i]%2==0)al2.add(i); } int val1=0; for(int i=0;i<al1.size();i++){ val1+=Math.abs(al1.get(i)-al2.get(i)); } ArrayList<Integer> al3=new ArrayList<Integer>(); ArrayList<Integer> al4=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(i%2==0 && ar[i]%2==0) al3.add(i); if(i%2!=0 && ar[i]%2==1)al4.add(i); } int val2=0; for(int i=0;i<al3.size();i++){ val2+=Math.abs(al3.get(i)-al4.get(i)); } System.out.println(Math.min(val1,val2)); } } t--; } }}
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
417d84bae4aeda6f5a128456c47ab3ea
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.StringTokenizer; import java.util.*; import java.io.*; public class Main { public static void main(String args[])throws Exception{ Input sc=new Input(); StringBuilder sb=new StringBuilder(); int t=sc.readInt(); for(int f=0;f<t;f++){ int n=sc.readInt(); int a[]=sc.readArray(); int c1,c0; c1=c0=0; // System.out.println("-----------------"); for(int i=0;i<n;i++){ if(a[i]%2==0) c0++; else c1++; a[i]=a[i]%2; // System.out.print(a[i]+" "); } //System.out.println(); ArrayList<Integer> lst1=new ArrayList<>(); ArrayList<Integer> lst2=new ArrayList<>(); for(int i=0;i<n;i++){ if(i%2==0 && a[i]!=0){ lst1.add(i); } if(i%2==1 && a[i]!=0){ lst2.add(i); } } //System.out.println(lst1); /// System.out.println(lst2); if(Math.abs(c1-c0)<=1){ int count=0; int v=0; int j=0; if(n%2==0){ for(int i=0;i<n;i++){ if(a[i]==0 && i%2!=0){ if(lst1.size()>0){ count+=Math.abs(i-lst1.get(j)); j++;} } } j=0; for(int i=0;i<n;i++){ if(a[i]==0 && i%2==0){ if(lst2.size()>0){ v+=Math.abs(i-lst2.get(j)); j++;} } } sb.append(Math.min(v,count)+"\n"); }else{ if(c1<c0){ for(int i=0;i<n;i++){ if(a[i]==0 && i%2!=0){ if(lst1.size()>0){ count+=Math.abs(i-lst1.get(j)); j++;} } } sb.append(count+"\n"); }else{ for(int i=0;i<n;i++){ if(a[i]==0 && i%2==0){ if(lst2.size()>0){ v+=Math.abs(i-lst2.get(j)); j++;} } } sb.append(v+"\n"); } } }else sb.append("-1\n"); } System.out.print(sb); } } /* 1 0 */ class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } 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
a80dd6f2da81dfbaa07050b1a90973b3
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.BigInteger; import java.util.InputMismatchException; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static long INF = (long)1e18; static int MAXN = (int)1e5 + 5; static int MOD = (int)1e9 + 7; static int q, t, n, m, k; static double pi = Math.PI; void solve() throws IOException { t = in.nextInt(); while (t --> 0) { n = in.nextInt(); int[] arr = new int[n]; int total = 0; for (int i = 0; i < n; i++) { arr[i] = in.nextInt()%2; if (arr[i] == 1) total++; else total--; } if (total < -1 || total > 1) { out.println(-1); continue; } long ans = cnt(arr); for (int i = 0; i < n; i++) arr[i] = 1-arr[i]; ans = Math.min(ans, cnt(arr)); out.println(ans); } } static long cnt(int[] arr) { long res = 0; for (int i = 0; i < n; i++) res += arr[i]; if (n-res < res) return 10000000000000000L; res = 0; Bit pre = new Bit(n+1); ArrayDeque<Integer> one = new ArrayDeque<>(), zero = new ArrayDeque<>(); for (int i = 0; i < n; i++) { if (arr[i] == 0) zero.addLast(i); else one.addLast(i); } for (int i = 0; i < n; i++) { if (i%2 == 0) { int pos = zero.removeFirst(); int tmp = pos+1; pos = pos+(int)pre.query(pos+1, n+1); if (pos >= i) res += pos-i; pre.update(tmp, 1); } else { int pos = one.removeFirst(); int tmp = pos+1; pos = pos+(int)pre.query(pos+1, n+1); if (pos >= i) res += pos-i; pre.update(tmp, 1); } } return res; } static class Bit { long[] bit; int n; Bit(int n) { this.n = n; bit = new long[n+1]; } public void update(int pos, long val) { if (pos <= 0) return; for (int i = pos; i <= n; i += i&-i) bit[i] += val; } public long get(int pos) { long sum = 0; for (int i = pos; i > 0; i -= i&-i) sum += bit[i]; return sum; } public long query(int l, int r) { return get(r) - get(l-1); } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 int nextInt() { 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.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 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
ada1f6004c170a1d41d67f42fe431dba
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 MyClass { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ int n=Integer.parseInt(br.readLine()); String str[]=br.readLine().split(" "); String s=""; int arr[]=new int[n]; int sum=0; for(int i=0;i<n;i++) arr[i]=Integer.parseInt(str[i])%2; for(int i:arr) sum+=i; if(!(Math.abs(2*sum-n)<=1)){ System.out.println("-1"); continue; } if(n==1){System.out.println("0");continue;} if(2*sum==n){ List<Integer> odd=new ArrayList<Integer>(); List<Integer> even=new ArrayList<Integer>(); int a=0,b=0; for(int i=0;i<n;i+=2){ if(arr[i]!=1) odd.add(i); } for(int i=1;i<n;i+=2){ if(arr[i]!=0) even.add(i); } Collections.sort(odd); Collections.sort(even); for(int i=0;i<odd.size();i++){ a+=Math.abs(odd.get(i)-even.get(i)); } odd.clear(); even.clear(); for(int i=0;i<n;i+=2){ if(arr[i]!=0) even.add(i); } for(int i=1;i<n;i+=2){ if(arr[i]!=1) odd.add(i); } Collections.sort(odd); Collections.sort(even); for(int i=0;i<odd.size();i++){ b+=Math.abs(odd.get(i)-even.get(i)); } System.out.println(Math.min(a,b)); continue; } if(2*sum<n){ List<Integer> odd=new ArrayList<Integer>(); List<Integer> even=new ArrayList<Integer>(); int b=0; for(int i=0;i<n;i+=2){ if(arr[i]!=0) even.add(i); } for(int i=1;i<n;i+=2){ if(arr[i]!=1) odd.add(i); } Collections.sort(odd); Collections.sort(even); for(int i=0;i<odd.size();i++){ b+=Math.abs(odd.get(i)-even.get(i)); } System.out.println(b); continue; } else{ List<Integer> odd=new ArrayList<Integer>(); List<Integer> even=new ArrayList<Integer>(); int b=0; for(int i=0;i<n;i+=2){ if(arr[i]!=1) odd.add(i); } for(int i=1;i<n;i+=2){ if(arr[i]!=0) even.add(i); } Collections.sort(odd); Collections.sort(even); for(int i=0;i<odd.size();i++){ b+=Math.abs(odd.get(i)-even.get(i)); } System.out.println(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 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
eb977148f60d6e8f2d33dafee5035eed
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; import java.io.FileReader; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static BufferedReader br; static PrintWriter out; static StringTokenizer st; public static int min(int a, int b) { if (a < b) return a; return b; } public static int find(int a[], int x) { int sum = 0; int n = a.length; ArrayList<Integer> odd = new ArrayList<>(); ArrayList<Integer> even = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] != x && x == 1) odd.add(i); else if (a[i] != x && x == 0) even.add(i); x ^= 1; } Collections.sort(odd); Collections.sort(even); for (int i = 0; i < odd.size(); i++) { sum += Math.abs(odd.get(i) - even.get(i)); } return sum; } public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); int t = 1; t = readInt(); while (t-- > 0) { int n = readInt(); int a[] = new int[n]; int even = 0, odd = 0; for (int i = 0; i < n; i++) { a[i] = readInt(); } for (int i = 0; i < n; i++) { a[i] &= 1; if (a[i] == 0) even++; else odd++; } if (Math.abs(even - odd) > 1) out.println(-1); else if (even == odd) { int ans1 = find(a, 0); int ans2 = find(a, 1); out.println(min(ans1, ans2)); } else if (even > odd) { out.println(find(a, 0)); } else { out.println(find(a, 1)); } } out.close(); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); 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 readLine() throws IOException { return br.readLine().trim(); } }
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
3f88ff0c32db832a54c4e13e6d08a070
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 A { public static void main(String[] args) { // TODO Auto-generated method stub //System.out.println("Hello"); Scanner obj = new Scanner(System.in); int t = obj.nextInt(); while(t-->0) { int n = obj.nextInt(); int [] a = new int[n]; int even = 0,odd=0; int eveni=0,oddi=0; for(int i = 0;i<n;i++) { a[i] = obj.nextInt(); if(a[i]%2==0) { even++; } else odd++; //System.out.println(a[0]+" "+a[1]+" "+a[2]); } long ans=0,ans1=0,ans2=0; if((n%2==0&&Math.abs(even-odd)!=0)||(n%2!=0&&Math.abs(even-odd)!=1)) { System.out.println(-1); continue; } else { int e=0; int m=1; for(int i=0;i<n;i++) { if(a[i]%2==0) { ans1=ans1+Math.abs(i-e); e=e+2; ans2=ans2+Math.abs(i-m); m=m+2; } } if(n%2==0) ans= Math.min(ans1,ans2); else { if(even<odd) ans=ans2; else ans=ans1; } } 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 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
0f1d2d959258d60856f7cf2d6ea45cf3
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) { FastScanner sc=new FastScanner(); int t=sc.nextInt(); PrintWriter pw=new PrintWriter(System.out); while(t-->0) { int n=sc.nextInt(); int[] a=new int[n]; int nodd=0; int neven=0; ArrayList<Integer> evenIdx=new ArrayList<>(); ArrayList<Integer> oddIdx=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]%2==0) { neven++; evenIdx.add(i); } else { oddIdx.add(i); nodd++; } } long ans=0; if(n%2==0) { if(neven!=nodd) { ans=-1; } else { int j=1; long temp=0; for(int z:oddIdx) { temp+=(Math.abs(z-j)); j+=2; } j=1; for(int z:evenIdx) { ans+=Math.abs(z-j); j+=2; } ans=Math.min(ans, temp); } } else { if(Math.abs(neven-nodd)!=1) { ans=-1; } else { if(neven>nodd) { int j=1; for(int z:oddIdx) { ans+=(Math.abs(z-j)); j+=2; } } else { int j=1; for(int z:evenIdx) { ans+=(Math.abs(z-j)); j+=2; } } } } pw.println(ans); } pw.flush(); } 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()); } } }
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
cacf795f7901c484dc361053c71ff918
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.*; import java.util.Map.Entry; public class codeforces { static int mod = 1000000007; public static void main(String[] args) { FastReader sc = new FastReader(); try { StringBuilder ss = new StringBuilder(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0 ; i<n;i++) { a[i] = sc.nextInt(); } ArrayList<Integer> al = new ArrayList<>(); ArrayList<Integer> bl = new ArrayList<>(); for(int i = 0 ; i <n;i++) { if(a[i] %2 == 0) { al.add(i); } else { bl.add(i); } } boolean flag = true; boolean flag1 = true; long ans = 0 ; long ans1 = 0; int j = 0 ; int k = 0; for(int i = 0; i < n;i++) { if(i%2 == 0) { if(j< bl.size()) { ans+= Math.abs(i - bl.get(j)); j++; } else { flag = false; break; } } else { if(k<al.size()) { ans+= Math.abs(i - al.get(k)); k++; } else { flag = false; break; } } } j = 0 ; k = 0; for(int i = 0; i < n;i++) { // System.out.println(ans1); if(i%2 == 0) { if(k<al.size()) { ans1+= Math.abs(i - al.get(k)); k++; } else { flag1 = false; break; } } else { if(j< bl.size()) { ans1+= Math.abs(i - bl.get(j)); j++; } else { flag1 = false; break; } } } long min = Long.MAX_VALUE; if(flag) { min = Math.min(min,ans/2); } if(flag1) { min = Math.min(min, ans1/2); } if(min == Long.MAX_VALUE) { min = -1; } ss.append(min +"\n"); } System.out.println(ss); } catch(Exception e) { System.out.println(e.getMessage()); } } static void sort(int a[]) { Arrays.parallelSort(a); } static long pow(long a, long b) { long ans = 1; long temp = a; while(b>0) { if((b&1) == 1) { ans*=temp; } temp = temp*temp; b = b>>1; } return ans; } static long ncr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static long fact(long n) { long res = 1; for (int i = 2; i <= n; i++) { res = (res * i); } return res; } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b , a%b); } static ArrayList<Integer> factor(long n) { ArrayList<Integer> al = new ArrayList<>(); for(int i = 1 ; i*i<=n;i++) { if(n%i == 0) { if(n/i == i) { al.add(i); } else { al.add(i); al.add((int) (n/i)); } } } return al; } static class Pair implements Comparable<Pair>{ long a; int b ; Pair(long a, int b){ this.a = a; this.b = b; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return (int)(this.a - o.a); } } static ArrayList<Integer> sieve(int n) { boolean a[] = new boolean[n+1]; Arrays.fill(a, false); for(int i = 2 ; i*i <=n ; i++) { if(!a[i]) { for(int j = 2*i ; j<=n ; j+=i) { a[j] = true; } } } ArrayList<Integer> al = new ArrayList<>(); for(int i = 2 ; i <=n;i++) { if(!a[i]) { al.add(i); } } return al; } static ArrayList<Long> pf(long n) { ArrayList<Long> al = new ArrayList<>(); while(n%2 == 0) { al.add(2l); n = n/2; } for(long i = 3 ; i*i<=n ; i+=2) { while(n%i == 0) { al.add(i); n = n/i; } } if(n>2) { al.add( n); } return al; } 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 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
0891012559296f546c05dffafb0d15a5
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.codeforces.Practise; import java.io.*; import java.util.ArrayList; import java.util.List; public class TakeYourPlaces { //If you stuck for 30min don't waste time anymore, have a look at to the hint or solution //when you get WA and you are okk with your solution then try out some edge cases means on which test case your code fails // because sometimes your writing code mistake // Consistency will always give you great Result // Don't Confuse Always make things simple // Don't afraid after seeing the problem instead dive deep into it to get better understanding //Experience is the name of the game // You won't fail until you stop trying....... // you can solve one problem by many approaches. when you stuck you are going to learn something new okk // Everything is easy. you feel its hard because of you don't know, and you not understand it very well. //// How to Improve Your problem-solving skill ??( By practise ). ***simple /// ==>> Solve problems slightly above of your level (to know some logic and how to approach cp problems) // Otherwise You will stay as it is okk. Learn from other code as well. ///////////////////////////////////////////////////////////////////////// ________________________________________________________ /// How to Solve Problem in CP ? (you need to come up with brainstorm(Learning)) ( if you feel problem is hard then your approach is wrong ) // ==>> Step01 :- Understanding problem statement clearly. Then Only Move Forward (Because Everything is mentioned in problem statement). // Step02 :- Think a lot about Solution. if you are confident that your solution might be correct Then only Move Forward // Step03 :- First think of brute force then move to optimal approach // Step04 :- Finally Code ( there is no any sense to code. if you not follow about steps okk) /////////////////////////////////////////////////////////////////////////// // private static long getAns(int[] arr,boolean flag) { // int[] temparr = arr.clone(); // int i = 0; // int n = temparr.length; // long res = 0; // boolean flag1 = flag; // while (i < n) { // int j = i + 1; // if (flag1) { // if (temparr[i] % 2 != 0) { // i++; // } else { // while (j < n) { // if (temparr[j] % 2 != 0) { // res += j - i; // //update // int temp = temparr[j]; // for (int k = j; k > i; k--) { // temparr[k] = temparr[k - 1]; // } // temparr[i] = temp; // i++; // break; // } // j++; // } // } // flag1 = false; // } else { // if (temparr[i] % 2 == 0) { // i++; // } else { // while (j < n) { // if (temparr[j] % 2 == 0) { // res += j - i; // //update // int temp = temparr[j]; // for (int k = j; k > i; k--) { // temparr[k] = temparr[k - 1]; // } // temparr[i] = temp; // i++; // break; // } // j++; // } // } // flag1 = true; // } // } // return res; // } // private static long method1(int n,int[] arr, Reader scan) // { // int odd=0; // int even=0; // for (int i = 0; i < n; i++) { // arr[i]=scan.nextInt(); // if(arr[i]%2==0){ // even++; // } // else{ // odd++; // } // } // int diff=Math.abs(even-odd); // long ans=-1; // if(diff==0){ // //start with odd // long ans1=getAns(arr,true); // //start with even // long ans2=getAns(arr,false); // ans=Math.min(ans1,ans2); // } // else if(diff==1 && odd>even){ // //start with odd // ans=getAns(arr,true); // } // else if(diff==1 && even>odd){ // //start with even // ans=getAns(arr,false); // } // return ans; // } private static long compareAndGet(int[] arr,int[] compare) { List<Integer> even=new ArrayList<>(); List<Integer> odd=new ArrayList<>(); long res=0; for (int i = 0; i < arr.length; i++) { if(arr[i]!=compare[i]){ if(arr[i]==0){ even.add(i); } else { odd.add(i); } } } int i=0; int j=0; while (i<even.size() && j<odd.size()){ res+=Math.abs(even.get(i)-odd.get(j)); i++; j++; } return res; } public static void main(String[] args)throws IOException { Reader scan=new Reader(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t=scan.nextInt(); while (t-->0) { int n=scan.nextInt(); int[] arr=new int[n]; int even=0; int odd=0; for (int i = 0; i < n; i++) { int val=scan.nextInt(); arr[i]=val%2; if(arr[i] == 0) even++; else odd++; } int diff=Math.abs(even-odd); long ans=-1; if(diff==0){ int[] startwithodd=new int[n]; int[] startwitheven=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwithodd[i]=1; startwitheven[i]=0; flag=false; } else { startwithodd[i]=0; startwitheven[i]=1; flag=true; } } long ans1=compareAndGet(arr,startwithodd); long ans2=compareAndGet(arr,startwitheven); ans=Math.min(ans1,ans2); } else if(diff==1 && even>odd) { int[] startwitheven=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwitheven[i]=0; flag=false; } else { startwitheven[i]=1; flag=true; } } ans=compareAndGet(arr,startwitheven); } else if(diff==1 && odd>even) { int[] startwithodd=new int[n]; boolean flag=true; for (int i = 0; i < n; i++) { if(flag){ startwithodd[i]=1; flag=false; } else { startwithodd[i]=0; flag=true; } } ans=compareAndGet(arr,startwithodd); } bw.write(ans+""); bw.newLine(); bw.flush(); } } //FAST READER static class Reader { 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 Reader() { in = new BufferedInputStream(System.in, BS); } public Reader(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+(cur < 0 ? -1*nextLong()/num : 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(); } } }
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
0362401dd34d8a86da9c151a5d01c64c
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 ComdeFormces { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int t=sc.nextInt(); while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; ArrayList<Integer> ev=new ArrayList<>(); ArrayList<Integer> od=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]%2==0) { ev.add(i); } else od.add(i); } // Collections.sort(ev); // Collections.sort(od); if((n%2==0 && ev.size()-od.size()==0) || (n%2!=0 && Math.abs(ev.size()-od.size())==1)){ long min=Long.MAX_VALUE; if(n%2==0) { long cal=0,cal2=0; int p1=0,p2=0,p3=0,p4=0; for(int i=0;i<n;i++) { if(i%2==0) { cal+=Math.abs(i-ev.get(p1)); cal2+=Math.abs(i-od.get(p3)); p3++; p1++; } else { cal+=Math.abs(i-od.get(p2)); cal2+=Math.abs(i-ev.get(p4)); p4++; p2++; } } min=Math.min(cal2, cal); } else { ArrayList<Integer> ar=ev.size()>od.size()?ev:od; ArrayList<Integer> br=ev.size()<od.size()?ev:od; long cal=0; int p1=0,p2=0; for(int i=0;i<n;i++) { if(i%2==0) { cal+=Math.abs(i-ar.get(p1)); p1++; } else { cal+=Math.abs(i-br.get(p2)); p2++; } } min=cal; } log.write((min/2)+""); } else log.write("-1"); log.write("\n"); log.flush(); } } static long slv(int a[],int b[],long dp[][],int end,int k,int i) { if(i<1 ) { if(k==0) { return (end-a[0])*b[0]; } else return Integer.MAX_VALUE; } if(k<0)return Integer.MAX_VALUE; if(k==0) { return (end-a[0])*b[0]; } if(dp[i][k]!=0)return dp[i][k]; long ans1=slv(a,b,dp,a[i],k-1,i-1); long ans2=slv(a,b,dp,end,k,i-1); long val=(end-a[i])*b[i]; return dp[i][k]=Math.min(val+ans1,ans2); } //debug public static <E> void p(E[][] a,String s) { System.out.println(s); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } public static <E> void p(E a,String s){ System.out.println(s+"="+a); } public static <E> void p(E a[],String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static <E> void p(ArrayList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(LinkedList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Stack<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Queue<E> a,String s){ System.out.println(s+"="+a); } //utils static ArrayList<Integer> divisors(int n){ ArrayList<Integer> ar=new ArrayList<>(); for (int i=2; i<=Math.sqrt(n); i++){ if (n%i == 0){ if (n/i == i) { ar.add(i); } else { ar.add(i); ar.add(n/i); } } } return ar; } static int primeDivisor(int n){ ArrayList<Integer> ar=new ArrayList<>(); int cnt=0; boolean pr=false; while(n%2==0) { pr=true; n/=2; } if(pr)ar.add(2); for(int i=3;i*i<=n;i+=2) { pr=false; while(n%i==0) { n/=i; pr=true; } if(pr)ar.add(i); } if(n>2) ar.add(n); return ar.size(); } static String rev(String s) { char temp[]=s.toCharArray(); for(int i=0;i<temp.length/2;i++) { char tp=temp[i]; temp[i]=temp[temp.length-1-i]; temp[temp.length-1-i]=tp; } return String.valueOf(temp); } static int bs(ArrayList<pair> arr,int el) { int start=0; int end=arr.size()-1; while(start<=end) { int mid=start+(end-start)/2; if(arr.get(mid).a==el)return mid; else if(arr.get(mid).a<el)start=mid+1; else end=mid-1; } if(start>arr.size()-1)return -2; return -1; } static long find(int s,long a[]) { if(s>=a.length)return -1; long num=a[s]; for(int i=s;i<a.length;i+=2) { num=gcd(num,a[i]); if(num==1 || num==0)return -1; } return num; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static long factmod(long n,long mod,long img) { if(n==0)return 1; long ans=1; long temp=1; while(n--!=0) { if(temp!=img) { ans=((ans%mod)*((temp)%mod))%mod; } temp++; } return ans%mod; } static int bs(long a[] ,long num) { int start=0; int end=a.length-1; while(start<=end) { int mid=start+(end-start)/2; if(a[mid]==num) { return mid; } else if(a[mid]<num)start=mid+1; else end=mid-1; } return start; } static int ncr(int n, int r){ if(r>n-r)r=n-r; int ans=1; for(int i=0;i<r;i++){ ans*=(n-i); ans/=(i+1); } return ans; } public static class trip{ int a,b,c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } public int compareTo(trip q) { return this.c-q.c; } } static void mergesort(ArrayList<Integer> a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(ArrayList<Integer> a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a.get(ptr1)<=a.get(ptr2)) { b[i]=a.get(ptr1); ptr1++; i++; } else { b[i]=a.get(ptr2); ptr2++; i++; } } while(ptr1<=mid) { b[i]=a.get(ptr1); ptr1++; i++; } while(ptr2<=end) { b[i]=a.get(ptr2); ptr2++; i++; } for(int j=start;j<=end;j++) { a.set(j, b[j-start]); } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } public int compareTo(pair b) { return this.a-b.a; } public int compareToo(pair b) { return this.b-b.b; } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*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 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
8d7495db7eb3f3a9489d695100a46e0e
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 ComdeFormces { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int t=sc.nextInt(); while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; ArrayList<Integer> ev=new ArrayList<>(); ArrayList<Integer> od=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]%2==0) { ev.add(i); } else od.add(i); } Collections.sort(ev); Collections.sort(od); if((n%2==0 && ev.size()-od.size()==0) || (n%2!=0 && Math.abs(ev.size()-od.size())==1)){ long min=Long.MAX_VALUE; if(n%2==0) { long cal=0,cal2=0; int p1=0,p2=0,p3=0,p4=0; for(int i=0;i<n;i++) { if(i%2==0) { cal+=Math.abs(i-ev.get(p1)); cal2+=Math.abs(i-od.get(p3)); p3++; p1++; } else { cal+=Math.abs(i-od.get(p2)); cal2+=Math.abs(i-ev.get(p4)); p4++; p2++; } } min=Math.min(cal2, cal); } else { ArrayList<Integer> ar=ev.size()>od.size()?ev:od; ArrayList<Integer> br=ev.size()<od.size()?ev:od; long cal=0; int p1=0,p2=0; for(int i=0;i<n;i++) { if(i%2==0) { cal+=Math.abs(i-ar.get(p1)); p1++; } else { cal+=Math.abs(i-br.get(p2)); p2++; } } min=cal; } log.write((min/2)+""); } else log.write("-1"); log.write("\n"); log.flush(); } } static long slv(int a[],int b[],long dp[][],int end,int k,int i) { if(i<1 ) { if(k==0) { return (end-a[0])*b[0]; } else return Integer.MAX_VALUE; } if(k<0)return Integer.MAX_VALUE; if(k==0) { return (end-a[0])*b[0]; } if(dp[i][k]!=0)return dp[i][k]; long ans1=slv(a,b,dp,a[i],k-1,i-1); long ans2=slv(a,b,dp,end,k,i-1); long val=(end-a[i])*b[i]; return dp[i][k]=Math.min(val+ans1,ans2); } //debug public static <E> void p(E[][] a,String s) { System.out.println(s); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } public static <E> void p(E a,String s){ System.out.println(s+"="+a); } public static <E> void p(E a[],String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static <E> void p(ArrayList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(LinkedList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Stack<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Queue<E> a,String s){ System.out.println(s+"="+a); } //utils static ArrayList<Integer> divisors(int n){ ArrayList<Integer> ar=new ArrayList<>(); for (int i=2; i<=Math.sqrt(n); i++){ if (n%i == 0){ if (n/i == i) { ar.add(i); } else { ar.add(i); ar.add(n/i); } } } return ar; } static int primeDivisor(int n){ ArrayList<Integer> ar=new ArrayList<>(); int cnt=0; boolean pr=false; while(n%2==0) { pr=true; n/=2; } if(pr)ar.add(2); for(int i=3;i*i<=n;i+=2) { pr=false; while(n%i==0) { n/=i; pr=true; } if(pr)ar.add(i); } if(n>2) ar.add(n); return ar.size(); } static String rev(String s) { char temp[]=s.toCharArray(); for(int i=0;i<temp.length/2;i++) { char tp=temp[i]; temp[i]=temp[temp.length-1-i]; temp[temp.length-1-i]=tp; } return String.valueOf(temp); } static int bs(ArrayList<pair> arr,int el) { int start=0; int end=arr.size()-1; while(start<=end) { int mid=start+(end-start)/2; if(arr.get(mid).a==el)return mid; else if(arr.get(mid).a<el)start=mid+1; else end=mid-1; } if(start>arr.size()-1)return -2; return -1; } static long find(int s,long a[]) { if(s>=a.length)return -1; long num=a[s]; for(int i=s;i<a.length;i+=2) { num=gcd(num,a[i]); if(num==1 || num==0)return -1; } return num; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static long factmod(long n,long mod,long img) { if(n==0)return 1; long ans=1; long temp=1; while(n--!=0) { if(temp!=img) { ans=((ans%mod)*((temp)%mod))%mod; } temp++; } return ans%mod; } static int bs(long a[] ,long num) { int start=0; int end=a.length-1; while(start<=end) { int mid=start+(end-start)/2; if(a[mid]==num) { return mid; } else if(a[mid]<num)start=mid+1; else end=mid-1; } return start; } static int ncr(int n, int r){ if(r>n-r)r=n-r; int ans=1; for(int i=0;i<r;i++){ ans*=(n-i); ans/=(i+1); } return ans; } public static class trip{ int a,b,c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } public int compareTo(trip q) { return this.c-q.c; } } static void mergesort(ArrayList<Integer> a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(ArrayList<Integer> a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a.get(ptr1)<=a.get(ptr2)) { b[i]=a.get(ptr1); ptr1++; i++; } else { b[i]=a.get(ptr2); ptr2++; i++; } } while(ptr1<=mid) { b[i]=a.get(ptr1); ptr1++; i++; } while(ptr2<=end) { b[i]=a.get(ptr2); ptr2++; i++; } for(int j=start;j<=end;j++) { a.set(j, b[j-start]); } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } public int compareTo(pair b) { return this.a-b.a; } public int compareToo(pair b) { return this.b-b.b; } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*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 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
549ceb88d98cd0c718edf13c9d711b22
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 StringBuilder sb; static dsu dsu; static long fact[]; static int mod = (int) (1e9 + 7); static void solve() { int n=i(); int[]arr=new int[n]; ArrayList<Integer> e=new ArrayList<>(); ArrayList<Integer> o=new ArrayList<>(); for(int i=0;i<n;i++){ arr[i]=i(); if(arr[i]%2==0)e.add(i); else o.add(i); } long f=0; if(n%2==0){ if(e.size()!=o.size()){ sb.append(-1+"\n"); return; } else{ long ans=0; int idx=0; for(int x:e){ ans+=Math.abs(x-idx); idx+=2; } idx=1; for(int x:o){ ans+=Math.abs(x-idx); idx+=2; } long ans1=0; idx=1; for(int x:e){ ans1+=Math.abs(x-idx); idx+=2; } idx=0; for(int x:o){ ans1+=Math.abs(x-idx); idx+=2; } f=Math.min(ans,ans1); } } else{ if(Math.abs(e.size()-o.size())!=1){ sb.append(-1+"\n"); return; } else{ if(o.size()>e.size()){ long ans1=0; int idx=1; for(int x:e){ ans1+=Math.abs(x-idx); idx+=2; } idx=0; for(int x:o){ ans1+=Math.abs(x-idx); idx+=2; } f=ans1; } else{ long ans=0; int idx=0; for(int x:e){ ans+=Math.abs(x-idx); idx+=2; } idx=1; for(int x:o){ ans+=Math.abs(x-idx); idx+=2; } f=ans; } } } sb.append((f/2)+"\n"); } public static void main(String[] args) { sb = new StringBuilder(); int test = i(); while (test-- > 0) { solve(); } System.out.println(sb); } /* * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++) * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; } */ //**************NCR%P****************** static long ncr(int n, int r) { if (r > n) return (long) 0; long res = fact[n] % mod; // System.out.println(res); res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod; res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod; // System.out.println(res); return res; } static long p(long x, long y)// POWER FXN // { if (y == 0) return 1; long res = 1; while (y > 0) { if (y % 2 == 1) { res = (res * x) % mod; y--; } x = (x * x) % mod; y = y / 2; } return res; } //**************END****************** // *************Disjoint set // union*********// static class dsu { int parent[]; dsu(int n) { parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = -1; } int find(int a) { if (parent[a] < 0) return a; else { int x = find(parent[a]); parent[a] = x; return x; } } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; parent[b] = a; } } //**************PRIME FACTORIZE **********************************// static TreeMap<Integer, Integer> prime(long n) { TreeMap<Integer, Integer> h = new TreeMap<>(); long num = n; for (int i = 2; i <= Math.sqrt(num); i++) { if (n % i == 0) { int nt = 0; while (n % i == 0) { n = n / i; nt++; } h.put(i, nt); } } if (n != 1) h.put((int) n, 1); return h; } //****CLASS PAIR ************************************************ static class Pair implements Comparable<Pair> { int x; long y; Pair(int x, long y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return (int) (this.y - o.y); } } //****CLASS PAIR ************************************************** static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } 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 Int() { 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 String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); public static long[] sort(long[] a2) { int n = a2.length; ArrayList<Long> l = new ArrayList<>(); for (long i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static char[] sort(char[] a2) { int n = a2.length; ArrayList<Character> l = new ArrayList<>(); for (char i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static long pow(long x, long y) { long res = 1; while (y > 0) { if (y % 2 != 0) { res = (res * x);// % modulus; y--; } x = (x * x);// % modulus; y = y / 2; } return res; } //GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } // ******LOWEST COMMON MULTIPLE // ********************************************* public static long lcm(long x, long y) { return (x * (y / gcd(x, y))); } //INPUT PATTERN******************************************************** public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } public static int[] readArrayi(int n) { int A[] = new int[n]; for (int i = 0; i < n; i++) { A[i] = i(); } return A; } public static long[] readArray(long n) { long A[] = new long[(int) n]; for (int i = 0; i < n; i++) { A[i] = l(); } 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
bc5f0264c8d2e55818ae6bc7d4183420
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 Codeforces { public static void main(String[] args) { Scanner sc= new Scanner(System.in); while(sc.hasNext()) { int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); long a[] = new long[n]; long b[] = new long[n]; int cnt = 0, cnt1 = 0; for(int i = 0 ; i <n;i++) { long s = sc.nextLong(); a[i] = s%2; b[i] = a[i]; if(a[i] == 1) { cnt++; } else{ cnt1++; } } if(cnt != n/2 && cnt1 != n/2) { System.out.println(-1); } else { ArrayList<Integer> al = new ArrayList<>(); ArrayList<Integer> bl = new ArrayList<>(); for(int i = 1 ; i <n;i+=2) { if(a[i] == 1) { al.add(i); } if(a[i] == 0) { bl.add(i); } } long moves = 0; boolean flag = true; for(int i = 0 ; i <n;i+=2) { if(b[i] == 0) { if(al.size() == 0) { flag = false; break; } else { b[i] = 1; moves += Math.abs(i - al.get(0)); b[al.get(0)] = 0; al.remove(0); } } } boolean flag1 = true; long moves1 = 0; for(int i = 0 ; i <n;i+=2) { if(a[i] == 1) { if(bl.size() == 0) { flag1 = false; break; } else { a[i] = 0; moves1+=Math.abs(i - bl.get(0)); a[bl.get(0)] = 1; bl.remove(0); } } } // System.out.println(moves +" "+moves1); if(flag && flag1) { System.out.println(Math.min(moves1, moves)); } else if(flag) { System.out.println(moves); } else if(flag1) { System.out.println(moves1); } else { System.out.println(-1); } } } } } static long gcd(long a , long b) { if(b == 0) { return a; } return gcd(b, a%b); } static boolean isPalindrome(int a[]) { int i= 0; int j = a.length - 1; while(i<=j) { if(a[i] != a[j]) { return false; } i++; j--; } return true; } static boolean isSubsequence(String a , String b) { int i = 0 , j = 0; while(i<a.length() && j<b.length()) { if(a.charAt(i) == b.charAt(j)) { i++; j++; } else { j++; } } if(i == a.length()) { return true; } return false; } static long binarySearch(long k, long target, long i, long j) { while(i<j ) { long mid = i +((j-i)/2); long temp = (long)(mid*(mid+1))/2; if(temp == target) { return mid; } else if(temp<target) { i = mid+1; } else { j = mid-1; } } return i; } static class Pair implements Comparable<Pair>{ char x; long y; Pair(char x, long y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return (int) (this.y - o.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
5e40ff317e914c388832c1a53d6428e5
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.Random; import java.util.StringTokenizer; public class Main { static long mod = 1000000007; static long inv(long a, long b) { return 1 < a ? b - inv(b % a, a) * b / a : 1; } static long mi(long a) { return inv(a, mod); } static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int[] A = new int[n]; int[] B = new int[n]; int even = 0; for(int i = 0 ; i < n ; i++){ A[i] = sc.nextInt(); B[i] = A[i]; if((A[i] & 1) == 0) { even++; } } int odd = n - even; if(Math.abs(even - odd) > 1){ out.println(-1); }else if(even == odd){ int minOp = Math.min(evenFront(A, false), evenFront(B, true)); out.println(minOp); }else if(odd > even){ out.println(evenFront(A, false)); }else{ out.println(evenFront(A, true)); } } out.flush(); out.close(); } private static int evenFront(int[] A, boolean evenFront){ int op =0; boolean evenNeeded = evenFront; int oddIndex = 0; int evenIndex = 0; for(int i = 0 ; i < A.length - 1; i++){ while(oddIndex < A.length && (A[oddIndex] & 1) == 0){ oddIndex++; } while(evenIndex < A.length && (A[evenIndex] & 1) == 1){ evenIndex++; } if(evenNeeded){ swap(A, i, evenIndex); op += evenIndex - i; evenIndex++; }else{ swap(A, i, oddIndex); op += oddIndex - i; oddIndex++; } evenNeeded = !evenNeeded; } return op; } private static void swap(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[j] = temp; } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.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 = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return str; } } public static void shuffle(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; } } public static void shuffle(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; } } }
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
78c811bc4c686f1c64ba87a3eeb639fd
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.IOException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; public class TakeYourPlaces { static InputReader inputReader=new InputReader(System.in); static void solve() { int n=inputReader.nextInt(); int arr[]=inputReader.nextIntArray(n); int evencount=0; int oddcount=0; for (int i=0;i<n;i++) { arr[i]=arr[i]%2; } StringBuffer s01=new StringBuffer(); StringBuffer s10=new StringBuffer(); for (int i=0;i<n;i++) { if (i%2==0) { s01.append(0); s10.append(1); } else { s01.append(1); s10.append(0); } } for (int ele:arr) { if (ele%2!=0) { oddcount++; } else { evencount++; } } if (Math.abs(evencount-oddcount)>1) { out.println(-1); return; } else { if (evencount>oddcount) { int ans=check(arr,new String(s01),n); out.println(ans); return; } else if (oddcount>evencount) { int ans=check(arr,new String(s10),n); out.println(ans); return; } else { int ans=check(arr,new String(s01),n); int ans1=check(arr,new String(s10),n); int fans=Math.min(ans,ans1); out.println(fans); return; } } } static int check(int arr[],String str,int n) { List<Integer>odd=new ArrayList<>(); List<Integer>even=new ArrayList<>(); for (int i=0;i<n;i++) { if (arr[i]==1) { if (str.charAt(i) != '1') { odd.add(i); } } else { if (str.charAt(i)!='0') { even.add(i); } } } int ans=0; for (int i=0;i<odd.size();i++) { ans+=Math.abs(odd.get(i)-even.get(i)); } return ans; } static PrintWriter out=new PrintWriter((System.out)); public static void main(String args[])throws IOException { int t=inputReader.nextInt(); while(t-->0) { solve(); } out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public 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
fedab42339e7addff667bc382bc117df
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 : Kartikey Rana from MSIT New Delhi */ import java.util.*; import java.util.Arrays; import java.util.Collections; import javax.sql.rowset.serial.SerialArray; import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction; import java.io.*; import java.math.*; import java.sql.Array;; public class Main { static class FR { BufferedReader br; StringTokenizer st; public FR() { 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; } // NEXT INT ARRAY int[] NIA(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } // NEXT DOUBLE ARRAY double[] NDA(int n) { double arr[] = new double[n]; for (int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } // NEXT LONG ARRAY long[] NLA(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } // NEXT STRING ARRAY String[] NSA(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = next(); return arr; } // NEXT CHARACTER ARRAY char[] NCA(int n) { char[] arr = new char[n]; String s = sc.nextLine(); for (int i = 0; i < n; i++) arr[i] = s.charAt(i); return arr; } } //************************* FR CLASS ENDS ********************************** static long mod = (long) (1e9 + 7); public static int[] sieve(int n) { int[] primes = new int[n + 1]; for (int i = 0; i <= n; i++) { primes[i] = i; } for (int i = 2; i < n; i++) { if (primes[i] < 0) continue; if ((long) i * (long) i > n) break; for (int j = i * i; j < n; j++) { if (primes[j] > 0 && primes[j] % primes[i] == 0) primes[j] = -primes[j]; } } return primes; } static int lcm(int a, int b) { return (int) ((a / gcd(a, b)) * b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long[][] ncr(int n, int k) { long C[][] = new long[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod; } } return C; } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int) ((p * (long) p) % m); if (y % 2 == 0) return p; else return (int) ((x * (long) p) % m); } static int XOR(int n) { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } // ----------------------------------DSU-------------------------------- static int parent[]; static int rank[]; public static int find(int x) { if(x == parent[x]) { return x; } int temp = find(parent[x]); parent[x] = temp; return temp; } public static void union(int x, int y) { int lx = find(x); int ly = find(y); if(parent[x] == parent[y]) return; if(rank[lx] < rank[ly]) { parent[lx] = ly; } else if(rank[lx] >rank[ly]) { parent[ly] = lx; } else { parent[lx] = ly; rank[ly]++; } find(x); find(y); } /* ***************************************************************************************************************************************************/ static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { super(); this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return this.x - o.x; } } static FR sc = new FR(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) throws IOException { int tc = sc.nextInt(); // int tc = 1; while (tc-- > 0) { TEST_CASE(); } sb.setLength(sb.length() - 1); System.out.println(sb); } static void TEST_CASE() throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = sc.nextInt(); int[] arr = sc.NIA(n); int o = 0; for(int i = 0; i < n; i++) { arr[i] &= 1; o += arr[i]; } if(Math.abs(o - (n-o)) > 1) { sb.append("-1\n"); return; } int ans = 0; if(o > n - o) { //1010101 List<Integer> eve = new LinkedList<>(); List<Integer> odd = new LinkedList<>(); for(int i = 0; i < n; i++) { if((i&1) == 0 && arr[i] == 0) odd.add(i); else if((i&1) == 1 && arr[i] == 1) eve.add(i); } while(eve.size() > 0) { ans += Math.abs(eve.remove(0) - odd.remove(0)); } } else if(o < n-o) { //0101010 List<Integer> eve = new LinkedList<>(); List<Integer> odd = new LinkedList<>(); for(int i = 0; i < n; i++) { if((i&1) == 0 && arr[i] == 1) odd.add(i); else if((i&1) == 1 && arr[i] == 0) eve.add(i); } while(eve.size() > 0) { ans += Math.abs(eve.remove(0) - odd.remove(0)); } } else { List<Integer> eve = new LinkedList<>(); List<Integer> odd = new LinkedList<>(); int ans1 = 0; int ans2 = 0; for(int i = 0; i < n; i++) { if((i&1) == 0 && arr[i] == 0) odd.add(i); else if((i&1) == 1 && arr[i] == 1) eve.add(i); } while(eve.size() > 0) { ans1 += Math.abs(eve.remove(0) - odd.remove(0)); } eve = new LinkedList<>(); odd = new LinkedList<>(); for(int i = 0; i < n; i++) { if((i&1) == 0 && arr[i] == 1) odd.add(i); else if((i&1) == 1 && arr[i] == 0) eve.add(i); } while(eve.size() > 0) { ans2 += Math.abs(eve.remove(0) - odd.remove(0)); } ans = Math.min(ans1, ans2); } sb.append(ans + "\n"); } }
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
713a1305d66a77faa826183721b38724
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 { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(); int ctodd=0; int cteven=0; int[]A=new int[n]; for (int i=0;i<n;i++) { int u=ni(); if (u%2==1) { A[i]=1; ctodd++; } else cteven++; } int ans=0; if (n%2==0 && ctodd!=cteven) { out.println(-1); continue; } if (n%2==1 && Math.abs(ctodd-cteven)!=1) { out.println(-1); continue; } int tar=A[0]; if (n%2==1) { if (ctodd>cteven) tar=1; else tar=0; } int p=0; while (p<n && A[p]!=tar) p++; for (int i=0;i<n;i+=2) { if (p>i) ans+=p-i; p++; while (p<n && A[p]!=tar) p++; } tar=(tar-1)*-1; p=0; while (p<n && A[p]!=tar) p++; for (int i=1;i<n;i+=2) { if (p>i) ans+=p-i; p++; while (p<n && A[p]!=tar) p++; } if (n%2==0) { int a2=0; tar=A[0]; tar=(tar-1)*-1; p=0; while (p<n && A[p]!=tar) p++; for (int i=0;i<n;i+=2) { if (p>i) a2+=p-i; p++; while (p<n && A[p]!=tar) p++; } tar=(tar-1)*-1; p=0; while (p<n && A[p]!=tar) p++; for (int i=1;i<n;i+=2) { if (p>i) a2+=p-i; p++; while (p<n && A[p]!=tar) p++; } ans=Math.min(ans,a2); } out.println(ans); } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
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
c68498366fb72423fe639f3cd35fcad7
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 { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(); int[]A=new int[n]; for (int i=0;i<n;i++) A[i]=ni(); if (n%2==0) { int ct=0; for (int i=0;i<n;i++) if (A[i]%2==0) ct++; if (ct!=n/2) out.println(-1); else { int a1=0; int a2=0; int np1=0; int np2=1; for (int i=0;i<n;i++) { if (A[i]%2==1) continue; a1+=Math.abs(np1-i); a2+=Math.abs(np2-i); np1+=2; np2+=2; } out.println(Math.min(a1,a2)); } } else { int ct=0; for (int i=0;i<n;i++) if (A[i]%2==0) ct++; //out.println(ct); if (ct==n/2) { int a1=0; int np=0; for (int i=0;i<n;i++) { if (A[i]%2==0) continue; a1+=Math.abs(np-i); np+=2; } out.println(a1); } else if (ct==n/2+1) { int a1=0; int np=0; for (int i=0;i<n;i++) { if (A[i]%2==1) continue; a1+=Math.abs(np-i); np+=2; } out.println(a1); } else out.println(-1); } } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
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
3094d8c380d992e63df63849b86c013d
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 FastReader reader; public static void main(String[] args) throws IOException { reader = new FastReader(); int t = reader.nextInt(); while (t-- > 0) test (); } static void test () { int n = reader.nextInt(); int[] arr = new int[n]; List<Integer> even = new ArrayList<>(), odd = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = reader.nextInt(); if (arr[i] % 2 == 0) even.add(i); else odd.add(i); } if (Math.abs(even.size() - odd.size()) > 1) { System.out.println(-1); return; } long ans = (long) 1e15; long cnt; int a, b; if (even.size() >= odd.size()) { cnt = 0; a = 0; b = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (even.get(a) > i) { cnt += even.get(a) - i; } a++; } else { if (odd.get(b) > i) { cnt += odd.get(b) - i; } b++; } } ans = Math.min(ans, cnt); } if (odd.size() >= even.size()) { cnt = 0; a = 0; b = 0; for (int i = 0; i < n; i++) { if (i % 2 == 1) { if (even.get(a) > i) { cnt += even.get(a) - i; } a++; } else { if (odd.get(b) > i) { cnt += odd.get(b) - i; } b++; } } ans = Math.min(ans, cnt); } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException { 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
acf3a1053445248f4dd0cde3918c01f0
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.text.ParseException; import java.util.*; public class Main { static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } static int ifnotPrime(int prime[], int x) { // checking whether the value of element // is set or not. Using prime[x/64], // we find the slot in prime array. // To find the bit number, we divide x // by 2 and take its mod with 32. return (prime[x/64] & (1 << ((x >> 1) & 31))); } // Marks x composite in prime[] static void makeComposite(int prime[], int x) { // Set a bit corresponding to given element. // Using prime[x/64], we find the slot // in prime array. To find the bit number, // we divide x by 2 and take its mod with 32. prime[x/64] |= (1 << ((x >> 1) & 31)); } // Prints all prime numbers smaller than n. static ArrayList<Integer> bitWiseSieve(int n) { ArrayList<Integer> al=new ArrayList<Integer>(); int prime[] = new int[n/64 + 1]; // 2 is the only even prime so we // can ignore that loop starts from // 3 as we have used in sieve of // Eratosthenes . for (int i = 3; i * i <= n; i += 2) { // If i is prime, mark all its // multiples as composite if (ifnotPrime(prime, i)==0) for (int j = i * i, k = i << 1; j < n; j += k) makeComposite(prime, j); } // writing 2 separately al.add(2); // Printing other primes for (int i = 3; i <= n; i += 2) if (ifnotPrime(prime, i) == 0) al.add(i); return al; } static List<Integer> sieve(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int)size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return pr; } static long binary_Expo(long a, long b) // calculating a^b { long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static long Modular_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % 1000000007; --b; } a = (a * a) % 1000000007; b /= 2; } return res; } static int i_gcd(int a, int b) // iterative way to calculate gcd. { while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) // here b is the remainder { if (b == 0) return a; //because each time b will divide a. return gcd(b, a % b); } static long ceil_div(long a, long b) // a numerator b denominator { return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static int upper_Bound(int a[], int x) //closest to the left+1 { 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; } static int upper_Bound(List<Integer> a, int x) //closest to the left+1 { int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) <= x) l = m; else r = m; } return l + 1; } static int lower_Bound(int a[], int x) //closest to the right { 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; } static int lower_Bound(List<Integer> a, int x) //closest to the right { int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) >= x) r = m; else l = m; } return r; } static boolean isSquarefactor(int x, int factor, int target) { int s = (int) Math.round(Math.sqrt(x)); return factor * s * s == target; } static boolean isSquare(int x) { int s = (int) Math.round(Math.sqrt(x)); return x * x == s; } static void sort(int a[]) // heap sort { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); fast_swap(in, idx, i); } } static int[] computeLps(String pat) { int len=0,i=1,m=pat.length(); int lps[]=new int[m]; lps[0]=0; while(i<m) { if(pat.charAt(i)==pat.charAt(len)) { ++len; lps[i]=len; ++i; } else { if(len!=0) { len=lps[len-1]; } else { lps[i]=len; ++i; } } } return lps; } static void kmp(String s,String pat) { int n=s.length(),m=pat.length(); int lps[]=computeLps(pat); int i=0,j=0; while(i<n) { if(s.charAt(i)==pat.charAt(j)) { i++; j++; } else { if(j!=0) { j=lps[j-1]; } else { i++; } } } } static void reverse_ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); for (int l = 0, r = a.length - 1; l < r; ++l, --r) fast_swap(a, l, r); } static void ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } static int[] z_function(String s) { int n = s.length(), z[] = new int[n]; for (int i = 1, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = Math.min(z[i - l], r - i + 1); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } static void swap(int a[], int idx1, int idx2) { a[idx1] += a[idx2]; a[idx2] = a[idx1] - a[idx2]; a[idx1] -= a[idx2]; } static void fast_swap(int[] a, int idx1, int idx2) { if (a[idx1] == a[idx2]) return; a[idx1] ^= a[idx2]; a[idx2] ^= a[idx1]; a[idx1] ^= a[idx2]; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 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(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static class Pair { int val,bin; public Pair(int val,int bin) { this.val=val; this.bin=bin; } } //int[] input = Arrays.stream(br.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); public static void main(String[] args) throws IOException,ParseException { FastScanner sc=new FastScanner(); int t=sc.nextInt(); while (t-->0) { int n=sc.nextInt(); int ev=0,od=0; int arr[]=new int[n]; for(int i=0;i<n;i++) { int val=sc.nextInt(); if((val&1)==1) { arr[i]=0; ++od; } else { arr[i]=1; ++ev; } } if(n%2==0) { if(ev==od) { int ans=Math.min(fun(0,n,arr),fun(1,n,arr)); System.out.println(ans); } else { System.out.println(-1); } } else { if(od==ev+1) { System.out.println(fun(0,n,arr)); } else if(ev==od+1) { System.out.println(fun(1,n,arr)); } else { System.out.println(-1); } } } } private static int fun(int x,int n,int[] arr) { int delta=0,ans=0; for(int i=0;i<n;i++) { if(arr[i]!=x) { delta+=(x-arr[i]); } ans+=Math.abs(delta); x^=1; } 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 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
1beb0a05018c4baf05cc97e6659d1597
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.*; import java.util.*; public class B { static final int INF = 0x3f3f3f3f; static final long LNF = 0x3f3f3f3f3f3f3f3fL; public static void main(String[] args) throws IOException { initReader(); int T = nextInt(); for (int i = 1; i <= T; i++) solve(); pw.flush(); } /*******************************************************************************************************************************/ public static void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); int odd = 0, even = 0; for (int i : a) { if ((i & 1) == 1) odd++; else even++; } if (Math.abs(odd - even) > 1) { pw.println(-1); return ; } long ans = LNF; if (even <= odd) { long re = 0; for (int i = 0, j = 1; i < n; i++) { if ((a[i] & 1) == 0) { re += Math.abs(i - j); j += 2; } } ans = Math.min(ans, re); } if (odd <= even) { long re = 0; for (int i = 0, j = 1; i < n; i++) { if ((a[i] & 1) == 1) { re += Math.abs(i - j); j += 2; } } ans = Math.min(ans, re); } pw.println(ans); } public static void Solve(BufferedReader reader1, PrintWriter pw1, StringTokenizer tokenizer1) throws IOException { reader = reader1; pw = pw1; tokenizer = tokenizer1; int T = nextInt(); for (int i = 1; i <= T; i++) solve(); pw.flush(); } public static <T> void deBug(T... a) { System.out.println(Arrays.toString(a)); } /*******************************************************************************************************************************/ /*******************************************************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // reader = new BufferedReader(new FileReader("test.in")); // tokenizer = new StringTokenizer(""); // pw = new PrintWriter(new BufferedWriter(new FileWriter("My answer.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static char nextChar() throws IOException { return next().charAt(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
ca9e2c2dbf9562afa046927ef87458c3
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.text.*; import java.util.*; import java.math.*; public class A { public static void main(String[] args) throws Exception { new A().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); while(asdf-->0) { int n = f.nextInt(); int[] arr = new int[n]; int _0 = 0, _1 = 0; for(int i = 0; i < n; i++) { arr[i] = f.nextInt(); if(arr[i] % 2 == 0) _0++; else _1++; } if(Math.abs(_0 - _1) > 1) out.println(-1); else if(n%2 == 0) { long aans = 214748364749494L; { int ind0 = 0, ind1 = 1; long ans = 0; for(int i = 0; i < n; i++) if(arr[i] % 2 == 0) { ans += Math.abs(ind0-i); ind0 += 2; } else { ans += Math.abs(ind1-i); ind1 += 2; } aans = Math.min(aans, ans); } { int ind0 = 1, ind1 = 0; long ans = 0; for(int i = 0; i < n; i++) if(arr[i] % 2 == 0) { ans += Math.abs(ind0-i); ind0 += 2; } else { ans += Math.abs(ind1-i); ind1 += 2; } aans = Math.min(aans, ans); } out.println(aans/2); } else { int ind0 = _0 > _1 ? 0 : 1, ind1 = 1 - ind0; long ans = 0; for(int i = 0; i < n; i++) if(arr[i] % 2 == 0) { ans += Math.abs(ind0-i); ind0 += 2; } else { ans += Math.abs(ind1-i); ind1 += 2; } out.println(ans/2); } } /// out.flush(); } /// static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } 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 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
35b699da9c70743fb4ba926cb37803dc
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 { static Scanner in = new Scanner(System.in); static StringBuilder out = new StringBuilder(); public static void main(String[] args) { int ntc = Integer.parseInt(in.nextLine()); for (int tc = 1; tc <= ntc; tc++) { int n = in.nextInt(); int noe = 0; // number of evens int[] evens = new int[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); if ((x & 1) == 0) { evens[noe++] = i; } } int evenFirstRes = 0, oddFirstRes = 0; for (int i = 0; i < noe; i++) { evenFirstRes += Math.abs(evens[i] - i*2); oddFirstRes += Math.abs(evens[i] - (i*2 + 1)); } int res = Math.abs(noe - (n-noe)) > 1 ? -1 : (n/2)*2 == n ? Math.min(evenFirstRes, oddFirstRes) : n-noe < noe ? evenFirstRes : oddFirstRes; out.append(res + "\n"); } System.out.print(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 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
96732713498d431ce60394200a6099e3
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.*; //solve harder problems //upsolve //get off computer //use gitgud //learn from everything //USACO public class Contest1556B { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { // reads in the next string while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { // reads in the next int return Integer.parseInt(next()); } public long nextLong() { // reads in the next long return Long.parseLong(next()); } public double nextDouble() { // reads in the next double return Double.parseDouble(next()); } } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { //LOOK FOR INT OVERFLOW //LOOK FOR SCOPE ERROR //Add negatives //SORT BOTH ARRAYS //CHECK THE LAST ONE THAT IS OUT LOOP //SORT BY BOTH VALUES //DON'T ADD STRINGS,USE STRING BUILDER int t = r.nextInt(); while (t > 0) { t--; int n = r.nextInt(); int[] a = new int[n]; long hi = 0; ArrayList<Integer> ones = new ArrayList<Integer>(); ArrayList<Integer> zero = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) { a[i] = r.nextInt()%2; hi += a[i]; if (a[i] == 1) { ones.add(i+1); } else { zero.add(i+1); } } if (hi < (n)/2 || hi > (n+1)/2) { pw.println(-1); } else { if (n %2 == 0) { int[] e = new int[n]; for (int i = 1; i <= n; i ++) { e[(i+1)/2-1] = i; } int[] o = new int[n]; for (int i = 0; i < n; i +=2) { o[i/2] = i + 1; } long sum = 0; for (int i = 0; i < n/2; i ++) { sum += Math.abs(ones.get(i)-o[i]); } long sum2 = 0; for (int i = 0; i < n/2; i ++) { sum2 += Math.abs(ones.get(i)-e[i]); } pw.println(Math.min(sum, sum2)); } else { int[] e = new int[n]; for (int i = 1; i <= n; i ++) { e[(i+1)/2-1] = i; } int[] o = new int[n]; for (int i = 0; i < n+1; i +=2) { o[i/2] = i + 1; } long sum = 0; if (hi == n/2) { for (int i = 0; i < n/2; i ++) { sum += Math.abs(ones.get(i)-e[i]); } } else { for (int i = 0; i < n/2+1; i ++) { sum += Math.abs(ones.get(i)-o[i]); } } pw.println(sum); } } } 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 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
29a72812969e6213a3a112df5bc63f1d
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.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class b729 { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); // try { int t = sc.nextInt(); for(int o = 0 ; o<t;o++) { int od = 0; int ev = 0; int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextInt(); if(arr[i]%2==0) { ev++; }else { od++; } } if(Math.abs(od-ev)>1) { System.out.println(-1); continue; } long ans = 0; if(ev>od) { int val = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==1) { ans += Math.abs(i-val); val+=2; } } System.out.println(ans); }else if(od>ev) { int val = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==0) { ans += Math.abs(i-val); val+=2; } } System.out.println(ans); }else { int val = 1; long ans1 = 0; long ans2 = 0; for(int i = 0 ; i<n;i++) { if(arr[i]%2==1) { ans1 += Math.abs(i-val); val+=2; } } // System.out.println(ans); int val2 = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==0) { ans2 += Math.abs(i-val2); val2+=2; } } System.out.println(Math.min(ans1, ans2)); // System.out.println(ans); } } // }catch(Exception e) { // return ; // } } } 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; } } //8 //3 //537 //3 //237 //5 //44444 //3 //221 //2 //35 //3 //773 //1 //4 //30 //626221626221626221626221626221
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
0b4ac92806d04df0143b8afeda544621
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.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class b729 { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); // try { int t = sc.nextInt(); for(int o = 0 ; o<t;o++) { int od = 0; int ev = 0; int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextInt(); if(arr[i]%2==0) { ev++; }else { od++; } } if(Math.abs(od-ev)>1) { System.out.println(-1); continue; } long ans = 0; if(ev>od) { int val = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==1) { ans += Math.abs(i-val); val+=2; } } System.out.println(ans); }else if(od>ev) { int val = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==0) { ans += Math.abs(i-val); val+=2; } } System.out.println(ans); }else { int val = 1; long ans1 = 0; long ans2 = 0; for(int i = 0 ; i<n;i++) { if(arr[i]%2==1) { ans1 += Math.abs(i-val); val+=2; } } // System.out.println(ans); int val2 = 1; for(int i = 0 ; i<n;i++) { if(arr[i]%2==0) { ans2 += Math.abs(i-val2); val2+=2; } } System.out.println(Math.min(ans1, ans2)); // System.out.println(ans); } } // }catch(Exception e) { // return ; // } } } 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 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
8c9ac51b4cdf3794305666f78968af7c
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 { public static int solve(ArrayList<Integer> a, ArrayList<Integer> b) { if(a.size() != b.size()) return Integer.MAX_VALUE; int ans = 0; for(int i = 0; i < a.size(); i++) { ans += Math.abs(a.get(i) - b.get(i)); } return ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int n = sc.nextInt(); ArrayList<Integer> a = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); ArrayList<Integer> c = new ArrayList<>(); for(int i = 0; i < n; i++) { if(sc.nextInt() % 2 == 0) a.add(i); } int i = 0; while(i < n) { if(i < n) b.add(i++); if(i < n) c.add(i++); } int ans = Math.min(solve(a, b), solve(a, c)); System.out.println((ans == Integer.MAX_VALUE ? -1 : ans)); } } } class MyScanner { BufferedReader br; StringTokenizer tok; MyScanner() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); tok = new StringTokenizer(""); } public String next() throws IOException { while(!tok.hasMoreTokens()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } public int nextInt() throws IOException { 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 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
c8cbf6edeb92b5e695c2b823bf90a61a
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 { public static int solve(ArrayList<Integer> a, ArrayList<Integer> b) { if(a.size() != b.size()) return Integer.MAX_VALUE; int ans = 0; for(int i = 0; i < a.size(); i++) { ans += Math.abs(a.get(i) - b.get(i)); } return ans; } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); int T = sc.nextInt(); while(T-- > 0) { int n = sc.nextInt(); ArrayList<Integer> a = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); ArrayList<Integer> c = new ArrayList<>(); for(int i = 0; i < n; i++) { if(sc.nextInt() % 2 == 0) a.add(i); } int i = 0; while(i < n) { if(i < n) b.add(i++); if(i < n) c.add(i++); } int ans = Math.min(solve(a, b), solve(a, c)); System.out.println((ans == Integer.MAX_VALUE ? -1 : ans)); } } } class MyScanner { BufferedReader br; StringTokenizer tok; MyScanner() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); tok = new StringTokenizer(""); } public String next() throws IOException { while(!tok.hasMoreTokens()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } public int nextInt() throws IOException { 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 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
55b5901bf8d14062f8030d80a95b3aae
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 { public static int solve(PriorityQueue<Integer> e, PriorityQueue<Integer> o, int n, int s) { int ans = 0; try { for(int i = 0; i < n; i++) { if(i % 2 == s) { int k = e.poll(); if(k != i) { o.poll(); ans += k - i; o.add(k); } } else { int k = o.poll(); if(k != i) { e.poll(); ans += k - i; e.add(k); } } } } catch(Exception ex) { return Integer.MAX_VALUE;} return ans; } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); int T = sc.nextInt(); while(T-- > 0) { int n = sc.nextInt(); PriorityQueue<Integer> e1 = new PriorityQueue<>(); PriorityQueue<Integer> e2 = new PriorityQueue<>(); PriorityQueue<Integer> o1 = new PriorityQueue<>(); PriorityQueue<Integer> o2 = new PriorityQueue<>(); for(int i = 0; i < n; i++) { int x = sc.nextInt(); if(x % 2 == 0) { e1.add(i); e2.add(i); } else { o1.add(i); o2.add(i); } } int ans = Math.min(solve(e1, o1, n, 0), solve(e2, o2, n, 1)); if(ans == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(ans); } } } class MyScanner { BufferedReader br; StringTokenizer tok; MyScanner() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); tok = new StringTokenizer(""); } public String next() throws IOException { while(!tok.hasMoreTokens()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } public int nextInt() throws IOException { 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 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
e8bb65aa2331c50c87dc83b24c5334eb
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.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class A { static int Inf = Integer.MAX_VALUE; static long check(int[] c,int[] o){ int n = c.length; int j=0; long ans=0; for(int i=0;i<n;i++){ if(j<n && c[i]==o[j]){ ans+=abs(i-j); j+=2; } } return ans; } public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); // int n = Integer.parseInt(st.nextToken()); // int m = Integer.parseInt(st.nextToken()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int n = Integer.parseInt(st.nextToken()); long[] a = readArr2(n, infile, st); int[] c = new int[n]; int one=0; int zero=0; for(int i=0;i<n;i++){ c[i] = (int)(a[i]%2); if(c[i]==1)one++; else zero++; } if(abs(one-zero)>1){ out.println(-1); continue; } int[] o = new int[n]; int[] e = new int[n]; int o1=0,e1=0; for(int i=0;i<n;i++){ if(i%2==0){ o[i] = 1; o1++; } else { o[i] = 0; e1++; } } long cnt1=Inf,cnt2=Inf; if(o1==one && zero==e1)cnt1=min(cnt1,check(c,o)); o1=0; e1=0; for(int i=0;i<n;i++){ if(i%2==0){ e[i] = 0; e1++; } else{ e[i] = 1; o1++; } } if(o1==one && zero==e1)cnt2=min(cnt2,check(c,e)); out.println(min(cnt1,cnt2)); } //BufferedReader infile = new BufferedReader(new FileReader("input.txt")); //System.setOut(new PrintStream(new File("output.txt"))); } 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 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 void print(int[] arr) { //for debugging only for(int x: arr) out.print(x+" "); out.println(); } //input shenanigans /* Random stuff to try when stuck: -for combo/probability problems, expand the given form we're interested in -make everything the same then build an answer (constructive, make everything 0 then do something) -something appears in parts of 2 --> model as graph -assume a greedy then try to show why it works -find way to simplify into one variable if multiple exist -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them) -find lower and upper bounds on answer -figure out what ur trying to find and isolate it -see what observations you have and come up with more continuations -work backwards (in constructive, go from the goal to the start) -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements) -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max) -draw something -simulate a process -dont implement something unless if ur fairly confident its correct -after 3 bad submissions move on to next problem if applicable -do something instead of nothing and stay organized -write stuff down Random stuff to check when wa: -if code is way too long/cancer then reassess -switched N/M -int overflow -switched variables -wrong MOD -hardcoded edge case incorrectly Random stuff to check when tle: -continue instead of break -condition in for/while loop bad Random stuff to check when rte: -switched N/M -long to int/int overflow -division by 0 -edge case for empty list/data structure/N=1 */ static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} 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; } static void sortr(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l,Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } 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); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static long power(long x, long y, long p) { //0^0 = 1 long res = 1L; x = x%p; while(y > 0) { if((y&1)==1) res = (res*x)%p; y >>= 1; x = (x*x)%p; } return 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 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
c59500bd74cd0af33331380c68a1b7ae
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.StringTokenizer; public class Bdeltox{ private static final long max = 1_000_000_000_000_000_000L; public static void main(String[] args){ FastReader sc = new FastReader(); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); ArrayList<Integer>position=new ArrayList<Integer>(); ArrayList<Integer>odd=new ArrayList<Integer>(); ArrayList<Integer>even=new ArrayList<Integer>(); for(int i=0;i<n;i++) { int x=sc.nextInt(); if((x&1)==0) { position.add(i); } if((i&1)==0) { even.add(i); } else { odd.add(i); } } long cost =Math.min(totaldis(position, odd), totaldis(position, even)); System.out.println(cost<max?cost:-1); } } static long totaldis(ArrayList<Integer> position,ArrayList<Integer> a) { if(position.size()!=a.size()) return max; long sum=0; for(int i=0;i<a.size();i++) { sum+=Math.abs(position.get(i)-a.get(i)); } return sum; } static class ind { int x;int y; ind(int x,int y){ this.x=x; this.y=y; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } int [] fastArray(int n) { int a[]=new int [n]; for(int i=0;i<n;i++) { a[i]=nextInt(); } return a; } 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
eb63cd29a8b8f2281dd073130e5eda39
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
/** * @Created_by : Lucent868 * @Date : 30-08-2021 * @Time : 09:52 */ import java.util.*; import java.io.*; import java.math.*; public class B { static InputReader in; static PrintWriter out; public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try { solve(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } public static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int a[] = in.nextIntArray(n); int o = 0; int e = 0; for (int i = 0; i < n; i++) { if (a[i] % 2 == 0) e++; else o++; a[i] %= 2; } if (n == 1) { out.println(0); continue; } if (Math.abs(o - e) > 1) { out.println(-1); continue; } ArrayList<Integer> even = new ArrayList<>(); ArrayList<Integer> odd = new ArrayList<>(); int b[] = new int[n]; for (int i = 1; i < n; i += 2) { b[i] = 1; } int c[] = new int[n]; for (int i = 0; i < n; i += 2) { c[i] = 1; } int ans1 = 0; for (int i = 0; i < n; i++) { if (b[i] == 1 && a[i] == 0) odd.add(i); else if (b[i] == 0 && a[i] == 1) even.add(i); } if (even.size() == odd.size()) { for (int i = 0; i < even.size(); i++) ans1 += Math.abs(even.get(i) - odd.get(i)); } else { ans1 = Integer.MAX_VALUE; } // out.println(even + " " + odd); even.clear(); odd.clear(); int ans2 = 0; for (int i = 0; i < n; i++) { if (c[i] == 1 && a[i] == 0) odd.add(i); else if (c[i] == 0 && a[i] == 1) even.add(i); } if (even.size() == odd.size()) { for (int i = 0; i < even.size(); i++) ans2 += Math.abs(even.get(i) - odd.get(i)); } else { ans2 = Integer.MAX_VALUE; } // out.println(even+" "+odd); out.println(Math.min(ans1,ans2)); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 int nextInt() { 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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static int[] sort(int[] arr) { List<Integer> temp = new ArrayList(); for (int i : arr) temp.add(i); Collections.sort(temp); int start = 0; for (int i : temp) arr[start++] = i; return arr; } public static long[] sort(long[] arr) { List<Long> temp = new ArrayList(); for (long i : arr) temp.add(i); Collections.sort(temp); int start = 0; for (long i : temp) arr[start++] = i; return arr; } public static int bs(int[] a, int fromIndex, int toIndex, double key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } }
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
82fb88e9c3184691cab3c5d1f171529c
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.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { int t = readInt(); for(int f =0;f<t;f++) { int n = readInt(); int arr[]=new int[n+1]; for(int i =1;i<=n;i++) arr[i]= readInt(); int even=0; int odd=0; ArrayList <Integer> e =new ArrayList<Integer>(); for(int i =1;i<=n;i++) { if(arr[i]%2==0) { even++; e.add(i); } else odd++; } if(even>(n+1)/2||odd>(n+1)/2) out.println(-1); else { int g = (n+1)/2; long ans=n; ans = ans*n; int l =e.size(); // out.println(e.size()); if(g==l) { int cur=1; long val=0; for(int i=0;i<e.size();i++) { val = val+Math.abs(e.get(i)-cur); // out.println(val); cur=cur+2; } ans=Math.min(ans,val); } if((n-g)==l) { int cur=2; long val=0; for(int i =0;i<e.size();i++) { val = val +Math.abs(e.get(i)-cur); // out.println(val); cur=cur+2; } ans=Math.min(ans,val); } out.println(ans); } } } public long query(long seg[] , int left, int right , int index, int l , int r) { long inf = 100000000; inf = inf*inf; if(left>=l&&right<=r) { return seg[index]; } if(l>right||left>r) return inf; int mid = left+(right-left)/2; return Math.min(query(seg,left,mid,2*index+1,l,r),query(seg,mid+1,right,2*index+2,l,r)); } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; edge(int u, int v) { this.u=u; this.v=v; } public int compareTo(edge e) { return this.v-e.v; } }
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
3113f4624a7f1e91747e73550c22fd2b
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 { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; while (t-- > 0) { int n = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); int arr[] = new int[n]; int zc = 0; int oc = 0; for (int i = 0; i < n; i++) { int e = Integer.parseInt(st.nextToken()); arr[i] = e % 2; if (arr[i] == 0) zc++; else oc++; } if ((int) Math.abs(zc - oc) > 1) { output.write("-1\n"); continue; } int fin[] = new int[n]; if (zc != oc) { fin[0] = (zc > oc) ? 0 : 1; for (int i = 1; i < n; i++) { fin[i] = 1 - fin[i - 1]; } int p1 = 0; int p2 = 0; int res = 0; while (p1 < n && p2 < n) { if (arr[p1] == fin[p2] && arr[p1] == 1) { p1++; p2++; res += (int) Math.abs(p1 - p2); continue; } else { if (arr[p1] == 0) p1++; else p2++; } } output.write(res + "\n"); } else { int fin2[] = new int[n]; fin2[0] = 0; fin[0] = 1; for (int i = 1; i < n; i++) { fin[i] = 1 - fin[i - 1]; fin2[i] = 1 - fin2[i - 1]; } int p1 = 0; int p2 = 0; int res = 0; while (p1 < n && p2 < n) { if (arr[p1] == fin[p2] && arr[p1] == 1) { p1++; p2++; res += (int) Math.abs(p1 - p2); continue; } else { if (arr[p1] == 0) p1++; else p2++; } } int p3 = 0; int p4 = 0; int res2 = 0; while (p3 < n && p4 < n) { if (arr[p3] == fin2[p4] && arr[p3] == 1) { p3++; p4++; res2 += (int) Math.abs(p3 - p4); continue; } else { if (arr[p3] == 0) p3++; else p4++; } } int resfin = Math.min(res, res2); output.write(resfin + "\n"); } // output.write(solve(arr, arr.length) + "\n"); // output.write(findMinSwaps(arr, arr.length) + "\n"); // int k = Integer.parseInt(st.nextToken()); // char arr[] = br.readLine().toCharArray(); // output.write(); // int n = Integer.parseInt(st.nextToken()); // HashMap<Character, Integer> map = new HashMap<Character, Integer>(); // if // output.write("YES\n"); // else // output.write("NO\n"); // long a = Long.parseLong(st.nextToken()); // long b = Long.parseLong(st.nextToken()); // if(flag == 1) // output.write("NO\n"); // else // output.write("YES\n" + x + " " + y + " " + z + "\n"); // output.write(n+ "\n"); } output.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
PASSED
093ae9785f78bb4717b674da1cdf4947
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.util.StringTokenizer; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class B { public static void main(String[] args) { FastReader fr = new FastReader(); PrintWriter out = new PrintWriter(System.out, true); int cases = fr.nextInt(); for(int c = 0; c < cases; c++) { int size = fr.nextInt(); int[] nums = new int[size]; Queue<Integer> evenlocs = new PriorityQueue<>(); Queue<Integer> oddlocs = new PriorityQueue<>(); Queue<Integer> othereven = new PriorityQueue<>(); Queue<Integer> otherodd = new PriorityQueue<>(); for (int i = 0; i < size; i++) { int curnum = fr.nextInt() % 2; nums[i] = curnum; if(curnum == 0) { evenlocs.add(i); othereven.add(i); } else { oddlocs.add(i); otherodd.add(i); } } if(Math.abs(evenlocs.size() - oddlocs.size()) > 1) { out.write(-1 + "\n"); } else { out.write(solve(nums, evenlocs, oddlocs, othereven, otherodd) + "\n"); } } out.close(); } static int solve(int[] nums, Queue<Integer> evenlocs, Queue<Integer> oddlocs, Queue<Integer> othereven, Queue<Integer> otherodd) { if(evenlocs.size() > oddlocs.size()) { return solveHelper(nums, evenlocs, oddlocs, 0); } else if(oddlocs.size() > evenlocs.size()) { return solveHelper(nums, oddlocs, evenlocs, 1); } else { if(nums[0] == 0) { int[] othernums = Arrays.copyOf(nums, nums.length); return Math.min(solveHelper(nums, evenlocs, oddlocs, 0), solveHelper(othernums, otherodd, othereven, 1)); } else { int[] othernums = Arrays.copyOf(nums, nums.length); return Math.min(solveHelper(nums, oddlocs, evenlocs, 1), solveHelper(othernums, othereven, otherodd, 0)); } } } static int solveHelper(int[] nums, Queue<Integer> startnums, Queue<Integer> others, int parity) { int swaps = 0; int curpar = parity; for(int i = 0; i < nums.length; i++) { if(nums[i] != curpar) { if (nums[i] == parity) { while(others.peek() <= i) { others.poll(); } int needed = others.poll(); swaps += needed - i; nums[needed] = curpar ^ 1; startnums.add(needed); } else { while(startnums.peek() <= i) { startnums.poll(); } int needed = startnums.poll(); swaps += needed - i; nums[needed] = curpar ^ 1; others.add(needed); } } curpar ^= 1; } return swaps; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { this.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
d83af0bb5cbd55d4d2ab890c0b21a823
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.*; public class practice{ public static void main(String[] args){ FastScanner r = new FastScanner(); int t = r.i() ,n,arr[]; boolean st; int od,ev; boolean f; StringBuffer ans = new StringBuffer(""); while(t-->0) { n = r.i(); arr = r.ia(n); od=0; ev=0; for(int x : arr) { if(x%2==1) od++; else ev++; } if(Math.abs(od-ev)>1) { ans.append("-1\n"); continue; } // int odd=0; int even =0 ; int count=0; if(od==ev) { for(int i=0;i<n;i++) { if(arr[i]%2==1) { even += Math.abs(count-i); count+=2; } } count =1; for(int i=0;i<n;i++) { if(arr[i]%2==1) { odd += Math.abs(count-i); count+=2; } } ans.append(Math.min(odd, even ) +"\n"); } else { odd=0; count=0; for(int i=0;i<n;i++) { if(od > ev) { if( arr[i]%2==1) { odd += Math.abs(count-i); count+=2; } } else { if( arr[i]%2==0) { odd += Math.abs(count-i); count+=2; } } } ans.append(odd + "\n"); } } p(ans); } static boolean isPrime(int n) { if(n <=1 )return false; if(n==2) return true; 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 <T> void incrementCount(HashMap<T,Integer> map, T key) { if(map.containsKey(key)) map.put(key, map.get(key) +1); else map.put(key, 1); } 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; } 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; } static <T> void p(T s) { System.out.println(s); } static void p() { System.out.println(); } static <T> void pn(T s) { System.out.print(s); } } 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(); } int[] ia(int n) { int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = i(); return arr; } String[] sa(int n) { String[] arr = new String[n]; for(int i=0;i<n;i++) arr[i] = n(); return arr; } long[] la(int n) { long[] arr = new long[n]; for(int i=0;i<n;i++) arr[i] = l(); return arr; } String nl() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int i() { return Integer.parseInt(n()); } long l() { return Long.parseLong(n()); } }
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
6e96735aadb1fc56e7cef66cf7e6d05c
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 codechef; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class cp_2 { static int mod=(int)1e9+7; // static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); ArrayList<Integer> even=new ArrayList<Integer>(); ArrayList<Integer> odd=new ArrayList<Integer>(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); if((arr[i]&1)==0) even.add(i); else odd.add(i); } if((n&1)==0 && odd.size()!=even.size()) { out.println(-1); continue; } if((n&1)!=0 && Math.abs(odd.size()-even.size())!=1) { out.println(-1); continue; } if((n&1)==0) { int ans=0,ev=0,od=0,max=0; for(int i=0;i<n;i++) { if((i&1)==0) max+=Math.abs(even.get(ev++)-i); } ans=max; max=0; for(int i=0;i<n;i++) { if(((i+1)&1)==1) max+=Math.abs(odd.get(od++)-i); } ans=Math.min(ans, max); out.println(ans); } else { int ans=0,ev=0,od=0; boolean first=true; if(even.size()<odd.size()) first=false; if(first) for(int i=0;i<n;i++) { if((i&1)==0) ans+=Math.abs(even.get(ev++)-i); } else for(int i=0;i<n;i++) { if((i&1)==0) ans+=Math.abs(odd.get(od++)-i); } out.println(ans); } } out.flush(); out.close(); System.gc(); } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void swap(int arr[],int i,int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } static boolean check(String num,String x) { int i=0,pos=0; while(i<num.length() && pos<x.length()) { if(num.charAt(i)==x.charAt(pos)) pos++; i++; } if(pos==x.length()) return true; return false; } static boolean util(int a,int b,int c) { if(b>a)util(b, a, c); while(c>=a) { c-=a; if(c%b==0) return true; } return (c%b==0); } static boolean check(int arr[]) { for (int i = 1; i < arr.length; i++) { if(arr[i-1]>arr[i]) return false; } return true; } static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } static ArrayList<Long> luckNums; static void luckyNum(long x,long p10) { luckNums.add(x); if(x>(long)1e10) return; luckyNum(x+4*p10, p10*10); luckyNum(x+7*p10, p10*10); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> it = set.iterator(); while(it.hasNext()) { int x=it.next(); } */ static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static int LowerBound(int a[], int x) { // x is the target value or key 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; } static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } 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; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // if ranks are the same { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } // static class countClass{ // int cnt; // public countClass() { // this.cnt=0; // // TODO Auto-generated constructor stub // } // } static class Graph { int v; ArrayList<Integer> list[]; Graph(int v) { this.v=v; list=new ArrayList[v+1]; for(int i=1;i<=v;i++) list[i]=new ArrayList<Integer>(); } void addEdge(int a, int b) { this.list[a].add(b); } } // static class GraphMap{ // Map<String,ArrayList<String>> graph; // GraphMap() { // // TODO Auto-generated constructor stub // graph=new HashMap<String,ArrayList<String>>(); // // } // void addEdge(String a,String b) // { // if(graph.containsKey(a)) // this.graph.get(a).add(b); // else { // this.graph.put(a, new ArrayList<>()); // this.graph.get(a).add(b); // } // } // } // static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok) // { // vis.add(src); // // if(g.graph.get(src)!=null) // { // for(String each:g.graph.get(src)) // { // if(!vis.contains(each)) // { // dfsMap(g, vis, each, ok+1); // } // } // } // // cnt=Math.max(cnt, ok); // } static double sum[]; static double cnt; static void DFS(Graph g, boolean[] visited, int u,double path) { visited[u]=true; sum[u]=0; int k=0; for(int i=0;i<g.list[u].size();i++) { int v=g.list[u].get(i); if(!visited[v]) { DFS(g, visited, v,path+1); sum[u]+=sum[v]; k++; } } if(k!=0) sum[u]=sum[u]/(double)k +1; } static class Pair { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } 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); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } 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 class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } 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(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; }
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
819098bffeb82462cb9034a32f1680c8
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.*; public class C { static long dfs(int source, int parent, long x, ArrayList<ArrayList<Integer>> adj, long[] arr) { long s = arr[source]; for (Integer i : adj.get(source)) { if (i != parent) { s += dfs(i, source, x, adj, arr); } } return Math.max(s, -x); } 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 gcd(long n, long m) { if (m == 0) return n; return gcd(m, n % m); } static long lcm(long n, long m) { return (n * m) / gcd(n, m); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } static StringBuilder str = new StringBuilder(); public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); int[] arr = new int[n]; 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) even.add(i); else odd.add(i); } if (Math.abs(even.size() - odd.size()) > 1) { str.append(-1 + "\n"); continue; } long s = 0; if (even.size() == odd.size()) { int j = 1; long s1 = 0; for (int i : even) { s1 += Math.abs(j - i); j += 2; } long s2 = 0; j = 1; for (int i : odd) { s2 += Math.abs(j - i); j += 2; } s = Math.min(s1, s2); } else { int j = 1; if (even.size() < odd.size()) { for (int i : even) { s += Math.abs(j - i); j += 2; } } else { for (int i : odd) { s += Math.abs(j - i); j += 2; } } } str.append(s + "\n"); } System.out.println(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
0815edab1b2ea3e7a9212e5fb2c80f10
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 java.util.*; import java.io.*; import java.math.*; public class B_Take_Your_Places { public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = f.nextInt(); while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); int[] arr = new int[n]; int count0 = 0; int count1 = 0; for(int i = 0; i < n; i++) { arr[i] = f.nextInt()%2; if(arr[i] == 0) { count0++; } else { count1++; } } if(abs(count1-count0) > 1) { out.println(-1); return; } if(n%2 == 0) { int arr2[] = new int[n]; for(int i = 0; i < n; i++) { arr2[i] = arr[i]; } long a = func(arr, 0); long b = func(arr2, 1); long ans = min(a, b); out.println(ans); } else { int curr = -1; if(count0 > count1) { curr = 0; } else { curr = 1; } out.println(func(arr, curr)); } } public static long func(int arr[], int curr) { int n = arr.length; long total = 0; int ind1 = 0; int ind0 = 0; for(int i = 0; i < n; i++) { while(ind0 < n && arr[ind0] != 0) { ind0++; } while(ind1 < n && arr[ind1] != 1) { ind1++; } if(curr == arr[i]) { if(curr == 1) { ind1++; } else { ind0++; } } else { if(curr == 0) { total += abs(ind0-i); arr[i] = 0; arr[ind0] = 1; ind0++; } else { total += abs(ind1-i); arr[i] = 1; arr[ind1] = 0; ind1++; } } curr = (curr+1)%2; } return total; } public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } public static int gcd(int a, int b) { int dividend = a > b ? a : b; int divisor = a < b ? a : b; while(divisor > 0) { int reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } public static int lcm(int a, int b) { int lcm = gcd(a, b); int hcf = (a * b) / lcm; return hcf; } public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } 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()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */
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
cd679cf8509e5ca93c64ec00c80d77e8
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 void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int arr[] = new int[n]; Arrays.setAll(arr, i-> sc.nextInt()); int copy[] = new int[n]; int odc = 0; int evc = 0; for(int i = 0; i < n; i++) { copy[i] = arr[i]; if(arr[i]%2==0)evc++; else odc++; } if(n%2==0) { if(odc != evc)writer.println(-1); else writer.println(Math.min(eveodd(arr), oddeve(copy))); }else { if(Math.abs(odc - evc) != 1)writer.println(-1); else { if(odc>evc)writer.println(oddeve(copy)); else writer.println(eveodd(arr)); } } } writer.flush(); writer.close(); } static int eveodd(int arr[]) { int ans = 0; int n = arr.length; int ind = -1; for(int i = 0; i < n;i++) { if(i%2==0) { if(arr[i]%2!=0) { ind = Math.max(ind, i+1); while(ind<n && arr[ind]%2 != 0)ind++; if(ind < n) { swapValue(arr, ind, i); ans += ind-i; }else return ans; } }else { if(arr[i]%2!=1) { ind = Math.max(ind, i+1); while(ind<n && arr[ind]%2 != 1)ind++; if(ind < n) { swapValue(arr, ind, i); ans += ind-i; }else return ans; } } } return ans; } static int oddeve(int arr[]) { int ans = 0; int n = arr.length; int ind = -1; for(int i = 0; i < n;i++) { if(i%2==0) { if(arr[i]%2!=1) { ind = Math.max(ind, i+1); while(ind<n && arr[ind]%2 != 1)ind++; if(ind < n) { swapValue(arr, ind, i); ans += ind-i; }else return ans; } }else { if(arr[i]%2!=0) { ind = Math.max(ind, i+1); while(ind<n && arr[ind]%2 != 0)ind++; if(ind < n) { swapValue(arr, ind, i); ans += ind-i; }else return ans; } } } return ans; } static void swapValue(int arr[], int eve, int od) { if(eve<arr.length && od<arr.length) { int temp = arr[eve]; arr[eve] = arr[od]; arr[od] = temp; } } private static long power (long a, long n, long p) { long res = 1; while(n!=0) { if(n%2==1) { res=(res*a)%p; n--; }else { a= (a*a)%p; n/=2; } } return res; } private static boolean isPrime(int c) { for (int i = 2; i*i <= c; i++) { if(c%i==0)return false; } return true; } private static int find(int a , int arr[]) { if(arr[a] != a) return arr[a] = find(arr[a], arr); return arr[a]; } private static void union(int a, int b, int arr[]) { int aa = find(a,arr); int bb = find(b, arr); arr[aa] = bb; } private static long gcd(long a, long b) { if(a==0)return b; return gcd(b%a, a); } public static int[] readIntArray(int size, FastReader s) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = s.nextInt(); } return array; } 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; } } } class Pair implements Comparable<Pair>{ long a; long b; Pair(long a, long b){ this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || obj.getClass()!= this.getClass()) return false; Pair pair = (Pair) obj; return (pair.a == this.a && pair.b == this.b); } @Override public int hashCode() { return Objects.hash(a,b); } @Override public int compareTo(Pair o) { if(this.a == o.a) { return Long.compare(this.b, o.b); }else { return Long.compare(this.a, o.a); } } @Override public String toString() { return this.a + " " + 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 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
c3aeb81e186e8d1ad7130b600efd8cd9
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
/*LoudSilence*/ import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ static FastScanner s = new FastScanner(); static FastWriter out = new FastWriter(); final static int mod = (int)1e9 + 7; final static int INT_MAX = Integer.MAX_VALUE; final static int INT_MIN = Integer.MIN_VALUE; final static long LONG_MAX = Long.MAX_VALUE; final static long LONG_MIN = Long.MIN_VALUE; final static double DOUBLE_MAX = Double.MAX_VALUE; final static double DOUBLE_MIN = Double.MIN_VALUE; final static float FLOAT_MAX = Float.MAX_VALUE; final static float FLOAT_MIN = Float.MIN_VALUE; /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ static class FastScanner{BufferedReader br;StringTokenizer st; public FastScanner() {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());} List<Integer> readIntList(int n){List<Integer> arr = new ArrayList<>(); for(int i = 0; i < n; i++) arr.add(s.nextInt()); return arr;} List<Long> readLongList(int n){List<Long> arr = new ArrayList<>(); for(int i = 0; i < n; i++) arr.add(s.nextLong()); return arr;} int[] readIntArr(int n){int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = s.nextInt(); return arr;} long[] readLongArr(int n){long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = s.nextLong(); return arr;} String nextLine(){String str = "";try{str = br.readLine();}catch (IOException 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 debug(int object[]) throws IOException{bw.append("["); for(int i = 0; i < object.length; i++){if(i != object.length-1){print(object[i]+", ");}else{print(object[i]);}}bw.append("]\n");} public void debug(long object[]) throws IOException{bw.append("["); for(int i = 0; i < object.length; i++){if(i != object.length-1){print(object[i]+", ");}else{print(object[i]);}}bw.append("]\n");} public void close() throws IOException{bw.close();}} /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ public static ArrayList<Integer> seive(int n){ArrayList<Integer> list = new ArrayList<>();int arr[] = new int[n+1];for(int i = 2; i <= n; i++) {if(arr[i] == 1) {continue;}else {list.add(i);for(int j = i*i; j <= n; j = j + i) {arr[j] = 1;}}}return list;} 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 void swap(int[] arr, int i, int j) {arr[i] = arr[i] ^ arr[j]; arr[j] = arr[j] ^ arr[i]; arr[i] = arr[i] ^ arr[j];} 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 mod_add(long a, long b){ return (a%mod + b%mod)%mod;} public static long mod_sub(long a, long b){ return (a%mod - b%mod + mod)%mod;} public static long mod_mul(long a, long b){ return (a%mod * b%mod)%mod;} public static long modInv(long a, long b){ return expo(a, b-2)%b;} public static long mod_div(long a, long b){return mod_mul(a, modInv(b, mod));} public static long expo (long a, long n){if(n == 0){return 1;}long recAns = expo(mod_mul(a,a), n/2);if(n % 2 == 0){return recAns;}else{return mod_mul(a, recAns);}} /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ // Pair class public static class Pair<X extends Comparable<X>,Y extends Comparable<Y>> implements Comparable<Pair<X, Y>>{ X first; Y second; public Pair(X first, Y second){ this.first = first; this.second = second; } public String toString(){ return "( " + first+" , "+second+" )"; } @Override public int compareTo(Pair<X, Y> o) { int t = first.compareTo(o.first); if(t == 0) return second.compareTo(o.second); return t; } } /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ // Code begins public static void solve() throws IOException { int n = s.nextInt(); int arr[] = s.readIntArr(n); if(n == 1){ out.println(0); return; } List<Pair<Integer, Integer>> e = new ArrayList<>(); List<Pair<Integer, Integer>> o = new ArrayList<>(); for(int i = 0; i < n; i++){ int ele = arr[i]; if((ele & 1) == 1) o.add(new Pair<>(ele, i)); else e.add(new Pair<>(ele, i)); } for(int ele : arr){ } if((n&1) == 1){ // Odd if(abs(o.size() - e.size()) > 1){ out.println(-1); return; } List<Pair<Integer, Integer>> ans = new ArrayList<>(); int ei = 0; int oi = 0; boolean even = false; if(e.size() > o.size()){ even = true; } for(int i = 0; i < n; i++){ if(even){ ans.add(e.get(ei)); ei++; even = !even; }else{ ans.add(o.get(oi)); oi++; even = !even; } } long op = 0; for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans.get(i); if(p.first % 2 == 1){ op += abs(p.second - i); } } out.println(op); }else{ // Even if(e.size() != o.size()){ out.println(-1); return; }else{ List<Pair<Integer, Integer>> ans1 = new ArrayList<>(); List<Pair<Integer, Integer>> ans2 = new ArrayList<>(); int ei = 0; int oi = 0; boolean even = true; for(int i = 0; i < n; i++){ if(even){ ans1.add(e.get(ei)); ei++; even = !even; }else{ ans1.add(o.get(oi)); oi++; even = !even; } } ei = 0; oi = 0; even = false; for(int i = 0; i < n; i++){ if(even){ ans2.add(e.get(ei)); ei++; even = !even; }else{ ans2.add(o.get(oi)); oi++; even = !even; } } long op1 = 0; long op2 = 0; for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans1.get(i); if(p.first % 2 == 1){ op1 += abs(p.second - i); } } for(int i = 0; i < n; i++){ Pair<Integer, Integer> p = ans2.get(i); if(p.first % 2 == 1){ op2 += abs(p.second - i); } } out.println(min(op1, op2)); } } } /*----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ public static void main(String[] args) throws IOException { int test = s.nextInt(); for(int tt = 1; tt <= test; tt++) { solve(); } 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
2c9462de6a6b602988d1d239a27b40c0
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 void main(String[] args) throws IOException { try { int t = sc.nextInt(); while (t-- > 0) solve(); } catch (Exception e) { return; } out.flush(); } // SOLUTION STARTS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static void solve() { int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt() % 2; } int c[] = { 0, 0 }; for (int i : a) c[i % 2]++; if (n == 1) { System.out.println(0); return; } if (Math.abs(c[0] - c[1]) > 1) { System.out.println(-1); return; } if (n % 2 == 0) { if (c[0] == c[1]) { System.out.println(Math.min(get(0, a), get(1, a))); return; } System.out.println(-1); } else { if (c[0] == c[1] + 1) { System.out.println(get(0, a)); } else if (c[1] == c[0] + 1) { System.out.println(get(1, a)); } else { System.out.println(-1); } } } static int get(int start, int a[]) { int d = 0, ans = 0; for (int i = 0; i < a.length; i++) { if (a[i] == 0 && start == 1) { d++; } else if (a[i] == 1 && start == 0) { d--; } ans += Math.abs(d); start ^= 1; } return ans; } // SOLUTION ENDS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static class DSU { int rank[]; int parent[]; DSU(int n) { rank = new int[n + 1]; parent = new int[n + 1]; for (int i = 1; i <= n; i++) { parent[i] = i; } } int findParent(int node) { if (parent[node] == node) return node; return parent[node] = findParent(parent[node]); } boolean union(int x, int y) { int px = findParent(x); int py = findParent(y); if (px == py) return false; if (rank[px] < rank[py]) { parent[px] = py; } else if (rank[px] > rank[py]) { parent[py] = px; } else { parent[px] = py; rank[py]++; } return true; } } 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); } static boolean[] seiveOfEratosthenes(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } return isPrime; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static boolean isPrime(long n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } 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()); } char[][] readCharMatrix(int n, int m) { char a[][] = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } return a; } long nextLong() { return Long.parseLong(next()); } int[] readIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } void printIntArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } long[] readLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(next()); } return a; } void printLongArray(long a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } 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(); } } private static final FastReader sc = new FastReader(); private static final FastWriter out = new FastWriter(System.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 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
ddd2a518160581928c98b158389214ea
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 void main(String[] args) throws IOException { try { int t = sc.nextInt(); while (t-- > 0) solve(); } catch (Exception e) { return; } out.flush(); } // SOLUTION STARTS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static void solve() { int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt() % 2; } int c[] = { 0, 0 }; for (int i : a) c[i % 2]++; if (n == 1) { System.out.println(0); return; } if (Math.abs(c[0] - c[1]) > 1) { System.out.println(-1); return; } if (n % 2 == 0) { if (c[0] == c[1]) { System.out.println(Math.min(get(0, a), get(1, a))); return; } System.out.println(-1); } else { if (c[0] == c[1] + 1) { System.out.println(get(0, a)); } else if (c[1] == c[0] + 1) { System.out.println(get(1, a)); } else { System.out.println(-1); } } } static int get(int start, int a[]) { int d = 0, ans = 0; for (int i = 0; i < a.length; i++) { if (a[i] == 0 && start == 1) { d--; } else if (a[i] == 1 && start == 0) { d++; } ans += Math.abs(d); start ^= 1; } return ans; } // SOLUTION ENDS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static class DSU { int rank[]; int parent[]; DSU(int n) { rank = new int[n + 1]; parent = new int[n + 1]; for (int i = 1; i <= n; i++) { parent[i] = i; } } int findParent(int node) { if (parent[node] == node) return node; return parent[node] = findParent(parent[node]); } boolean union(int x, int y) { int px = findParent(x); int py = findParent(y); if (px == py) return false; if (rank[px] < rank[py]) { parent[px] = py; } else if (rank[px] > rank[py]) { parent[py] = px; } else { parent[px] = py; rank[py]++; } return true; } } 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); } static boolean[] seiveOfEratosthenes(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } return isPrime; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static boolean isPrime(long n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } 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()); } char[][] readCharMatrix(int n, int m) { char a[][] = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } return a; } long nextLong() { return Long.parseLong(next()); } int[] readIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } void printIntArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } long[] readLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(next()); } return a; } void printLongArray(long a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } 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(); } } private static final FastReader sc = new FastReader(); private static final FastWriter out = new FastWriter(System.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 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
67815d27b18d270e4b6ca4b58a32699d
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.*; public class Test { public static void main(String[] args) { FastReader fastReader = new FastReader(); int t = fastReader.nextInt(); while (t-- > 0) { int n = fastReader.nextInt(); int[] a = new int[n]; int oddC = 0, evenC = 0; for (int i = 0; i < n; i++) { a[i] = fastReader.nextInt(); if ((a[i] & 1) == 1) { oddC++; } else { evenC++; } } if (n == 1) { System.out.println(0); } else if (Math.abs(oddC - evenC) > 1) System.out.println(-1); else { StringBuilder temp = new StringBuilder(""); for (int c : a) { if ((c & 1) == 1) { temp.append('1'); } else { temp.append('0'); } } int f; int ans = (int)Integer.MAX_VALUE; if (oddC > evenC){ StringBuilder comp1 = new StringBuilder(""); f = 1; for (int i = 0; i < n; i++) { if (f == 1) { comp1.append('1'); f = 0; } else { comp1.append('0'); f = 1; } } ans = Math.min(ans, check(temp.toString(),comp1.toString())); }else if (evenC > oddC){ StringBuilder comp2 = new StringBuilder(""); f = 0; for (int i = 0; i < n; i++) { if (f == 1) { comp2.append('1'); f = 0; } else { comp2.append('0'); f = 1; } } ans = Math.min(ans, check(temp.toString(),comp2.toString())); }else{ StringBuilder comp2 = new StringBuilder(""); f = 0; for (int i = 0; i < n; i++) { if (f == 1) { comp2.append('1'); f = 0; } else { comp2.append('0'); f = 1; } } ans = Math.min(ans, check(temp.toString(),comp2.toString())); comp2.reverse(); ans = Math.min(ans, check(temp.toString(),comp2.toString())); } System.out.println(ans); } } } public static int check(String a, String b) { int cnt = 0, n = a.length(); ArrayList<Integer> l1= new ArrayList<>(), l2 = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a.charAt(i) != b.charAt(i)) { if (((a.charAt(i) - '0') & 1) == 1){ l1.add(i); }else{ l2.add(i); } } } int q = l1.size() , p = l2.size(); Collections.sort(l1); Collections.sort(l2); for (int i = 0 ; i < Math.min(q,p) ; i++){ cnt+= Math.abs(l1.get(i) - l2.get(i)); } return cnt; } static int solve(String a, String b) { int ans = 0; int index1 = 0, index2 = 0; while (index1 < a.length() && index2 < b.length()) { if (a.charAt(index1) != b.charAt(index2)) { index1++; } else { ans++; index1++; index2++; } } return (a.length() - ans) + (b.length() - ans); } 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 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
bb3c682d2b3b2c53c149b5beeda426d1
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 { //----------- StringBuilder for faster output------------------------------ static StringBuilder out = new StringBuilder(); static int cnt = 0; public static void main(String[] args) { FastScanner fs=new FastScanner(); /****** CODE STARTS HERE *****/ int t = fs.nextInt(); while(t-->0) { int n = fs.nextInt(); int[] a = new int[n]; int[] cnt = new int[2]; for(int i=0; i<n; i++) { if((fs.nextInt()&1) == 0) a[i]=0; else a[i] = 1; cnt[a[i]]++; } int min = Integer.MAX_VALUE; if(Math.abs(cnt[0]-cnt[1]) > 1) { out.append("-1\n"); continue; } else if(cnt[0] > cnt[1]) { min = swaps_req(a, 0); } else if(cnt[0] < cnt[1]) { min = swaps_req(a, 1); } else { min = swaps_req(a.clone(), 1); min = Math.min(min, swaps_req(a, 0)); } out.append(min+"\n"); } System.out.println(out); } static int swaps_req(int[] a, int s) { //s -> Starting parity int i=0, j=1, n=a.length, swaps=0; while(j<n) { int p;//change parity for next position if(i%2==0)p=s; else p=Math.abs(s-1); if(a[i]==p) {i++;j++;} else { if(j>=n)break; while(a[j]!=p)j++; swaps += j-i; int temp = a[i]; a[i] = a[j]; a[j] = temp; i+=2;j++; if(j<=i)j=i+1; } } return swaps; } 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); } //----------- FastScanner class for faster input--------------------------- 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()); } } }
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
1f71ac5cc18b967a81296e32483ed1bf
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 in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(), ones = 0, x = 1, a = 0, b = 0; // 0 0 0 1 1 1 // for (int i = 1; i <= n; i++) { int mod = in.nextInt() % 2; ones += mod; if (mod == 1) { a += Math.abs(i - 1 - x); b += Math.abs(i - x); x += 2; } } if (Math.abs(n - 2 * ones) > 1) System.out.println(-1); else if (n % 2 == 0) System.out.println(Math.min(a, b)); else if (n - ones > ones) System.out.println(a); else System.out.println(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 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
10b2cec17eda7e0dcd8485bd21378f8f
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 file{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int t = scan.nextInt(); // scan.nextLine(); for(int x = 1;x <= t;x++) { int n = scan.nextInt(); int arr[] = new int[n]; int even = 0, odd = 0; for(int i = 0;i < n;i++) { arr[i] = scan.nextInt(); if(arr[i] % 2 == 0) { even++; }else { odd++; } } if(Math.abs(odd - even) > 1) { System.out.println("-1"); }else if(odd == even) { int index = 0, index1 = 1, ans = 0,ans1 = 0; for(int i = 0;i < n;i++) { if(arr[i] % 2 == 1) { ans += Math.abs(index - i); ans1 += Math.abs(index1 - i); index += 2; index1 += 2; } } ans = Math.min(ans, ans1); System.out.println(ans); }else if(odd > even) { int index = 0, ans = 0; for(int i = 0;i < n;i++) { if(arr[i] % 2 == 1) { ans += Math.abs(index - i); index += 2; } } System.out.println(ans); }else { int index = 0, ans = 0; for(int i = 0;i < n;i++) { if(arr[i] % 2 == 0) { ans += Math.abs(index - i); index += 2; } } 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 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
8a5c3d14d4cb6abae62b863d2b8a9b11
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.text.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int ar[] = new int[n], odd = 0, even = 0; Queue<Integer> qo = new LinkedList<Integer>(), qe = new LinkedList<Integer>(); for(int i = 0; i < n; i++){ ar[i] = Integer.parseInt(st.nextToken())&1; odd += ar[i]; if(ar[i] == 1) qo.offer(i); else qe.offer(i); } // System.out.println(Arrays.toString(ar)); even = n - odd; if(Math.abs(even - odd) > 1) sb.append(-1); else{ if(even == odd) sb.append(Math.min(findSwaps(new LinkedList(qe), n, ar), findSwaps(new LinkedList(qo), n, ar))); else if(even > odd) sb.append(findSwaps(qe, n, ar)); else sb.append(findSwaps(qo, n, ar)); } sb.append("\n"); } System.out.print(sb); } public static long findSwaps(Queue<Integer> qe, int n, int ar[]){ long swaps = 0; for(int i = 0; i < n; i+=2) swaps += Math.abs(qe.poll() - i); return swaps; } }
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
14f8207fefaf31f557b61c1d56547855
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.StringTokenizer; public class Solver { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); new TaskA().solveB(in, out); out.close(); } static class TaskA { public void solveA(FastReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int a = in.nextInt(); int b = in.nextInt(); out.println(((a % 2 != b % 2) ? -1 : (a == b) ? (a == 0 ? 0 : 1) : 2)); } } public void solveB(FastReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { boolean correct = true; int n = in.nextInt(); int[] array = in.nextIntArray(n); int evenCount = 0; for (int arrayItem : array) if (arrayItem % 2 == 0) evenCount++; if (evenCount != array.length / 2 && (n - evenCount) != array.length / 2) correct = false; if (!correct) { out.println(-1); } else if (evenCount == n - evenCount) { long count1 = getCount(array, 1); long count2 = getCount(array, 0); out.println(Math.min(count1, count2)); } else { int remainder = evenCount > n - evenCount ? 0 : 1; long count = getCount(array, remainder); out.println(count); } } } private long getCount(int[] array, int remainder) { long count = 0, x = 0, y = 1; for (int i = 0; i < array.length; i++) { if (array[i] % 2 == remainder) { count += Math.abs(x - i); x += 2; } else { count += Math.abs(y - i); y += 2; } } return count / 2; } public void solveC(FastReader in, PrintWriter out) { } public void solveD(FastReader in, PrintWriter out) { } public void solveE(FastReader in, PrintWriter out) { } } private static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } private static long lcm(long a, long b) { return (a * b) / gcd(a, b); } private static int min(int a, int b) { return a < b ? a : b; } private static int max(int a, int b) { return a > b ? a : b; } private static int min(ArrayList<Integer> list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(ArrayList<Integer> list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static int min(int[] list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(int[] list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static void fill(int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } } }
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
c08535cb5193b37a3f6486d9a7a83632
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 in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(), ones = 0, x = 1, a = 0, b = 0; // 0 0 0 1 1 1 // for (int i = 1; i <= n; i++) { int mod = in.nextInt() % 2; ones += mod; if (mod == 1) { a += Math.abs(i - 1 - x); b += Math.abs(i - x); x += 2; } } if (Math.abs(n - 2 * ones) > 1) System.out.println(-1); else if (n % 2 == 0) System.out.println(Math.min(a, b)); else if (n - ones > ones) System.out.println(a); else System.out.println(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 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
e7a71ec73bd7b256402c4396b0649b92
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.*; import java.lang.*; public class problemB{ public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); for(int j=0;j<t;j++){ int n=Integer.parseInt(br.readLine()); String[]input=br.readLine().split(" "); StringBuilder sb=new StringBuilder(); StringBuilder zero=new StringBuilder(); StringBuilder one=new StringBuilder(); int c0=0,c1=0; for(int i=0;i<n;i++){ int val=Integer.parseInt(input[i])%2; sb.append(val); if(val==0) c0++; else c1++; if(i%2==0){ zero.append(0); one.append(1); }else{ zero.append(1); one.append(0); } } int diff=(int)Math.abs(c0-c1); if((n%2==0&&diff!=0)||(n%2!=0&&diff!=1)) System.out.println(-1); else{ if(n%2==0) System.out.println(Math.min(minimumSwaps(sb,one),minimumSwaps(sb,zero))); else{ if(c0>c1) System.out.println(minimumSwaps(sb,zero)); else System.out.println(minimumSwaps(sb,one)); } } } } public static int minimumSwaps(StringBuilder sb,StringBuilder s){ List<Integer>zeroes=new ArrayList<>(); List<Integer>ones=new ArrayList<>(); for(int i=0;i<sb.length();i++){ if(sb.charAt(i)!=s.charAt(i)){ if(sb.charAt(i)=='1') ones.add(i); else zeroes.add(i); } } int ans=0; Collections.sort(zeroes); Collections.sort(ones); for(int i=0;i<Math.min(zeroes.size(),ones.size());i++){ ans+=(int)Math.abs(zeroes.get(i)-ones.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 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
245fb7250966c0805e2f6b0757e39f7e
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 Sol{ /* ->check n=1, int overflow , array bounds , all possibilites(dont stuck on 1 approach) ->Problem = Observation(constraints(m<=n/3 or k<=min(100,n)) + Thinking + Technique (seg_tree,binary lift,rmq,bipart,dp,connected comp etc) ->solve or leave it (- tutorial improves you in minimal way -) */ public static void main (String []args) { //precomp(); int times=ni();while(times-->0){solve();}out.close();} static void solve(){ int n=ni(); int a[]=new int[n]; int c[]=new int[2]; for(int i=0;i<n;i++){a[i]=ni()%2;c[a[i]]++;} if( c[1]-c[0]>1 || c[0]-c[1]>1 ){out.println(-1);return;} long ans=(long)Math.pow(10,18); if(c[0]>=c[1]){ //Case 1 0-> odd int b[]=new int[n]; int i=1;int j=2; for(int k=0;k<n;k++){if(a[k]==0){b[k]=i;i+=2;}else {b[k]=j;j+=2;}} ans=Math.min(ans,Inv(b,0,n-1)); } //Case 2 0->even if(c[1]>=c[0]){ int i=2;int j=1; int d[]=new int[n]; for(int k=0;k<n;k++){if(a[k]==0){d[k]=i;i+=2;}else{d[k]=j;j+=2;}} ans=Math.min(ans,Inv(d,0,n-1)); } out.println(ans); return; } static long Inv(int a[],int l,int r){ long count=0; if(l<r){ int mid=(l+r)/2; count+=Inv(a,l,mid);count+=Inv(a,mid+1,r); count+=mergeInv(a,l,mid,r); } return count; } static long mergeInv(int a[],int l,int mid,int r){ long swaps=0l; int left[]=Arrays.copyOfRange(a,l,mid+1);int right[]=Arrays.copyOfRange(a,mid+1,r+1); int i=0;int j=0;int k=l; while(i<left.length && j<right.length){ if(left[i]<=right[j])a[k++]=left[i++]; else{ swaps+=(mid-(l+i-1)); a[k++]=right[j++]; } } while(i<left.length)a[k++]=left[i++]; while(j<right.length)a[k++]=right[j++]; return swaps; } //-----------------Utility-------------------------------------------- static long gcd(long a,long b){if(b==0)return a; return gcd(b,a%b);} static int Max=Integer.MAX_VALUE; static long mod=1000000007; //static int v(char c){return (int)(c-'a');} public static long power(long x, long y ) { //0^0 = 1 long res = 1L; x = x%mod; while(y > 0) { if((y&1)==1) res = (res*x)%mod; y >>= 1; x = (x*x)%mod; } return res; } static class Pair implements Comparable<Pair>{ int id;int value;Pair next; public Pair(int id,int value) { this.id=id;this.value=value;next=null; } @Override public int compareTo(Pair p){return Long.compare(value,p.value);} } //----------------------I/O--------------------------------------------- static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static FastReader in=new FastReader(inputStream); static PrintWriter out=new PrintWriter(outputStream); static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public 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()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } /*static int ni() { try { boolean in = false; int res = 0; for (;;) { int b = System.in.read() - '0'; if (b >= 0) { in = true; res = 10 * res + b; } else if (in) return res; } } catch (IOException e) { throw new Error(e); } }*/ static int ni(){return in.nextInt();} static long nl(){return in.nextLong();} static double nd(){return in.nextDouble();} static String ns(){return in.nextLine();} }
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
a10b35afb730f94ef57b29d04707bd66
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.List; /* for i in range(int(input())): n = int(input());l = list(map(int, input().split()));c = 0;c1 = 0;d = 0;d1 = 0; for j in l: if j % 2 == 0:c1 += abs(d - c);c += 1 else:d1 += abs(c - d);d += 1 if abs(c - d) > 1:print(-1) else: if c > d:print(c1) elif d > c:print(d1) else:print(min(c1, d1)) */ public class Main2 { public static void main(String[] args) { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); List<Integer> list = new ArrayList<>(); for(int i = 0; i < n; i++) { list.add(in.nextInt()); } int even = 0; int odd = 0; int evenResult = 0; int oddResult = 0; for(Integer num : list) { if(num % 2 == 0) { evenResult += Math.abs(even - odd); even++; } else { oddResult += Math.abs(odd - even); odd++; } } if(Math.abs(even - odd) > 1) { pw.println(-1); continue; } /* if c > d:print(c1) elif d > c:print(d1) else:print(min(c1, d1)) */ if(even > odd) { pw.println(evenResult); } else if(odd > even) { pw.println(oddResult); } else { pw.println(Math.min(evenResult, oddResult)); } } pw.close(); } static class FastReader { private final int BS = 1 << 16; private final char NC = (char) 0; private final byte[] buf = new byte[BS]; private final BufferedInputStream in; private int bId = 0; private int size = 0; private char c = NC; private double cnt = 1; public FastReader(InputStream is) { in = new BufferedInputStream(is, 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 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 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 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
e303a16f41f68c88911a2e29a2db4e7e
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
// Problem: Take Your Places! // https://codeforces.com/contest/1556/problem/B // This submission: // // The problem only cares about parity of the input elements, so we can consider all input values // under (mod 2). // Then, we are given an array of `0`s and `1`s and want to swap adjacent elements to make an array // with alternating `0`s and `1`s. There are only two possible final arrays, starting with a `0` or // a `1`. The positions of `0`s for the two choices are provided by `even` (starting with `0`) and // `odd` (starting with `1`). // Note that we will never swap two adjacent `0`s or two adjacent `1`s. So, the i-th `0` from the // original array must be the i-th `0` in the final array. import java.util.*; public class TakeYourPlaces { // 10^18 private static final long oo = 1_000_000_000_000_000_000L; // Returns the cost (number of swaps) of putting all zeros at positions in `a` to their desired // positions in `b`. This is the sum of absolute differences of corresponding positions in `a` // and `b`. // The input lists `a` and `b` are both sorted in ascending order. private static long cost(List<Integer> a, List<Integer> b) { if (a.size() != b.size()) { return oo; } long sum = 0; for (int i = 0; i < a.size(); ++i) { sum += Math.abs(a.get(i) - b.get(i)); } return sum; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCasesCount = in.nextInt(); for (int testCase = 1; testCase <= testCasesCount; ++testCase) { // The indexes of positions of even numbers in the input. List<Integer> positions = new ArrayList<>(); List<Integer> even = new ArrayList<>(); List<Integer> odd = new ArrayList<>(); int n = in.nextInt(); for (int i = 0; i < n; ++i) { int x = in.nextInt(); if (x % 2 == 0) { positions.add(i); } if (i % 2 == 0) { even.add(i); } else { odd.add(i); } } long cost = Math.min(cost(positions, even), cost(positions, odd)); System.out.println(cost < oo ? cost : -1); } in.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
9e9b1bad4fc7c919b68890846339ede4
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
// Problem: Take Your Places! // https://codeforces.com/contest/1556/problem/B // This submission: import java.util.*; public class TakeYourPlaces { // 10^18 private static final long oo = 1_000_000_000_000_000_000L; // Returns the cost of putting all zeros at positions in `a` to their desired positions in `b`. // This is the sum of absolute differences of corresponding positions in `a` and `b`. private static long cost(List<Integer> a, List<Integer> b) { if (a.size() != b.size()) { return oo; } long sum = 0; for (int i = 0; i < a.size(); ++i) { sum += Math.abs(a.get(i) - b.get(i)); } return sum; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCasesCount = in.nextInt(); for (int testCase = 1; testCase <= testCasesCount; ++testCase) { // The index of positions of even numbers in the input. List<Integer> positions = new ArrayList<>(); List<Integer> even = new ArrayList<>(); List<Integer> odd = new ArrayList<>(); int n = in.nextInt(); for (int i = 0; i < n; ++i) { int x = in.nextInt(); if (x % 2 == 0) { positions.add(i); } if (i % 2 == 0) { even.add(i); } else { odd.add(i); } } long cost = Math.min(cost(positions, even), cost(positions, odd)); System.out.println(cost < oo ? cost : -1); } in.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
f89428e53ab7d99ee12553c9fda05757
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.BufferedReader; import java.io.InputStreamReader; import java.util.*; 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); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static int findMax(int a[], int n, int vis[], int i, int d){ if(i>=n) return 0; if(vis[i]==1) return findMax(a, n, vis, i+1, d); int max = 0; for(int j=i+1;j<n;j++){ if(Math.abs(a[i]-a[j])>d||vis[j]==1) continue; vis[j] = 1; max = Math.max(max, 1 + findMax(a, n, vis, i+1, d)); vis[j] = 0; } return max; } static void findSub(ArrayList<ArrayList<Integer>> ar, int n, ArrayList<Integer> a, int i){ if(i==n){ ArrayList<Integer> b = new ArrayList<Integer>(); for(int y:a){ b.add(y); } ar.add(b); return; } for(int j=0;j<n;j++){ if(j==i) continue; a.set(i,j); findSub(ar, n, a, i+1); } } public static void solve(InputReader sc, PrintWriter pw){ int t=sc.nextInt(); // int t=1; while(--t>=0){ int n=sc.nextInt(); int a[]=new int[n]; int c=0,e=0; for(int i=0;i<n;i++){ if((sc.nextInt()&1)==0){ a[e++]=i; } } if(e!=n/2&&e!=(n+1)/2){ pw.println(-1); continue; } long a1=0,a2=0; for(int i=0;i<e;i++){ a1+=Math.abs(a[i] - 2*i); a2+=Math.abs(a[i] - 2*i -1); } pw.println((n&1)==0?Math.min(a1,a2):e==n/2?a2:a1); } } static void assignAnc(ArrayList<Integer> ar[],int sz[], int pa[] ,int curr, int par){ sz[curr] = 1; pa[curr] = par; for(int v:ar[curr]){ if(par==v) continue; assignAnc(ar, sz, pa, v, curr); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static class Pair implements Comparable<Pair> { int a; int b; // int c; Pair(int a, int b) { this.a = a; this.b = b; // this.c = c; } public int compareTo(Pair p) { // if(a!=p.a) // return a-p.a; return b-p.b; // return p.c - c; } } 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; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); 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[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } 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
e68e5a69c02a401913e892f784b20e25
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 TakeYourPlaces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); long a[] = new long[n]; int oddC = 0; int evenC = 0; for(int i = 0; i < n; i++){ a[i] = sc.nextLong() % 2; if(a[i] == 0){ evenC++; }else{ oddC++; } } if(Math.abs(evenC - oddC) > 1){ System.out.println(-1); }else if(oddC > evenC){ long res = countFunc(a, 1); System.out.println(res); }else if(evenC > oddC){ long res = countFunc(a, 0); System.out.println(res); }else{ long res = Math.min(countFunc(a, 1), countFunc(a, 0)); System.out.println(res); } } } private static long countFunc(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
78b14e7e88ea51a72a1dd65690f593dc
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.*; import java.util.Scanner; import java.util.StringTokenizer; public class eashan{ public static boolean checker(long[] arr,long K,long diff) { long collect=0; for(int i=0;i<arr.length;i++) { if(arr[i]>diff) collect+=arr[i]-diff; } if(collect>=K) return true; else return false; } public static long search(long[] arr,long K,long R) { long l=0; long r=R; while(l<=r) { long mid=(l+r)/2; if(checker(arr,K,mid)) { if(checker(arr,K,mid+1)) l=mid+1; else return mid; } else r=mid-1; } return -1; } static void sieveOfEratosthenes(int n,ArrayList<Integer> arr,ArrayList<Integer> arr1) { // 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; } } // Print all prime numbers int x=0; for (int i = 2; i <= n; i++) { if (prime[i] == true) { arr.add(i); } } System.out.println(arr.size()); } public static boolean check(long[] time,long complete,long tasks) { long c=0; for(int i=0;i<time.length;i++) c+=complete/time[i]; if(c>=tasks) return true; else return false; } public static long sear(long[] arr,long tasks) { long l=0; long r=(long)Math.pow(10,18); while(l<=r) { long mid=(l+r)/2; //System.out.println(mid); //System.out.println(pro.get(mid)); if(check(arr,mid,tasks)) { if(check(arr,mid-1,tasks)) r=mid-1; else return mid; } else l=mid+1; } return -1; } public static long get_answer(int node_start, int node_end, int node_index, int query_start, int query_end, long seg_tree[]) { if(query_start <= node_start && query_end >= node_end) { return seg_tree[node_index]; } if(node_end < query_start || query_end < node_start) { // long s=0; return (long)Math.pow(2,31)-1; } int mid=node_start+(node_end-node_start)/2; return get_answer(node_start, mid, 2*node_index+1, query_start, query_end, seg_tree)& get_answer(mid+1, node_end, 2*node_index+2,query_start, query_end, seg_tree); } public static void update_recurse(long seg_tree[], int node_start, int node_end, int update_index, long old_value, long new_value, int node_index) { if(update_index < node_start || update_index > node_end) return; seg_tree[node_index] = (seg_tree[node_index]|old_value)&new_value; if(node_start!=node_end) { int mid = node_start+(node_end-node_start)/2; update_recurse(seg_tree, node_start,mid,update_index,old_value,new_value,2*node_index+1); update_recurse(seg_tree,mid+1,node_end,update_index,old_value, new_value, 2*node_index+2); } } public static void update(long elements[], long seg_tree[], int i, int N, long new_value) { if(i > 0 && i <= N-1) { int number_of_bits = (int)(Math.floor(Math.log(elements[i]) / Math.log(2))) + 1; long complement = elements[i]^(long)(Math.pow(2,31)-1); // long complement = ~elements[i]; // System.out.println(complement); // System.out.println((long)((1 << number_of_bits)-1)); elements[i] = new_value; update_recurse(seg_tree,0,N-1,i,complement,new_value,0); } } public static long create_seg_tree(long elements[], int node_start, int node_end, long seg_tree[], int node_index) { if(node_start == node_end) { seg_tree[node_index]=elements[node_start]; return elements[node_start]; } int mid = node_start+(node_end-node_start)/2; seg_tree[node_index]=create_seg_tree(elements, node_start, mid, seg_tree, 2*node_index+1) & create_seg_tree(elements, mid+1, node_end, seg_tree, 2*node_index+2); return seg_tree[node_index]; } public static void main(String[] args)throws IOException { Reader.init(System.in); BufferedWriter output=new BufferedWriter(new OutputStreamWriter(System.out)); int T=Reader.nextInt(); for(int m=1;m<=T;m++) { int N=Reader.nextInt(); ArrayList<Integer> arr_even=new ArrayList<>(); ArrayList<Integer> arr_odd=new ArrayList<>(); for(int i=0;i<N;i++) { int ch=Reader.nextInt(); if(ch%2==0) arr_even.add(i); else arr_odd.add(i); } if(Math.abs(arr_even.size()-arr_odd.size())>1) output.write(-1+"\n"); else { int ans1=0,ans2=0; int pos=0,l=0; while(l<arr_even.size()) { ans1+=Math.abs(arr_even.get(l)-pos); ++l; pos+=2; } pos=0;l=0; while(l<arr_odd.size()) { ans2+=Math.abs(arr_odd.get(l)-pos); ++l; pos+=2; } if(arr_even.size()>arr_odd.size()) output.write(ans1+"\n"); else if(arr_even.size()<arr_odd.size()) output.write(ans2+"\n"); else output.write(Math.min(ans1,ans2)+"\n"); } } output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { 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 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
43107db71c8cd7f28ffcec99c7854498
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.util.*; import java.io.*; public class template{ 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()); } } public static int gcd(int a,int b) { if(b == 0) { return a; } return gcd(b,a%b); } public static void main(String[] args) { FastScanner sc = new FastScanner(); int test = sc.nextInt(); while(test-->0) { int n = sc.nextInt(); int arr[] = sc.readArray(n); if(n == 1) { System.out.println("0"); continue; } int a[] = new int[n/2]; int e = 0; int o = 0; for(int i=0;i<arr.length;i++){ if(arr[i] % 2 == 0) { e++; } else { o++; } } int diff = Math.abs(e-o); int ind = 0; int ans = 0; if(!(diff == 0 || diff == 1)) { System.out.println("-1"); } else { if(diff == 0 ) { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 != 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even for(int i=0;i<a.length;i++) { int dd = Math.abs(even - a[i]); c1 += dd; even += 2; } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } if(c1 < c2) { System.out.println(c1); } else { System.out.println(c2); } } else if(e - o == 1) { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 != 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even // for(int i=0;i<a.length;i++) { // int dd = Math.abs(even - a[i]); // c1 += dd; // even += 2; // } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } // if(c1 < c2) { // System.out.println(c1); // } // else { System.out.println(c2); // } } else { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 == 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even // for(int i=0;i<a.length;i++) { // int dd = Math.abs(even - a[i]); // c1 += dd; // even += 2; // } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } // if(c1 < c2) { // System.out.println(c1); // } // else { System.out.println(c2); //} } } } } } class pair { int value; int index; pair(int value,int index){ this.value = value; this.index = index; } public int getValue() { return value; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setValue(int value) { this.value = value; } } //5 //3 //6 6 1 //1 //9 //6 //1 1 1 2 2 2 //2 //8 6 //6 //6 2 3 4 5 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
5443a6a31be0e32f7d247e87b26ba2d4
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 TakeYourPlaces { public static void main(String args[]) { int i,j,k,l,n,t; Scanner sc=new Scanner(System.in); t=sc.nextInt(); while(t-->0) { n=sc.nextInt(); int a[]=new int[n]; int count0=0,count1=0; ArrayList<Integer> even=new ArrayList<>(); ArrayList<Integer> odd=new ArrayList<>(); for(i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]%2==0) { even.add(i+1); count0++; } else { odd.add(i+1); count1++; } } if(n%2==0&&(count1!=count0)) { System.out.println("-1"); } else if(n%2==1&&Math.abs(count1-count0)!=1) { System.out.println("-1"); } else { int sum=0,max=0; if(n%2==0) { int z=0; int b; for(i=1;i<n;i+=2) { k=odd.get(z); b=even.get(z); max=max+Math.abs(i-b); sum=sum+Math.abs(i-k); z++; } if(max<sum) { sum=max; } } else { int z=0; if(count1>count0) { for(i=1;i<=n;i+=2) { k=odd.get(z++); sum=sum+Math.abs(i-k); } } else { for(i=1;i<=n;i+=2) { k=even.get(z++); sum=sum+Math.abs(i-k); } } } System.out.println(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 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
c17223ff4bac013a01958cb97c5c3ac2
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.System.out; import java.util.*; import java.io.*; import java.math.*; /* -> Give your 100%, that's it! -> Rules To Solve Any Problem: 1. Read the problem. 2. Think About It. 3. Solve it! */ public class Template { static int mod = 1000000007; public static void main(String[] args){ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int yo = sc.nextInt(); while (yo-- > 0) { int n = sc.nextInt(); int[] a = new int[n]; int e = 0; int o = 0; for(int i = 0; i < n; i++){ int num = sc.nextInt(); a[i] = num%2; if(num%2 == 1) o++; else e++; } if(abs(e-o) > 1){ out.println(-1); continue; } PriorityQueue<Integer> pq = new PriorityQueue<>(); PriorityQueue<Integer> pq2 = new PriorityQueue<>(); if(e < o){ for(int i = 0; i < n; i++){ a[i] = a[i] == 0 ? 1 : 0; } } for(int i = 0; i < n; i++){ if(a[i] == 1){ pq.add(i); pq2.add(i); } } // for odd int steps = 0; for(int i = 1; i < n; i+=2){ if(pq.isEmpty()) { steps = Integer.MAX_VALUE; break; } steps += abs(pq.poll()-i); } int steps2 = 0; for(int i = 0; i < n; i+=2){ if(pq2.isEmpty()) { steps2 = Integer.MAX_VALUE; break; } steps2 += abs(pq2.poll()-i); } int ans = min(steps,steps2); out.println(ans); } out.close(); } /* Source: hu_tao Random stuff to try when stuck: -if it's 2C then it's dp -for combo/probability problems, expand the given form we're interested in -make everything the same then build an answer (constructive, make everything 0 then do something) -something appears in parts of 2 --> model as graph -assume a greedy then try to show why it works -find way to simplify into one variable if multiple exist -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them) -find lower and upper bounds on answer -figure out what ur trying to find and isolate it -see what observations you have and come up with more continuations -work backwards (in constructive, go from the goal to the start) -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements) -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max) -draw something -simulate a process -dont implement something unless if ur fairly confident its correct -after 3 bad submissions move on to next problem if applicable -do something instead of nothing and stay organized -write stuff down Random stuff to check when wa: -if code is way too long/cancer then reassess -switched N/M -int overflow -switched variables -wrong MOD -hardcoded edge case incorrectly Random stuff to check when tle: -continue instead of break -condition in for/while loop bad Random stuff to check when rte: -switched N/M -long to int/int overflow -division by 0 -edge case for empty list/data structure/N=1 */ public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); for (int i = 0; i < arr.length; i++) arr[i] = ls.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int N) { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i <= N; i++) sieve[i] = true; for (int i = 2; i <= N; i++) { if (sieve[i]) { for (int j = 2 * i; j <= N; j += i) { sieve[j] = false; } } } return sieve; } public static long power(long x, long y, long p) { long res = 1L; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res; } public static void print(int[] arr) { //for debugging only for (int x : arr) out.print(x + " "); out.println(); } 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[] readInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readLongs(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[] readDoubles(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; } } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
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
325b9d99a6391940caea77508168cab0
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 Codeforces2 { public static void main(String[] args)throws IOException { FastReader sc = new FastReader(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); //t -> test cases; long t = sc.nextLong(); while(t-->0){ int n = sc.nextInt(); long arr[] = new long[n]; Map<Long, Integer> parity = new LinkedHashMap<>(); int count0=0, count1=0; int a0[]=new int[n]; int a1[]=new int[n]; int change0=0, change1=0; boolean flag=true; ArrayList<Integer> zeroToOne0=new ArrayList<>(); ArrayList<Integer> zeroToOne1=new ArrayList<>(); ArrayList<Integer> oneToZero0=new ArrayList<>(); ArrayList<Integer> oneToZero1=new ArrayList<>(); for(int i=0; i<n; i++){ //Write loop stuffs long a=sc.nextLong(); long check = a&1; if(check == 0){ arr[i]=0; count0++; }else{ arr[i]=1; count1++; } if(flag){ a0[i]=0; a1[i]=1; if(arr[i]!=a0[i]){ change0++; oneToZero0.add(i); } else if(arr[i]!=a1[i]){ change1++; zeroToOne1.add(i); } flag=false; }else{ a0[i]=1; a1[i]=0; if(arr[i]!=a0[i]){ change0++; zeroToOne0.add(i); } else if(arr[i]!=a1[i]){ change1++; oneToZero1.add(i); } flag=true; } } if(count0-count1>1 || count0-count1<-1){ output.write(-1+"\n"); }else{ int ans0=0, ans1=0; int i=0; while(i<zeroToOne0.size() && i<oneToZero0.size()){ int diff=zeroToOne0.get(i)-oneToZero0.get(i); if(diff>0){ ans0+=diff; }else{ ans0-=diff; } i++; } i=0; while(i<zeroToOne1.size() && i<oneToZero1.size()){ int diff=zeroToOne1.get(i)-oneToZero1.get(i); if(diff>0){ ans1+=diff; }else{ ans1-=diff; } i++; } if(count0 == count1) output.write(Math.min(ans0, ans1)+"\n"); else if(count0>count1){ output.write(ans0+"\n"); }else{ output.write(ans1+"\n"); } } } output.flush(); } //Max Sliding Window static ArrayList<Integer> findKMaxElement(int[] arr, int k, int n) { // creating the max heap ,to get max element always PriorityQueue<Integer> queue = new PriorityQueue<>( Collections.reverseOrder()); ArrayList<Integer> res = new ArrayList<>(); int i = 0; for (; i < k; i++) queue.add(arr[i]); // adding the maximum element among first k elements res.add(queue.peek()); // removing the first element of the array queue.remove(arr[0]); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.add(arr[i]); // finding & adding the max element in the // current sliding window res.add(queue.peek()); // finally removing the first element from front // end of queue queue.remove(arr[i - k + 1]); } return res; // this code is Contributed by Pradeep Mondal P } 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; } } //Number of bits static int numberOfBits(int n){ return (int)(Math.log(n)/Math.log(2)+1); } //GCD of a Two number static long GCD(long a, long b){ if(b==0) return a; return GCD(b, a%b); } //No of factors in factorial n i.e. (n!) static long factors(long n, long b){ long count =0; int power = 1; while(n>=b){ count+=n/b; b=(long)Math.pow(b, ++power); } return count; } //prime numbers in a range from 2 to n static boolean[] primeUptoN(int n){ boolean arr[]= new boolean[n]; return arr; } //Round off static double roundOff(double value, int digit){ double mul = Math.pow(10.0, digit); value=Math.round((value*mul)/mul); return value; } }
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
ec41bd3c9e312a92bd5388c5023e7ae4
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.util.*; import java.io.*; public class template{ 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()); } } public static int gcd(int a,int b) { if(b == 0) { return a; } return gcd(b,a%b); } public static void main(String[] args) { FastScanner sc = new FastScanner(); int test = sc.nextInt(); while(test-->0) { int n = sc.nextInt(); int arr[] = sc.readArray(n); if(n == 1) { System.out.println("0"); continue; } int a[] = new int[n/2]; int e = 0; int o = 0; for(int i=0;i<arr.length;i++){ if(arr[i] % 2 == 0) { e++; } else { o++; } } int diff = Math.abs(e-o); int ind = 0; int ans = 0; if(!(diff == 0 || diff == 1)) { System.out.println("-1"); } else { if(diff == 0 ) { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 != 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even for(int i=0;i<a.length;i++) { int dd = Math.abs(even - a[i]); c1 += dd; even += 2; } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } if(c1 < c2) { System.out.println(c1); } else { System.out.println(c2); } } else if(e - o == 1) { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 != 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even // for(int i=0;i<a.length;i++) { // int dd = Math.abs(even - a[i]); // c1 += dd; // even += 2; // } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } // if(c1 < c2) { // System.out.println(c1); // } // else { System.out.println(c2); // } } else { for(int i=0;i<arr.length;i++) { if(arr[i] % 2 == 0) { a[ind] = i; ind++; } } int even = 0; int odd = 1; int c2 = 0; int c1 = 0; //even // for(int i=0;i<a.length;i++) { // int dd = Math.abs(even - a[i]); // c1 += dd; // even += 2; // } //odd for(int i=0;i<a.length;i++) { int dd = Math.abs(odd - a[i]); c2 += dd; odd += 2; } // if(c1 < c2) { // System.out.println(c1); // } // else { System.out.println(c2); //} } } } } } class pair { int value; int index; pair(int value,int index){ this.value = value; this.index = index; } public int getValue() { return value; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setValue(int value) { this.value = value; } } //5 //3 //6 6 1 //1 //9 //6 //1 1 1 2 2 2 //2 //8 6 //6 //6 2 3 4 5 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
247b9c19ffcdbfdd00390200c87d5ccb
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.IOException; import java.io.OutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /* * I referred to Petr's input / output template */ 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); TaskA solver = new TaskA(); int testCount = in.nextInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskA { static final long INF = 0x1fffffffffffffffL; static final int IINF = 0x3fffffff; static final long MOD = 1000000007; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); List<Integer> ans1 = new ArrayList<>(); List<Integer> ans2 = new ArrayList<>(); List<Integer> defEven = new ArrayList<>(); for (int i = 1; i <= n; i++) { int a = in.nextInt(); if (a % 2 == 0) { defEven.add(i); } } if (n == 1) { out.println(0); return; } int cntOdd = n - defEven.size(); if (Math.abs(cntOdd - defEven.size()) > 1) { out.println(-1); return; } long ans = INF; if (n % 2 == 0) { for (int i = 1; i <= n; i += 2) { ans1.add(i); } for (int i = 2; i <= n; i += 2) { ans2.add(i); } long sum = 0; for (int i = 0; i < defEven.size(); i++) { sum += Math.abs((long)defEven.get(i) - ans1.get(i)); } ans = Math.min(ans, sum); sum = 0; for (int i = 0; i < defEven.size(); i++) { sum += Math.abs((long)defEven.get(i) - ans2.get(i)); } ans = Math.min(ans, sum); } else { if (cntOdd < defEven.size()) { for (int i = 1; i <= n; i += 2) { ans1.add(i); } } else { for (int i = 2; i <= n; i += 2) { ans1.add(i); } } long sum = 0; for (int i = 0; i < defEven.size(); i++) { sum += Math.abs((long)defEven.get(i) - ans1.get(i)); } ans = Math.min(ans, sum); } out.println(ans); // end solve } } 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 int[] arrayInt(int N) { int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = nextInt(); } return arr; } public int[][] matrixInt(int H, int W) { int[][] matrix = new int[H][W]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { matrix[i][j] = nextInt(); } } return matrix; } public long nextLong() { return Long.parseLong(next()); } public long[] arrayLong(int N) { long[] arr = new long[N]; for (int i = 0; i < N; i++) { arr[i] = nextInt(); } return arr; } public long[][] matrixLong(int H, int W) { long[][] matrix = new long[H][W]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { matrix[i][j] = nextLong(); } } return matrix; } public double nextDouble() { return Double.parseDouble(next()); } public double[] arrayDouble(int N) { double[] arr = new double[N]; for (int i = 0; i < N; i++) { arr[i] = nextDouble(); } return arr; } public double[][] matrixDouble(int H, int W) { double[][] matrix = new double[H][W]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { matrix[i][j] = nextDouble(); } } return matrix; } } }
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
952b35abb5f2222c44629688b27cca79
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 : Akshat Jindal from NIT Jalandhar , Punjab , India JAI MATA DI */ import java.util.*; import java.io.*; import java.math.*; import java.sql.Array; public class Main { static class FR{ BufferedReader br; StringTokenizer st; public FR() { 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 void sort(long[] arr ) { ArrayList<Long> al = new ArrayList<>(); for(long e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(int[] arr ) { ArrayList<Integer> al = new ArrayList<>(); for(int e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static int UB(long[] arr , long find , int l , int r) { while(l<=r) { int m = (l+r)/2; if(arr[m]<find) l = m+1; else r = m-1; } return l; } static int LB(long[] arr , long find,int l ,int r ) { while(l<=r) { int m = (l+r)/2; if(arr[m] > find) r = m-1; else l = m+1; } return r; } static int UB(int[] arr , long find , int l , int r) { while(l<=r) { int m = (l+r)/2; if(arr[m]<find) l = m+1; else r = m-1; } return l; } static int LB(int[] arr , long find,int l ,int r ) { while(l<=r) { int m = (l+r)/2; if(arr[m] > find) r = m-1; else l = m+1; } return r; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static void sort(char[] arr) { ArrayList<Character> al = new ArrayList<Character>(); for(char cc:arr) al.add(cc); Collections.sort(al); for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i); } static long[][] ncr(int n, int k) { long C[][] = new long[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = (C[i - 1][j - 1] + C[i - 1][j])%mod; } } return C; } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } /************************************************ Query **************************************************************************************/ static class SparseTable{ private long[][] st; SparseTable(long[] arr){ int n = arr.length; st = new long[n][25]; log = new int[n+2]; build_log(n+1); build(arr); } private void build(long[] arr) { int n = arr.length; for(int i = n-1 ; i>=0 ; i--) { for(int j = 0 ; j<25 ; j++) { int r = i + (1<<j)-1; if(r>=n) break; if(j == 0 ) st[i][j] = arr[i]; else st[i][j] = gcd(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] ); } } } public long gcd(long a ,long b) { if(a == 0) return b; return gcd(b%a , a); } public long query(int l ,int r) { int w = r-l+1; int power = log[w]; return gcd(st[l][power],st[r - (1<<power) + 1][power]); } private int[] log; void build_log(int n) { log[1] = 0; for(int i = 2 ; i<=n ; i++) { log[i] = 1 + log[i/2]; } } } // static int query(int[] tree , int ss ,int se ,int qs , int qe,int index) { // // if(ss>=qs && se<=qe) return tree[index]; // // if(qe<ss || se<qs) return Integer.MAX_VALUE; // // int mid = (ss + se)/2; // int left = query(tree , ss , mid , qs ,qe , 2*index); // int right= query(tree ,mid + 1 , se , qs ,qe , 2*index+1); // return Math.min(left, right); // } // static void buildTree(int[] a ,int s ,int e ,int[] tree ,int index ) { // if(s == e) { // tree[index] = a[s]; // return; // } // // int mid = (s+e)/2; // // buildTree(a, s, mid, tree, 2*index); // buildTree(a, mid+1, e, tree, 2*index+1); // // tree[index] = tree[2*index] + tree[2*index+1]; // } /* ***************************************************************************************************************************************************/ static FR sc = new FR(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) { int tc = 1; tc = sc.nextInt(); while(tc-->0) { TEST_CASE(); } System.out.println(sb); } static void TEST_CASE() { int n = sc.nextInt(); int[] arr = new int[n]; int[] a = new int[n]; for(int i =0 ; i<n ; i++) { arr[i] = (sc.nextInt())%2; a[i] = arr[i]; } int one = 0; int zero = 0; for(int e:arr) { if(e == 1) one++; else zero++; } if(Math.abs(one-zero)>1) { sb.append("-1\n"); return; } sb.append(count(arr)+"\n"); } static long count(int[] arr ) { int[] a = new int[arr.length]; ArrayList<Integer> al1 = new ArrayList<>(); ArrayList<Integer> al2 = new ArrayList<>(); for(int i =0 ; i<arr.length ; i++) { if(arr[i] == 1) al1.add(i); } int n = arr.length; int one = al1.size(); if(n%2 == 0) { long c1 = 0; int i = 0 , j = 0; while(i<n) { if(i%2 == 1) { c1 += Math.abs(al1.get(j) - i); j++; }i++; } long ans = c1; long c0 = 0; i =0 ; j = 0; while(i<n) { if(i%2 == 0) { c0 += Math.abs(al1.get(j) - i); j++; }i++; } return Math.min(c1, c0); }else { if(one > n/2) { long c0 = 0; int i =0 , j = 0; while(i<n) { if(i%2 == 0) { c0 += Math.abs(al1.get(j) - i); j++; }i++; } return c0; }else { long c1 = 0; int i = 0 , j = 0; while(i<n) { if(i%2 == 1) { c1 += Math.abs(al1.get(j) - i); j++; }i++; } return c1; } } } static boolean fnc(int[] arr) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int e:arr) pq.add(e); int max = 0; while(!pq.isEmpty()) { int pv = pq.peek(); int c = 0; while(!pq.isEmpty() && pq.peek() == pv) { pq.poll(); c++; } max = Math.max(max, c); } int rem = arr.length - max; if(max > rem+1) return true; return false; } } /*******************************************************************************************************************************************************/
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
ca3f8bd60254a8c8fdeead4ab037260d
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 { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader(new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader reader = new FastReader(); int t = reader.nextInt(); int n; StringBuilder sb = new StringBuilder(""); long ans = 0; int i; int pos; while (t-- > 0) { ans = 0; n = reader.nextInt(); int arr[] = new int[n]; int ones = 0, zeroes = 0; for(i=0; i<n; i++){ arr[i] = reader.nextInt(); arr[i] = arr[i]%2; if(arr[i]==0){ zeroes++; }else{ ones++; } } if(Math.abs(ones-zeroes)>1){ sb.append("-1\n"); continue; } ArrayList<Integer> array = new ArrayList<>(); for(i=0; i<n; i++){ if(arr[i]==1){ array.add(i); } } int size = array.size(); int a1 = 0; pos = 0; i = 0; while(pos<n && i<size){ a1 += Math.abs(array.get(i)-pos); pos += 2; i++; } int a2 = 0; pos = 1; i = 0; while(pos<n){ a2 += Math.abs(array.get(i)-pos); pos += 2; i++; } if(ones==zeroes){ ans = Math.min(a1, a2); }else if(ones>zeroes){ ans = a1; }else{ ans = a2; } sb.append(ans + "\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 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
db72ee4b426274019ad9d3e5f8ac7b6a
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 { FastIO io = new FastIO(); int test=io.nextInt(); while(test>0) { int n=io.nextInt(); long arr[]=new long[n]; int z=0,o=0; for(int i=0;i<n;i++) { long x=io.nextLong(); arr[i]=x%2; if(arr[i]==1)o++; else z++; } if(n%2==0&&o!=z){ io.println(-1); test--; continue; } if(n%2==1&&Math.abs(z-o)!=1) { io.println(-1); test--; continue; } long temp[]=new long[n]; for(int i=0;i<n;i++)temp[i]=i%2; long ans=Long.MAX_VALUE; if(o==z||z-1==o) ans=solve(arr,temp); for(int i=0;i<n;i++)temp[i]=(i+1)%2; if(o==z||o-1==z) ans=Math.min(ans,solve(arr,temp)); io.println(ans); test--; } io.close(); } static long solve(long arr[],long temp[]) { Stack<Integer> stk=new Stack<>(); long ans=0; for(int i=0;i<arr.length;i++) { if(arr[i]!=temp[i]) { if(stk.size()==0)stk.push(i); else { int j=stk.peek(); if(arr[i]==arr[j])stk.push(i); else { j=stk.pop(); ans+=i-j; } } } } //System.out.println(ans); return ans; } } class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1<<16]; private int curChar, numChars; // standard input public FastIO() { this(System.in,System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } public String nextLine() { int c; do { c = nextByte(); } while (c <= '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public 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 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
7991d4556b3bdac81d348bb0e34e4afb
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.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; 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.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; public class Main implements Runnable { int n, m, k; long n1, s; static boolean use_n_tests = true; long mod = 1_000_000_007; long mod1 = 998244353L; // Long[][] dp; double scale = 1e+6; char[] s1; Integer[][] dp; int steps = 0; List<Integer> primes = Collections.emptyList();//generatePrimes(31623); boolean[] mark; List<Integer> curComp; Graph g; int[][] ls; int[] coord1, coord2; int[] lasts; boolean[] end1, end2; int ensz1, ensz2; List<Integer> ensz2list; int it = 0; void solve(FastScanner in, PrintWriter out, int testNumber) { n = in.nextInt(); int[] a = in.nextArray(n); int odd = 0; List<Integer> posOnes = new ArrayList<>(); List<Integer> posZero = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) { odd++; } a[i] = a[i] % 2; if (a[i] == 1) { posOnes.add(i); } else { posZero.add(i); } } if (n % 2 == 0) { if (odd == n / 2) { out.println(calc(posOnes, posZero)); return; } } else { if (odd == n / 2 || odd == (n + 1) / 2) { out.println(calc(posOnes, posZero)); return; } } out.println(-1); } long calc(List<Integer> ones, List<Integer> zero) { int n = ones.size() + zero.size(); List<Integer> place0 = new ArrayList<>(), place1 = new ArrayList<>(); for (int i = 0; i < n; i++) { if (i % 2 == 0) { place0.add(i); } else { place1.add(i); } } long ans = Long.MAX_VALUE; if (ones.size() == place0.size()) { long ans1 = 0; for (int i = 0; i < ones.size(); i++) { ans1 += Math.abs(ones.get(i) - place0.get(i)); } ans = ans1; } if (zero.size() == place0.size()) { long ans1 = 0; for (int i = 0; i < zero.size(); i++) { ans1 += Math.abs(zero.get(i) - place0.get(i)); } ans = Math.min(ans1, ans); } if (ones.size() == place1.size()) { long ans1 = 0; for (int i = 0; i < place1.size(); i++) { ans1 += Math.abs(ones.get(i) - place1.get(i)); } ans = Math.min(ans1, ans); } if (zero.size() == place1.size()) { long ans1 = 0; for (int i = 0; i < place1.size(); i++) { ans1 += Math.abs(zero.get(i) - place1.get(i)); } ans = Math.min(ans1, ans); } return ans; } int higherThen(int a) { return a; } // ****************************** template code *********** static public class LcaSparseTable { int len; int[][] up; int[] tin; int[] tout; int time; static List<Integer>[] tree; static LcaSparseTable t; void dfs(List<Integer>[] tree, int u, int p) { tin[u] = time++; up[0][u] = p; for (int i = 1; i < len; i++) up[i][u] = up[i - 1][up[i - 1][u]]; for (int v : tree[u]) if (v != p) dfs(tree, v, u); tout[u] = time++; } public LcaSparseTable(List<Integer>[] tree, int root) { int n = tree.length; len = 1; while ((1 << len) <= n) ++len; up = new int[len][n]; tin = new int[n]; tout = new int[n]; dfs(tree, root, root); } boolean isParent(int parent, int child) { return tin[parent] <= tin[child] && tout[child] <= tout[parent]; } public int lca(int a, int b) { if (isParent(a, b)) return a; if (isParent(b, a)) return b; for (int i = len - 1; i >= 0; i--) if (!isParent(up[i][a], b)) a = up[i][a]; return up[0][a]; } public static void adaptGraph(Graph graph) { int n = graph.size() + 1; tree = new List[n]; for (int i = 0; i < n; i++) { tree[i] = new ArrayList<>(); } List<Integer> edges = graph.getEdges(); for (int i = 0; i < edges.size() / 2; i++) { int v = edges.get(i * 2); int u = edges.get(i * 2 + 1); tree[v].add(u); tree[u].add(v); } t = new LcaSparseTable(tree, 0); } public static int getLca(int a, int b) { return t.lca(a, b); } } List<Integer> factorize(int a) { List<Integer> res = new ArrayList<>(); for (int i = 0; i < primes.size(); i++) { int p = primes.get(i); while (a % p == 0) { res.add(p); a /= p; } if (a == 1 && p > a) { break; } } if (a != 1) { res.add(a); } return res; } void impossible() { out.println(-1); } void yes() { out.println("YES"); } void no() { out.println("NO"); } static boolean next_permutation(char[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } public static class DisjointSets { int[] p; DisjointSets(int size) { p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; } public int root(int x) { return x == p[x] ? x : (p[x] = root(p[x])); } public void unite(int a, int b) { a = root(a); b = root(b); if (a != b) p[a] = b; } } boolean triangleCheck(int a, int b, int c) { return a + b > c && a + c > b && b + c > a; } Map<Integer, Integer> numberCompression(List<Integer> ls) { Collections.sort(ls); int id = 1; Map<Integer, Integer> comp = new HashMap<>(); for (int num : ls) { if (!comp.containsKey(num)) { comp.put(num, id++); } } return comp; } long lcm(long a, long b) { return (a / gcd(a, b)) * b; } long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } class Pt { int x, y; Pt(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } boolean sameAxis(Pt b) { return b.x == x || b.y == y; } int manxDist(Pt b) { return Math.abs(x - b.x) + Math.abs(y - b.y); } void read() { x = in.nextInt(); y = in.nextInt(); } } void swap(Integer[] a, int i, int j) { Integer tmp = a[i]; a[i] = a[j]; a[j] = tmp; } void swap(List<Integer> a, int i, int j) { Integer tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } long manhDist(long x, long y, long x1, long y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double dist(double x, double y, double x1, double y1) { return Math.sqrt(Math.pow(x - x1, 2.0) + Math.pow(y - y1, 2.0)); } public static class FW { public static void add(long[] t, int i, long value) { for (; i < t.length; i |= i + 1) t[i] += value; } public static long sum(long[] t, int i) { long res = 0; for (; i >= 0; i = (i & (i + 1)) - 1) res += t[i]; return res; } public static void add(long[] t, int a, int b, long value) { add(t, a, value); add(t, b + 1, -value); } } int sign(int a) { if (a < 0) { return -1; } return 1; } long binpow(long a, int b) { long res = 1; while (b != 0) { if (b % 2 == 0) { b /= 2; a *= a; a %= mod; } b--; res *= a; res %= mod; } return res; } List<Integer> getDigits(long n) { List<Integer> res = new ArrayList<>(); while (n != 0) { res.add((int) (n % 10L)); n /= 10; } return res; } List<Integer> generatePrimes(int n) { List<Integer> res = new ArrayList<>(); boolean[] sieve = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (!sieve[i]) { res.add(i); } if ((long) i * i <= n) { for (int j = i * i; j <= n; j += i) { sieve[j] = true; } } } return res; } int[] ask(int l) { System.out.printf("? %d\n", l); System.out.flush(); return in.nextArray(n); } static int stack_size = 1 << 29; static class Coeff { long mod; long[][] C; long[] fact; boolean cycleWay = false; Coeff(int n, long mod) { this.mod = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = i; fact[i] %= mod; fact[i] *= fact[i - 1]; fact[i] %= mod; } } Coeff(int n, int m, long mod) { // n > m cycleWay = true; this.mod = mod; C = new long[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, m); j++) { if (j == 0 || j == i) { C[i][j] = 1; } else { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][j] %= mod; } } } } public long C(int n, int m) { if (cycleWay) { return C[n][m]; } return fC(n, m); } private long fC(int n, int m) { return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod; } private long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } } class Pair { int first; long second; Pair(int f, long s) { first = f; second = s; } public int getFirst() { return first; } public long getSecond() { return second; } } class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T higher(T x) { return mp.higherKey(x); } T smallest() { return mp.firstKey(); } T biggest() { return mp.lastKey(); } int size() { return size; } int diffSize() { return mp.size(); } } class Multiset<T> { int size = 0; Map<T, Integer> mp = new HashMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } boolean contains(T x) { return mp.containsKey(x); } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } int size() { return size; } int diffSize() { return mp.size(); } } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static List<List<Integer>> intInit2D(int n) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } return res; } static boolean isSorted(Integer[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static public long sum(List<Integer> a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public long sum(long[] a) { long sum = 0; for (long x : a) { sum += x; } return sum; } static public long sum(Integer[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public int min(Integer[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int min(int[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int max(Integer[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int max(int[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> graph; List<Integer> edges; Graph(int n) { create(n); } private void create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } this.graph = graph; edges = new ArrayList<>(); } int size() { return graph.size(); } List<Integer> abj(int v) { return graph.get(v); } void read(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; graph.get(v).add(u); } } void readBi(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; addEdge(v, u); } } public void addEdge(int v, int u) { graph.get(v).add(u); graph.get(u).add(v); edges.add(v); edges.add(u); } public List<Integer> getEdges() { return edges; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public char[] nextc() { return next().toCharArray(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public int[] nextArray() { int n = in.nextInt(); return nextArray(n); } public long[] nextArrayL(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Long[] nextArrayL2(int n) { Long[] res = new Long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Integer[] nextArray2(int n) { Integer[] res = new Integer[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
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
30e41615d0e1ccd16f8e6f63b1858a23
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 Dell */ public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int a[] = new int[n]; int odd = 0, even = 0; int o[] = new int[n]; int e[] = new int[n]; int min = 0; for(int i = 0; i < n; i++){ a[i] = sc.nextInt(); if(a[i] % 2 == 0){ a[i] = 2; e[even] = i; even ++; } else{ a[i] = 1; o[odd] = i; odd ++; } } if(Math.abs(odd - even) >= 2){ System.out.println(-1); } else if(odd > even){ int count = 0; for(int j = 0; j < n; j+=2){ min += Math.abs(o[count] - j); count ++; } System.out.println(min); } else if (even > odd){ int count = 0; for(int j = 0; j < n; j+=2){ min += Math.abs(e[count] - j); count ++; } System.out.println(min); } else if(even == odd){ int m1 = 0, m2 = 0; int count = 0; for(int j = 0; j < n; j+= 2){ m1 += Math.abs(e[count] - j); m2 += Math.abs(o[count] - j); count ++; } System.out.println(Math.min(m1, m2)); } t--; } } }
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
7fec81c4d3ebe0f7d5cef71bf4bef28e
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.lang.*; import java.util.*; public final class CodeForces { static FastScanner scan = new FastScanner(); static StringBuffer output = new StringBuffer(); public static void main(String[] args) throws IOException { int t = 1; t = scan.nextInt(); while (t-- > 0) { solve(); } System.out.println(output); } static void solve() throws IOException { int n = scan.nextInt(); int[] a = new int[n]; int even = 0, odd = 0; for(int i=0;i<n;i++) { a[i] = scan.nextInt(); if(a[i] % 2 == 0) { even++; } else { odd++; } } int ans = 0; if(odd == even) { int index1 = 0, index2 = 1; int ans1 = 0, ans2 = 0; for(int i=0;i<n;i++) { if(a[i] % 2 == 1) { ans1 += Math.abs(i - index1); ans2 += Math.abs(i - index2); index1 += 2; index2 += 2; } } ans = Math.min(ans1, ans2); } else if(odd == even + 1) { int index = 0; for(int i=0;i<n;i++) { if(a[i] % 2 == 1) { ans += Math.abs(i - index); index += 2; } } } else if(even == odd + 1) { int index = 0; for(int i=0;i<n;i++) { if(a[i] % 2 == 0) { ans += Math.abs(i - index); index += 2; } } } else { ans = -1; } output.append(ans).append("\n"); } static class FastScanner { String line; String[] values; int position; BufferedReader bufferedReader; FastScanner() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(Boolean test) { InputStream inputStream = CodeForces.class.getResourceAsStream("test.txt"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); } void readLine() throws IOException { if (values == null || position == values.length) { line = bufferedReader.readLine(); values = line.trim().split(" "); position = 0; } } String next() throws IOException { readLine(); return values[position++]; } Integer nextInt() throws IOException { return Integer.parseInt(next()); } Long nextLong() throws IOException { 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
42f052d8fff97e95419e26f782c533d1
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 javax.rmi.ssl.SslRMIClientSocketFactory; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.io.*; import java.sql.ResultSetMetaData; import java.text.DecimalFormat; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); output.flush(); int t = Reader.nextInt(); while ( t > 0){ int n = Reader.nextInt(); int array[] = new int[n]; int i = 0; int eve = 0; int odd = 0; ArrayList<Integer> eveI = new ArrayList<>(); ArrayList<Integer> oddI = new ArrayList<>(); while (i < n){ array[i] = Reader.nextInt(); if ( (array[i]&1) == 1){ oddI.add(i+1); odd++; } else{ eveI.add(i+1); eve++; } i++; } if ( n%2 == 0 && eve != odd){ System.out.println(-1); } else if ( n%2 == 0){ long a = abs(calculate(oddI,n)); long b = abs(calculate(eveI,n)); System.out.println(Math.min(a,b)); } else if ( n%2 == 1){ int M = max(odd,eve); int mid = n/2 +1; if ( M != mid){ System.out.println(-1); } else{ if ( M == odd){ System.out.println(abs(calculate(oddI,n))); } else{ System.out.println(abs(calculate(eveI,n))); } } } t--; } output.flush(); } private static long calculate(ArrayList<Integer> array,int n){ int i = 1; long count = 0; while ( i <= n){ if ( (i&1) == 1){ int v = array.remove(0); count+= abs(v-i); } i++; } return count; } private static int bs(int low,int high,int[] array,int find){ if ( low <= high ){ int mid = low + (high-low)/2; if ( array[mid] > find){ high = mid -1; return bs(low,high,array,find); } else if ( array[mid] < find){ low = mid+1; return bs(low,high,array,find); } return mid; } return -1; } private static int max(int a, int b) { return Math.max(a,b); } private static int min(int a,int b){ return Math.min(a,b); } public static long modularExponentiation(long a,long b,long mod){ if ( b == 1){ return a; } else{ long ans = modularExponentiation(a,b/2,mod)%mod; if ( b%2 == 1){ return (a*((ans*ans)%mod))%mod; } return ((ans*ans)%mod); } } public static long sum(long n){ return (n*(n+1))/2; } public static long abs(long a){ return a < 0 ? (-1*a) : a; } public static long gcd(long a,long b){ if ( a == 0){ return b; } else{ return gcd(b%a,a); } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()); } } class NComparator implements Comparator<Node>{ @Override public int compare(Node o1, Node o2) { if ( o1.value> o2.value){ return 1; } else if ( o2.value > o1.value){ return -1; } else{ if ( o1.index < o2.index){ return 1; } else if ( o1.index > o2.index){ return -1; } else{ return 0; } } } } class Node{ int value; int length; int index; Node(int v,int l,int i){ value = v; length = l; index = 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 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
11e5ebca0845e7b6ba2ec00d078cc742
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.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { var sc = new Scanner(System.in); var pw = new PrintWriter(System.out); int T = Integer.parseInt(sc.next()); for(int t = 0; t < T; t++){ int n = Integer.parseInt(sc.next()); var a = new int[n]; for(int i = 0; i < n; i++){ a[i] = Integer.parseInt(sc.next()); } var odd = new ArrayList<Integer>(); var even = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ if(a[i] % 2 == 1){ odd.add(i); }else{ even.add(i); } } if(Math.abs(odd.size() - even.size()) >= 2){ pw.println(-1); continue; } long ans = Long.MAX_VALUE; if(odd.size() >= even.size()){ long count = 0; for(int i = 0; i < n; i++){ if(i%2 == 0){ count += Math.abs(i - odd.get(i/2)); }else{ count += Math.abs(i - even.get(i/2)); } } ans = Math.min(count / 2, ans); } if(odd.size() <= even.size()){ long count = 0; for(int i = 0; i < n; i++){ if(i%2 == 0){ count += Math.abs(i - even.get(i/2)); }else{ count += Math.abs(i - odd.get(i/2)); } } ans = Math.min(count / 2, ans); } pw.println(ans); } pw.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
PASSED
d0af9421477b2fa7451967191ee1ea32
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.company; import java.math.*; import java.util.*; import java.lang.*; import java.io.*; public final class Main { FastReader s; public static void main (String[] args) throws java.lang.Exception { new Main().run(); } void run() { s = new FastReader(); solve(); } StringBuffer sb; void solve() { sb = new StringBuffer(); for(int T = s.nextInt();T > 0;T--) { start(); } System.out.print(sb); } void start() { int n = s.nextInt(); int arr[] = intArr(n); int odd = 0; int even = 0; for(int i : arr) { if(i%2 == 0)even++; else odd++; } int l = n/2 + n%2; /// System.out.println(odd +" "+even+" "+l); if(Math.max(odd,even) > l) { //System.out.println("idhr hua " + n+" ka"); sb.append("-1\n"); return; } if(n%2 == 0) { ArrayList<Integer> x1 = new ArrayList<>(); ArrayList<Integer> x2 = new ArrayList<>();//even pos pe even wale ko ArrayList<Integer> y1 = new ArrayList<>(); ArrayList<Integer> y2 = new ArrayList<>();// odd pos pe even wale ko for(int i = 0; i<n; i++) { if(arr[i]%2 == 0) { if(i%2 == 0) { y1.add(i); } else { x1.add(i); } } else { if(i%2 == 0) { x2.add(i); } else { y2.add(i); } } } int ans1 = 0; int ans2 = 0; for(int j = 0; j<x1.size(); j++) { ans1+= Math.abs(x1.get(j)-x2.get(j)); } for(int j = 0; j<y1.size(); j++) { ans2+=Math.abs(y1.get(j)-y2.get(j)); } sb.append(Math.min(ans1,ans2)+"\n"); return; } else if(even > odd) { ArrayList<Integer> x1 = new ArrayList<>(); ArrayList<Integer> x2 = new ArrayList<>();// even pe even rhega for(int i = 0; i<n; i++) { if(arr[i]%2 == 0) { if(i%2 != 0) { x1.add(i); } } else { if(i%2 == 0) { x2.add(i); } } } int ans1 = 0; // int ans2 = 0; for(int j = 0; j<x1.size(); j++) { ans1+=Math.abs(x1.get(j)-x2.get(j)); } sb.append(ans1+"\n"); } else { ArrayList<Integer> x1 = new ArrayList<>(); // odd pe even rhega ArrayList<Integer> x2 = new ArrayList<>(); // odd pe even rhega for(int i = 0; i<n; i++) { if(arr[i]%2 == 0) { if(i%2 == 0) { x1.add(i); } } else { if(i%2 != 0) { x2.add(i); } } } int ans1 = 0; // int ans2 = 0; for(int j = 0; j<x1.size(); j++) { ans1+=Math.abs(x1.get(j)-x2.get(j)); } sb.append(ans1+"\n"); } } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the 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; } int lower_bound(int [] arr , int key) { int i = 0; int j = arr.length-1; //if(arr[i] > key)return -1; if(arr[j] < key)return -1; while(i<j) { int mid = (i+j)/2; if(arr[mid] == key) { j = mid; } else if(arr[mid] < key) { i = mid+1; } else j = mid-1; } return i; } int upper_bound(int [] arr , int key) { int i = 0; int j = arr.length-1; if(arr[j] <= key)return j+1; while(i<j) { int mid = (i+j)/2; if(arr[mid] <= key) { i = mid+1; } else j = mid; } return i; } int find(int dsu [],int i) { if(dsu[i] == i) return i; dsu[i] = find(dsu,dsu[i]); return dsu[i]; } void union(int dsu[] ,int i, int j) { int a = find(dsu,i); int b = find(dsu,j); dsu[a] = b; } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } //long array input public long [] longArr(int len) { // long arr input long [] arr = new long[len]; String [] strs = s.nextLine().trim().split("\\s+"); for(int i =0; i<len; i++) { arr[i] = Long.parseLong(strs[i]); } return arr; } // int arr input public int [] intArr(int len) { // long arr input int [] arr = new int[len]; String [] strs = s.nextLine().trim().split("\\s+"); for(int i =0; i<len; i++) { arr[i] = Integer.parseInt(strs[i]); } return arr; } 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 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
b76c0121245cdeb85facce0fd2beae06
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.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.StringTokenizer; public class TaskB { private static Set<Integer> simpleNums = new HashSet<>(); public static void main(String[] arg) { final FastScanner in = new FastScanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int T = in.nextInt(); for (int t = 0; t < T; t++) { final int n = in.nextInt(); final int[] a = in.readIntArr(n); out.println(solution(n, a)); } out.close(); in.close(); } private static int solution(int n, int[] a) { LinkedList<Integer> even = new LinkedList<>(); LinkedList<Integer> odd = new LinkedList<>(); for (int i = 0; i < n; i++) { if (a[i] % 2 == 0) { even.add(i); } else { odd.add(i); } } if (Math.abs(even.size() - odd.size()) >= 2) { return -1; } if (even.size() == odd.size()) { return Math.min(calsShift(new LinkedList[]{new LinkedList(odd), new LinkedList(even)}), calsShift(new LinkedList[]{new LinkedList(even), new LinkedList(odd)})); } return calsShift(new LinkedList[]{even, odd}); } private static int calsShift(LinkedList<Integer>[] elements) { if (elements[0].size() < elements[1].size()) { return calsShift(new LinkedList[]{elements[1], elements[0]}); } int cur = 0; int shiftCnt = 0; int next = 0; while (elements[next].size() > 0) { final Integer pos = elements[next].poll(); if (pos - cur > 0) { shiftCnt += pos - cur; } cur++; next++; next %= 2; } return shiftCnt; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } 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()); } int[] readIntArr(int n) { int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = nextInt(); } return result; } long[] readLongArr(int n) { long[] result = new long[n]; for (int i = 0; i < n; i++) { result[i] = nextLong(); } return result; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } 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
0d1752967cac770f837fd74161cc9fe1
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 17
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
22edaf1171992aa98ae2251607e395db
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.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class RoundDeltix2021B { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); // the code for the deep recursion (more than 100k or 3~400k or so) // Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28); // t.start(); // t.join(); RoundDeltix2021B sol = new RoundDeltix2021B(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = true; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ... int n; int[] a; void getInput() { n = in.nextInt(); a = in.nextIntArray(n); } void printOutput() { out.printlnAns(ans); } long ans; long solve(boolean evenFirst) { long ans = 0; int even = 0; int odd = 0; for(int i=0; i<n; i++) { if(a[i] % 2 == 0) even++; else odd++; if(even >= 1 && odd >= 1) { if(evenFirst) { if(a[i] % 2 == 0) ans += odd; else ans += even-1; } else { if(a[i] % 2 == 1) ans += even; else ans += odd-1; } odd--; even--; } } return ans; } void solve(){ ans = 0; int even = 0; int odd = 0; for(int i=0; i<n; i++) { if(a[i] % 2 == 0) even++; else odd++; } if(n % 2 == 0) { if(even == odd) ans = Math.min(solve(true), solve(false)); else ans = -1; } else { if(even == odd + 1) ans = solve(true); else if(odd == even+1) ans = solve(false); else ans = -1; } } // Optional<T> solve() // return Optional.empty(); static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } 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[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } // public <T> void printlnAns(Optional<T> ans) { // if(ans.isEmpty()) // println(-1); // else // printlnAns(ans.get()); // } public void printlnAns(OptionalInt ans) { println(ans.orElse(-1)); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean[] ans) { for(boolean b: ans) printlnAns(b); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.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 17
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
ee8a0b0f964771f05d69cd295a5d7f97
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class C { static final int INF = 0x3f3f3f3f; static final long LNF = 0x3f3f3f3f3f3f3f3fL; public static void main(String[] args) throws IOException { initReader(); // int T = nextInt(); // for (int i = 1; i <= T; i++) solve(); pw.flush(); } /*******************************************************************************************************************************/ public static void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); if ((n & 1) == 1) n -= 1; long ans = 0; for (int i = 0; i < n; i += 2) { ans += Math.min(a[i], a[i + 1]); if (a[i] > a[i + 1]) continue; long x = a[i + 1] - a[i], left = 0, right = 0; for (int j = i - 2; j >= 0; j -= 2) { if (a[j] >= a[j + 1]) { left = a[j] - a[j + 1]; long t = Math.min(left, right); left -= t; right -= t; if (right == 0) ans++; if (left > 0) { ans += Math.min(left, x); if (left > x) break; x -= left; } } else { right += a[j + 1] - a[j]; } } } pw.println(ans); } public static void Solve(BufferedReader reader1, PrintWriter pw1, StringTokenizer tokenizer1) throws IOException { reader = reader1; pw = pw1; tokenizer = tokenizer1; int T = nextInt(); for (int i = 1; i <= T; i++) solve(); pw.flush(); } public static <T> void deBug(T... a) { System.out.println(Arrays.toString(a)); } /*******************************************************************************************************************************/ /*******************************************************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // reader = new BufferedReader(new FileReader("test.in")); // tokenizer = new StringTokenizer(""); // pw = new PrintWriter(new BufferedWriter(new FileWriter("My answer.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static char nextChar() throws IOException { return next().charAt(0); } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
182f703bc17c293ffe4b11ea1382389a
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
//Utilities import java.io.*; import java.util.*; public class C { static int n; static long[] c; static long res; public static void main(String[] args) throws IOException { n = in.iscan(); c = new long[n+1]; for (int i = 1; i <= n; i++) { c[i] = in.lscan(); } res = 0; for (int l = 1; l < n; l += 2) { long carry = 0; long needPlus = 0; long add = 0; for (int r = l+1; r <= n; r += 2) { if (r == l+1) { if (c[r] > c[r-1]) { add = c[r-1]; break; } add += c[r]; carry = c[r-1] - c[r]; continue; } if (c[r] - (c[r-1] + needPlus) >= 0) { if (carry < c[r] - (c[r-1] + needPlus)) { add += 1L + carry; break; } add += 1L + c[r] - (c[r-1] + needPlus); carry -= c[r] - (c[r-1] + needPlus); needPlus = 0; } else { needPlus += c[r-1] - c[r]; } } res += add; } out.println(res); out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
acbb43e55a3e44962ec290885a6a7f76
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import java.io.*; import java.util.*; public class CF1556C extends PrintWriter { CF1556C() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1556C o = new CF1556C(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); if (n % 2 == 1) n--; n /= 2; int[] aa = new int[n]; long ans = 0; for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); ans += Math.min(a, b); aa[i] = a - b; } for (int i = 0; i < n; i++) { long a = aa[i]; if (a >= 0) { long b = 0; for (int j = i + 1; j < n; j++) if ((b += aa[j]) <= 0) { ans += Math.min(a, -b) + 1; if ((a += b) < 0) break; b = 0; } } } println(ans); } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
12c2a95295e5106cf3d257efe74dda9f
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; /* -> Give your 100%, that's it! -> Rules To Solve Any Problem: 1. Read the problem. 2. Think About It. 3. Solve it! */ public class Template { static int mod = 1000000007; public static void main(String[] args){ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int yo = 1; while (yo-- > 0) { int n = sc.nextInt(); long[] arr = new long[1005]; for(int i = 1; i <= n; i++){ arr[i] = sc.nextLong(); } long res = 0; for(int i = 1; i < n; i += 2) { long ans = 0; long ans2 = 0; for(int j = i+1; j <= n; j += 2) { if(arr[i] < -ans2) break; long left = max(0 ,ans - ans2); long right = min(arr[j],ans+arr[i]); res += max(0, right - left + 1); ans2 = min(ans2,ans-arr[j]); ans += arr[j+1]-arr[j]; } } res -= n/2; out.println(res); } out.close(); } /* Source: hu_tao Random stuff to try when stuck: -if it's 2C then it's dp -for combo/probability problems, expand the given form we're interested in -make everything the same then build an answer (constructive, make everything 0 then do something) -something appears in parts of 2 --> model as graph -assume a greedy then try to show why it works -find way to simplify into one variable if multiple exist -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them) -find lower and upper bounds on answer -figure out what ur trying to find and isolate it -see what observations you have and come up with more continuations -work backwards (in constructive, go from the goal to the start) -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements) -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max) -draw something -simulate a process -dont implement something unless if ur fairly confident its correct -after 3 bad submissions move on to next problem if applicable -do something instead of nothing and stay organized -write stuff down Random stuff to check when wa: -if code is way too long/cancer then reassess -switched N/M -int overflow -switched variables -wrong MOD -hardcoded edge case incorrectly Random stuff to check when tle: -continue instead of break -condition in for/while loop bad Random stuff to check when rte: -switched N/M -long to int/int overflow -division by 0 -edge case for empty list/data structure/N=1 */ public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); for (int i = 0; i < arr.length; i++) arr[i] = ls.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int N) { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i <= N; i++) sieve[i] = true; for (int i = 2; i <= N; i++) { if (sieve[i]) { for (int j = 2 * i; j <= N; j += i) { sieve[j] = false; } } } return sieve; } public static long power(long x, long y, long p) { long res = 1L; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res; } public static void print(int[] arr) { //for debugging only for (int x : arr) out.print(x + " "); out.println(); } 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[] readInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readLongs(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[] readDoubles(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; } } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
9e9427fe5c4823aaecf3e4298cbc219f
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import java.util.*; // import java.lang.*; import java.io.*; // THIS TEMPLATE MADE BY AKSH BANSAL. public class Solution { 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; } } private static boolean[] isPrime; private static void primes(){ int num = (int)1e6; // PRIMES FROM 1 TO NUM isPrime = new boolean[num]; for (int i = 2; i< isPrime.length; i++) { isPrime[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(isPrime[i] == true) { for(int j = (i*i); j<num; j = j+i) { isPrime[j] = false; } } } } static void sort(int a[]){ // int -> long ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long for(int i=0;i<a.length;i++) arr.add(a[i]); Collections.sort(arr); for(int i=0;i<a.length;i++) a[i]=arr.get(i); } private static long gcd(long a, long b){ if(b==0)return a; return gcd(b,a%b); } private static long pow(long x,long y){ if(y==0)return 1; long temp = pow(x, y/2); if(y%2==1){ return x*temp*temp; } else{ return temp*temp; } } static PrintWriter out; static FastReader sc ; public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); // primes(); // ________________________________ // _______________________________ // int n = sc.nextInt(); int n = sc.nextInt(); long[] arr =new long[n]; for(int i=0;i<n;i++){ arr[i] = sc.nextLong(); } out.println(solver(arr, n)); // ________________________________ out.flush(); } public static long solver(long[] arr, int n) { long res = 0; long cur = 0; long prev = 0; Stack<long[]> stack = new Stack<>(); for(int i=0;i<n-1;i+=2){ long temp = arr[i]-arr[i+1]; if(temp>0){ stack.push(new long[]{prev, cur}); prev = 0; cur = 0; } res+= prev+Math.min(arr[i], arr[i+1]); prev+=Math.min(arr[i], arr[i+1])>0?1:0; while(cur>0 && temp<0 && !stack.isEmpty()){ if(Math.abs(temp)>Math.abs(cur)){ long[] anc = stack.pop(); cur+=anc[1]; res+=anc[0]; } else{ break; } } if(cur>0 && temp<0){ res+=Math.min(Math.abs(cur), Math.abs(temp)); prev = Math.min(Math.abs(cur), Math.abs(temp))>0?1:0; } cur+=temp; if(cur == 0 && !stack.isEmpty()){ long[] anc = stack.pop(); cur+=anc[1]; res+=anc[0]; prev+= anc[0]; } else if(cur<0){ prev = 0; cur = 0; } // System.out.println(i+"__"+ res); } return res; } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
06e33889addd79a462eb289b592d2ea7
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { long mod1 = (long) 1e9 + 7; int mod2 = 998244353; public void solve() throws Exception { int n=sc.nextInt(); long arr[] = new long[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextLong(); } long ans=0; for(int i=0;i<n;i++) { if(i%2==1) { long currClosing = arr[i]; long initial = arr[i]; long min=arr[i]; for(int j=i-1;j>=0;j--) { if(min<0) break; if((i-j)%2==0) { currClosing += arr[j]; } else { if(arr[j]<=currClosing) { if(min==arr[i]) { ans += arr[j]; currClosing -= arr[j]; min = min-arr[j]; continue; } long leftWith = currClosing - min; long nn = arr[j]; nn -= leftWith; if(nn>=0) ans += nn+1; currClosing -= arr[j]; min=Math.min(min, currClosing); } else { if(j==i-1) ans += min; else ans += min+1; break; } } } } } out.println(ans); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } 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); } static long ncr(int n, int r, long p) { if (r > n) return 0l; if (r > n - r) r = n - r; long C[] = new long[r + 1]; C[0] = 1; for (int i = 1; i <= n; i++) { for (int j = Math.min(i, r); j > 0; j--) C[j] = (C[j] + C[j - 1]) % p; } return C[r] % p; } void sieveOfEratosthenes(boolean prime[], int size) { for (int i = 0; i < size; i++) prime[i] = true; for (int p = 2; p * p < size; p++) { if (prime[p] == true) { for (int i = p * p; i < size; i += p) prime[i] = false; } } } static int LowerBound(int a[], int x) { // smallest index having value >= 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; } static int UpperBound(int a[], int x) {// biggest index having value <= 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 long power(long x, long y, long p) { long res = 1; // out.println(x+" "+y); x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public int[] readArray(int n) throws Exception { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
85cc13172a86f4183be9b856478ff81a
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) 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 double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); //code below int n = sc.nextInt(); long[] arr = new long[n]; for(int i = 0; i < n; i++){ arr[i] = sc.nextLong(); //for safety brackets } long ans = 0; for(int i = 1; i < n; i += 2){ //simply remove odd number shit long lcnt = arr[i-1]; long rcnt = arr[i]; //after this ans += min(lcnt, rcnt); if(rcnt > lcnt) continue; //otherwise long lremcnt = lcnt - rcnt; long clarity = 0; for(int j = i + 2; j < n; j += 2){ //what if lcount > rcount long nowleft = arr[j-1]; long nowright = arr[j]; //this piece of code is so fucking tough man! if(clarity == 0){ if(nowleft == nowright){ ans++; }else if(nowleft < nowright){ ans++; //for the sake of increment if(lremcnt > nowright - nowleft){ ans += nowright - nowleft; lremcnt -= nowright - nowleft; }else if(lremcnt == nowright - nowleft){ ans += lremcnt; lremcnt = 0; }else{ ans += lremcnt; break; } }else{ //nowleft is greater now!! clarity shall rise now clarity = nowleft - nowright; } }else{ //if clarity is already there, then fucking remove it first if(nowleft > nowright){ clarity += nowleft - nowright; }else{ if(nowright - nowleft > clarity){ long remaining = nowright - nowleft - clarity; clarity = 0; ans++; if(lremcnt > remaining){ ans += remaining; lremcnt -= remaining; }else if(lremcnt == remaining){ ans += lremcnt; lremcnt = 0; }else{ ans += lremcnt; break; } }else if(nowright - nowleft == clarity){ clarity = 0; ans++; }else{ clarity -= nowright - nowleft; } } } } } System.out.println(ans); out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //updates are pretty cool //point update and range update!!! public void updateNode(int s, int e, int i, long increment, int index){ //case where I is out of bounds if(i < s || i > e){ return; } if(s == e){ //making increment tree[index] += increment; return; } //otherwise int mid = (s + e)/2; updateNode(s, mid, i, increment, 2 * index); updateNode(mid + 1, e, i, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //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'); } //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); } //sort long public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long 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; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //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); } //for ncr calculator(ignore this code) public 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; } //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--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------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\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
57d6d03971fc1f4d621c1796abe533b8
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
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.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; 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; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CCompressedBracketSequence solver = new CCompressedBracketSequence(); solver.solve(1, in, out); out.close(); } static class CCompressedBracketSequence { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long[] a = in.nextLongArray(n); long res = 0; for (int i = 0; i < n; i += 2) { long begin = a[i]; long sum = 0; boolean first = true; for (int j = i + 1; j < n; j++) { if (j % 2 == 0) { sum += a[j]; } else { if (a[j] < sum) { sum -= a[j]; } else { res += Math.min(begin, a[j] - sum); if (first) { first = false; } else { res++; } begin -= a[j] - sum; sum = 0; if (begin < 0) { break; } } } } } out.println(res); } } 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 println(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } 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 nextInt() { 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output
PASSED
d5b5ec5c0734664d26145e3e93abf429
train_107.jsonl
1630247700
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
256 megabytes
import java.sql.SQLSyntaxErrorException; import java.util.*; import java.io.*; import java.util.stream.StreamSupport; public class Solution { static int mod = 998244353; public static void main(String str[]) throws IOException{ // Reader sc = new Reader(); // BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long ans = 0; ArrayList<Long> al = new ArrayList<>(); for(int i=0;i<n;i++){ long x= sc.nextInt(); al.add(x); } Stack<Long> st = new Stack<>(); for(int i=0;i<n;i++){ if(i%2==0){ st.add(al.get(i)); } else{ long x = al.get(i); int zero = 0; boolean b = false; while((x>0 && !st.isEmpty()) || (b && !st.isEmpty() && st.peek()==0) ){ b = false; long pos = st.pop(); if(pos==0){ ans++; if(x==0){ b = true; zero++; } } else{ if(pos-x>0){ st.add(pos-x); st.add(0l); ans+=x; x = 0; break; } else if(pos-x==0){ zero++; ans+=x; x = 0; b = true; } else{ ans+=pos; x-=pos; } } } while(zero-->0) st.add(0l); } } System.out.println(ans); // output.flush(); } static class Pair { int ind; long weight; Pair(int i, long w) { ind = i; weight = w; } } static class Node{ int ind; long total = -1; int dis = 0; Map<Integer, Long> map = new HashMap<>(); ArrayList<Pair> al = new ArrayList<>(); Node(int i){ ind =i; } } static int maxHeight(List<Integer> wallPositions, List<Integer> wallHeights){ int ans = 0; int n = wallHeights.size(); for(int i=1;i<n;i++){ int ind1 = wallPositions.get(i-1); int ind2 = wallPositions.get(i); if(ind2-ind1==1) continue; int x = wallHeights.get(i-1); int y = wallHeights.get(i); int index = (y-x+ind1+ind2)/2; if(index<=ind1){ index = ind1+1; } else if(index>=ind2){ index = ind2-1; } ans = Math.max(ans, Math.min(x+(index-ind1),y+(ind2-index))); } return ans; } // 3 // 2 1 1 // 2 3 1 // 3 4 1 // 4 // 2 public static ArrayList<Integer> primeFactors(int n) { // Print the number of 2s that divide n ArrayList<Integer> al = new ArrayList<>(); while (n%2==0) { al.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { al.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) al.add(n); return al; } static void bfs(Graph[] g, int ind, boolean vis[], ArrayList<Node> al, Set<Integer> set){ vis[ind] = true; set.add(ind); for(int i: g[ind].pq){ if(!vis[i]) bfs(g,i,vis,al,set); } g[ind].set = set; } // static class tempSort implements Comparator<Node> { // // Used for sorting in ascending order of // // roll number // public int compare(Node a, Node b) { // return a.size - b.size; // } // } static long divide(long p, long q, long mod) { long expo = mod - 2; while (expo != 0) { if ((expo & 1) == 1) { // long temp = p; // System.out.println("zero--> "+temp+" "+q); p = (p * q) % mod; // if(p<0){ // System.out.println("one--> "+temp+" "+q); // } } q = (q * q) % mod; // if(q<0){ // System.out.println("two--> "+p+" "+q); // } expo >>= 1; } return p; } static class Graph{ int ind; ArrayList<Integer> pq = new ArrayList<>(); Set<Integer> set; boolean b = false; public Graph(int a){ ind = a; } } // // static class Pair{ // int a=0; // int b=0; // int in = 0; // int ac = 0; // int ex = 0; // } long fun2(ArrayList<Integer> arr, int x){ ArrayList<ArrayList> al = new ArrayList<>(); ArrayList<Integer> curr = new ArrayList<>(); fun(arr, x, al, curr, 0); if(al.size()==0) return 0; int max = 0; for(ArrayList<Integer> i: al){ if(i.size()>max) max = i.size(); } for(int i=0;i<al.size();i++){ if(al.get(i).size()!=max){ al.remove(i); i--; } } for(ArrayList<Integer> i: al){ Collections.sort(al, Collections.reverseOrder()); } long ans = 0; for(ArrayList<Integer> i: al){ long temp = 0; for(int j: i){ temp*=10; temp+=j; } if(ans<temp) ans = temp; } return ans; } void fun(ArrayList<Integer> arr, int x, ArrayList<ArrayList> al, ArrayList<Integer> curr, int i){ if(x<0) return ; if(x==0) { al.add(curr); return; } for(int j=i;j<arr.size();j++){ ArrayList<Integer> temp = new ArrayList<>(curr); fun(arr, x-arr.get(j), al, temp, j); } } // Returns n^(-1) mod p static long modInverse(long n, long p) { return (long)power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, int p, long[] fac) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long x = modInverse(fac[r], p); long y = modInverse(fac[n - r], p); return (fac[n] * x % p * y % p) % p; } static long[] sum(String[] str){ int n = str[0].length(); long ans[] = new long[n]; for(String s: str){ for(int i=0;i<n;i++) ans[i]+=s.charAt(i); } return ans; } // static class tSort implements Comparator<Pair>{ // // public int compare(Pair s1, Pair s2) { // if (s1.b < s2.b) // return -1; // else if (s1.b > s2.b) // return 1; // return 0; // } // } // static boolean checkCycle(Tree[] arr, boolean[] visited, int curr, int node){ // if(curr==node && visited[curr]) return true; // if(visited[curr]) return false; // visited[curr] = true; // for(int i: arr[curr].al){ // if(checkCycle(arr, visited, i, node)) return true; // } // return false; // } // static boolean allCombinations(int n){ //Global round 15 // int three2n = 1; // for (int i = 1; i <= n; i++) // three2n *= 3; // // for (int k = 1; k < three2n; k++) { // int k_cp = k; // int sum = 0; // for (int i = 1; i <= n; i++) { // int s = k_cp % 3; // k_cp /= 3; // if (s == 2) s = -1; // sum += s * a[i]; // } // if (sum == 0) { // return true; // } // } // return false; // } static ArrayList<String> fun( int curr, int n, char c){ int len = n-curr; if(len==0) return null; ArrayList<String> al = new ArrayList<>(); if(len==1){ al.add(c+""); return al; } String ss = ""; for(int i=0;i<len/2;i++){ ss+=c; } ArrayList<String> one = fun(len/2+curr, n, (char)(c+1)); for(String str: one){ al.add(str+ss); al.add(ss+str); } return al; } static ArrayList convert(int x, int k){ ArrayList<Integer> al = new ArrayList<>(); if(x>0) { while (x > 0) { al.add(x % k); x /= k; } } else al.add(0); return al; } static int max(int x, int y, int z){ int ans = Math.max(x,y); ans = Math.max(ans, z); return ans; } static int min(int x, int y, int z){ int ans = Math.min(x,y); ans = Math.min(ans, z); return ans; } // static long treeTraversal(Tree arr[], int parent, int x){ // long tot = 0; // for(int i: arr[x].al){ // if(i!=parent){ // tot+=treeTraversal(arr, x, i); // } // } // arr[x].child = tot; // if(arr[x].child==0) arr[x].child = 1; // return tot+1; // } public static int primeFactors(int n, int k) { int ans = 0; while (n%2==0) { ans++; if(ans>=k) return k; n /= 2; } for (int i = 3; i <= Math.sqrt(n); i+= 2) { while (n%i == 0) { ans++; n /= i; if(ans>=k) return k; } } if (n > 2) ans++; return ans; } static int binaryLow(ArrayList<Integer> arr, int x, int s, int e){ if(s>=e){ if(arr.get(s)>=x) return s; else return s+1; } int m = (s+e)/2; if(arr.get(m)==x) return m; if(arr.get(m)>x) return binaryLow(arr,x,s,m); if(arr.get(m)<x) return binaryLow(arr,x,m+1,e); return 0; } static int binaryLow(int[] arr, int x, int s, int e){ if(s>=e){ if(arr[s]>=x) return s; else return s+1; } int m = (s+e)/2; if(arr[m]==x) return m; if(arr[m]>x) return binaryLow(arr,x,s,m); if(arr[m]<x) return binaryLow(arr,x,m+1,e); return 0; } static int binaryHigh(int[] arr, int x, int s, int e){ if(s>=e){ if(arr[s]<=x) return s; else return s-1; } int m = (s+e)/2; if(arr[m]==x) return m; if(arr[m]>x) return binaryHigh(arr,x,s,m-1); if(arr[m]<x) return binaryHigh(arr,x,m+1,e); return 0; } // static void arri(int arr[], int n, Reader sc) throws IOException{ // for(int i=0;i<n;i++){ // arr[i] = sc.nextInt(); // } // } // static void arrl(long arr[], int n, Reader sc) throws IOException{ // for(int i=0;i<n;i++){ // arr[i] = sc.nextLong(); // } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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%p; } // static boolean dfs(Tree node, boolean[] visited, int parent, ArrayList<Tree> tt){ // visited[node.a] = true; // boolean b = false; // for(int i: node.al){ // if(tt.get(i).a!=parent){ // if(visited[tt.get(i).a]) return true; // b|= dfs(tt.get(i), visited, node.a, tt); // } // } // return b; // } // static class SortbyI implements Comparator<Pair> { // // Used for sorting in ascending order of // // roll number // public int compare(Pair a, Pair b) // { // if(a.a>=b.a) return 1; // else return -1; // } // } // static class SortbyD implements Comparator<Pair> { // // Used for sorting in ascending order of // // roll number // public int compare(Pair a, Pair b) // { // if(a.a<b.a) return 1; // else if(a.a==b.b && a.b>b.b) return 1; // else return -1; // } // } // static int binarySearch(ArrayList<Pair> a, int x, int s, int e){ // if(s>=e){ // if(x<=a.get(s).b) return s; // else return s+1; // } // int mid = (e+s)/2; // if(a.get(mid).b<x){ // return binarySearch(a, x, mid+1, e); // } // else return binarySearch(a,x,s, mid); // } // static class Edge{ // int a; // int b; // int c; // int sec; // Edge(int a, int b, int c, int sec){ // this.a = a; // this.b = b; // this.c = c; // this.sec = sec; // } // // } static class Tree{ int a; ArrayList<Tree> al = new ArrayList<>(); Tree(int a){ this.a = a; } } 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 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; } static ArrayList<Integer> sieveOfEratosthenes(int n) { ArrayList<Integer> al = new ArrayList<>(); // 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; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) al.add(i); } return al; } }
Java
["5\n4 1 2 3 1", "6\n1 3 2 1 2 4", "6\n1 1 1 1 2 2"]
1 second
["5", "6", "7"]
NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences: Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(())) Subsequence from the $$$4$$$th to $$$5$$$th character: () Subsequence from the $$$4$$$th to $$$9$$$th character: ()(()) Subsequence from the $$$6$$$th to $$$9$$$th character: (()) Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
Java 11
standard input
[ "brute force", "implementation" ]
ca4ae2484800a98b5592ae65cd45b67f
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.
1,800
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.
standard output