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
9541c0b0007716123258f8902880c63f
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Solution { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; void solve(Integer[] nums){ int sorted = 0; for(int i=0; i<nums.length; i++){ if(nums[i] == i + 1) sorted++; } if(sorted == nums.length){ println(0); }else if(nums[0] == nums.length && nums[nums.length-1] == 1){ println(3); }else if(nums[0] == 1 || nums[nums.length-1] == nums.length){ println(1); } else{ println(2); } // More than 1 element don't need sort /// None of element is sorted } boolean isReveredSorted(Integer[] nums){ for(int i=nums.length-1; i>0; i--){ if(nums[i] > nums[i-1]) return false; } return true; } public void execute() throws IOException{ int n = nextInt(); for(int i=0; i<n; i++){ solve(toArray(nextInt(), nextLine())); } br.close(); } public static void main(String[] args) throws IOException{ new Solution().execute(); } void print(Object obj){ System.out.print(obj); } void println(Object obj){ System.out.println(obj); } Integer[] toArray(int n, String s){ Integer[] res = new Integer[n]; String[] nums = s.split(" "); for(int i=0; i<n; i++){ res[i] = Integer.parseInt(nums[i]); } return res; } String next() { while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } String[] nextLines(int lines) { String[] inputs = new String[lines]; for(int i=0; i<lines; i++){ inputs[i] = nextLine(); } return inputs; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
67ece6da14944f66affea9a6944aa731
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.util.Arrays; public class Solution { 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]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); if (isSorted(a)) { System.out.println(0); } else if (a[0] == 1 || a[n-1] == n) { System.out.println(1); } else if (a[0] == n && a[n-1] == 1) { System.out.println(3); } else { System.out.println(2); } --t; } } public static boolean isSorted(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { if (a[i] - 1 != i) return false; } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
df34618f9088d688866ab299590a564b
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class B_Permutation_Sort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { list.add(sc.nextInt()); } if (issorted(list)) { System.out.println(0); } else{ if (list.get(0) == 1 || list.get(n-1) == n){ System.out.println(1); } else if (list.get(0) == n && list.get(n-1) == 1){ System.out.println(3); } else{ System.out.println(2); } } } sc.close(); } private static boolean issorted(List<Integer> list) { for (int i = 0; i < list.size() - 1; i++) { if (list.get(i) > list.get(i + 1)) { return false; } } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
a4c824c3f13dc917cb55c85c63f0a2aa
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Solution { private static final int MOD_1 = 1000000000 + 7; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } /* --------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ void printArray(int[] arr) { System.out.println(Arrays.toString(arr)); } void printArray(String[] arr) { System.out.println(Arrays.toString(arr)); } void printArray(long[] arr) { System.out.println(Arrays.toString(arr)); } void print(int data) { System.out.println(data); } void print(String data) { System.out.println(data); } void print(long data) { System.out.println(data); } int[] II(int n) throws IOException { int[] d = new int[n]; String[] arr = nextLine().split(" "); for (int i = 0; i < n; i++) { d[i] = Integer.parseInt(arr[i]); } return d; } String[] IS(int n) throws IOException { return nextLine().split(" "); } long[] IL(int n) throws IOException { long[] d = new long[n]; String[] arr = nextLine().split(" "); for (int i = 0; i < n; i++) { d[i] = Long.parseLong(arr[i]); } return d; } public long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } public 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) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } void sieveOfEratosthenes(boolean prime[], int size) { Arrays.fill(prime, true); prime[0] = prime[1] = false; prime[2] = 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; } } } } public long fact(long n) { long ans = 1; for (int i = 2; i <= n; i++) { ans = (ans * i) % MOD_1; } return ans; } public long lcm(long a, long b) { return (a * b) / gcd(a, b); } } /* ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ public static void main(String[] args) throws IOException { FastReader fs = new FastReader(); int t = Integer.parseInt(fs.nextLine()); while (t-- > 0) { int k = fs.nextInt(); int[] arr = fs.II(k); if(arr[0] == k && arr[k - 1] == 1){ System.out.println("3"); } else if(arr[0] != 1 && arr[k - 1] != k){ System.out.println("2"); } else{ boolean isPoss = true; for(int i = 0; i < k ; i++){ if(arr[i] != (i + 1)) { isPoss = false; break; } } if(!isPoss) System.out.println("1"); else System.out.println("0"); } } } /* StringBuilder sb = new StringBuilder(); sb.append(x + "\n"); Collections.sort(arr, (a, b) -> Integer.compare(a[0], b[0])) arr.toArray(new int[arr.size()][]) */ }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
841891237a7b2f893f8797544f44a3ae
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { FastScanner fs = new FastScanner(); int t = fs.nextInt(); for (int T = 0; T < t; T++) { int n = fs.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = fs.nextInt(); } boolean isOk = true; for (int i = 0; i < n; i++) { if (arr[i] != i+1) { isOk = false; break; } } if (isOk) { System.out.println(0); } else if (arr[0] == 1 || arr[n-1] == n) { System.out.println(1); } else if (arr[0] == n && arr[n-1] == 1) { System.out.println(3); } else { System.out.println(2); } } // end main } 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8777eaa7d6fc22efcd214be104b5e669
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class PermutationSort_1525B { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-->0){ int n = s.nextInt(); int [] a = new int [n]; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } int [] b = a.clone(); Arrays.sort(b); if(n==3){ // if the length is 3, use bubble sort int count = 0; for (int i = 0; i < a.length-1; i++) { if(a[i]>a[i+1]){ int temp = a[i+1]; a[i+1] = a[i]; a[i] = temp; count++; i = -1; } } System.out.println(count); } else { if (b[0]==a[0] && b[n-1]==a[n-1]){ boolean sorted = true; for (int i = 1; i < n-1; i++) { if(b[i]!=a[i]){ sorted = false; break; } } if(sorted) System.out.println(0); else System.out.println(1); } else if(b[0]==a[0] || b[n-1]==a[n-1]) System.out.println(1); else if (b[0]==a[n-1] && b[n-1]==a[0]) System.out.println(3); else { // if both position is not the min and max System.out.println(2); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c10006a3ca70e642faeb8ad9fa736301
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class Permutation_Sort { public static boolean isSorted(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) { return false; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } if (isSorted(arr)){ System.out.println(0); continue; } if (arr[0]==1||arr[n-1]==n){ System.out.println(1); }else if (arr[0]!=n||arr[n-1]!=1){ System.out.println(2); }else { System.out.println(3); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
7f5cd4ec9af9dd7e53d355690f5f0ebb
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class Permutation_Sort { public static void main(String[] args) { Scanner in=new Scanner(System.in); int test=in.nextInt(); while(test>0){ int n,i,cn1=0,cn2=0,maximum=-1,minimum=100000,max1,max2; n=in.nextInt(); int[] arr=new int[n]; for(i=0; i<n; i++){ arr[i]=in.nextInt(); } for(i=0; i<n-1; i++){ if(arr[i]<=arr[i+1]){ cn1++; } if(arr[i]>=arr[i+1]){ cn2++; } } for(i=0; i<n; i++){ if(arr[i]>maximum){ maximum=arr[i]; } if(arr[i]<minimum){ minimum=arr[i]; } } if(cn1==n-1){ System.out.println("0"); } else if(cn2==n-1){ System.out.println("3"); } else if(minimum==arr[n-1] && maximum==arr[0]){ System.out.println("3"); } else if(maximum==arr[n-1] || minimum==arr[0]){ System.out.println("1"); } else{ maximum=-1; minimum=100000; for(i=0; i<n-1; i++){ if(arr[i]>maximum){ maximum=arr[i]; } } if(maximum<arr[n-1]){ max1=1; } else{ max1=2; } for(i=1; i<n; i++){ if(arr[i]<minimum){ minimum=arr[i]; } } if(minimum<arr[0]){ max2=2; } else{ max2=1; } System.out.println(Math.min(max1,max2)); } test--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
1aee8c047371e23a95814dfa60f44b87
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class b1 { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int tc = scan.nextInt(); while((tc--) > 0){ int n = scan.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = scan.nextInt(); int is = 0; for(int i=0;i<n;i++){ if(arr[i] != i+1) is = 1; } int ans = 0; if(is == 0) { ans = 0; } else{ if(arr[0] == 1 || arr[n-1] == n) ans = 1; else if(arr[0] == n && arr[n-1] == 1) ans = 3; else ans = 2; } System.out.println(ans); } scan.close(); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
682e0d37868934a6a4537795b60a9db9
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
/*============================================== Name : Shadman Shariar || Email : [email protected] || University : North South University (NSU) || Facebook : shadman.shahriar.007 || ==============================================*/ //import java.io.*; import java.util.*; //import java.math.BigInteger; //import java.text.DecimalFormat; public class Main { public static Main obj = new Main(); public static Scanner input = new Scanner (System.in); //public static DecimalFormat df = new DecimalFormat(".00"); public static void main(String[] args) throws Exception { Scanner input = new Scanner (System.in); //BigInteger bi1 = new BigInteger("0"); //StringBuilder sb = new StringBuilder(); int t = input.nextInt(); for (int i = 0; i < t; i++) { int n = input.nextInt(); int c = 0; int [] arr = new int [n]; for (int j = 0; j < arr.length; j++) { arr[j] = input.nextInt(); if(j>0) { if(arr[j-1]>arr[j])c++; } } if (c==0) { System.out.println(0); } else if (arr[0] == 1 || arr[n-1] == n) { System.out.println(1); continue; } else if (arr[0] == n && arr[n-1] == 1) { System.out.println(3); } else { System.out.println(2); } } input.close(); System.exit(0); } public static boolean square(long x) { if (x >= 0) { double sr = Math.sqrt(x); return ((sr * sr) == x); } return false; } public static boolean cube(long N) { int cube; int c = 0; for (int i = 0; i <= N; i++) { cube = i * i * i; if (cube == N) { c=1; break; } else if (cube > N) { c=0 ; break ; } } if (c==1)return true; else return false; } public static boolean checkleapyear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } public static boolean[] sieveOfEratosthenes(int n) { 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] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } prime[1]=false; return prime; } public static boolean issquare(long n) { long sqrt=(long) Math.sqrt(n); for (int i=(int) Math.max(1, sqrt-5); i<=sqrt+5; i++) if (i*i==n) return true; return false; } public static long sumarray(long a[]) { long sum=0; for(int i=0;i<a.length;i++) sum+=a[i]; return sum; } public static boolean isperfectsquare(long n) { for (long i = 1; i * i <= n; i++) { if ((n % i == 0) && (n / i == i)) { return true; } } return false; } public static int removeduplicateelements(int arr[], int n){ Arrays.sort(arr); if (n==0 || n==1){ return n; } int[] temp = new int[n]; int j = 0; for (int i=0; i<n-1; i++){ if (arr[i] != arr[i+1]){ temp[j++] = arr[i]; } } temp[j++] = arr[n-1]; for (int i=0; i<j; i++){ arr[i] = temp[i]; } return j; } public static int fibon(int n) { if (n <= 1) { return n; } int[] array = new int[n + 1]; array[0] = 0; array[1] = 1; for (int i = 2; i <= n; i++) { array[i] = array[i - 2] + array[i - 1]; } return array[n]; } public static long sumofdigits(long n) { long sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } public static int reversedigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } public static int binarysearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarysearch(arr, l, mid - 1, x); return binarysearch(arr, mid + 1, r, x); } return -1; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static void rangeofprimenumber(int a, int b) { int i, j, flag; for (i = a; i <= b; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) System.out.println(i); } } public static boolean isprime(long n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } public static int factorial(int n) { return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static int[] reversearrayinrange(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
822a9bef47c49a50d423fac4e9190c14
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args){ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] a=new int[n+1]; boolean sorted=true; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); if(a[i]!=i) { sorted=false; } } if(sorted==true) { System.out.println(0); } else { if(a[n]==n || a[1]==1) { System.out.println(1); } else if(a[n]==1 && a[1]==n){ System.out.println(3); } else { System.out.println(2); } } } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c9d8cdda1f68aff535298ce496729dc4
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int ttt=1; ttt=f.nextInt(); PrintWriter out=new PrintWriter(System.out); for(int tt=0;tt<ttt;tt++) { int n=f.nextInt(); int[] l=f.readArray(n); boolean check=true; for(int i=0;i<n-1;i++) { if(i+1!=l[i]) check=false; } if(check) System.out.println(0); else if(l[0]==1) { System.out.println(1); } else { int ind=-1; for(int i=0;i<n;i++) { if(1==l[i]) ind=i; } if(ind==n-1) { if(l[0]==n) { System.out.println(3); } else { System.out.println(2); } } else { if(l[n-1]==n) System.out.println(1); else System.out.println(2); } } } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } } //Some things to notice //Check for the overflow //Binary Search //Bitmask //runtime error most of the time is due to array index out of range
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
172e094fd4731ce7d9c635eeff2c0385
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public final class coin34 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int testCases = scan.nextInt(); for (int i = 0; i < testCases; i++) { int length = scan.nextInt(); int[] array = new int[length]; for (int x = 0; x < length; x++) { array[x] = scan.nextInt(); } System.out.println(lenOfLongIncSubArr(array)); } } public static int lenOfLongIncSubArr(int arr[]) { boolean sorted = true; for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i+1]) { sorted = false; break; } } if(sorted == true){ return 0; } else if(arr[0] == 1 || arr[arr.length-1] == arr.length){ return 1; } else if(arr[0] == arr.length && arr[arr.length-1] == 1){ return 3; } return 2; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
96fc3f0b31b1fa00c21b01c5edc9c5e2
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Problem { static int Mod = 1000000007; public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = scan.nextInt(); // int t=1; while (t-- > 0) { int n=scan.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=scan.nextInt(); int flag=1; for(int i=0;i<n-1;i++){ if(a[i+1]<a[i]){ flag=0; break; } } if(flag==1) out.println(0); else if(a[0]==1 || a[n-1]==n){ out.println(1); }else { if(a[0]==n && a[n-1]==1) out.println(3); else out.println(2);} } out.close(); } static class Pair { long l; long r; Pair(long l, long r) { this.l = l; this.r = r; } @Override public String toString() { return "Pair [l=" + l + ", r=" + r + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (l ^ (l >>> 32)); result = prime * result + (int) (r ^ (r >>> 32)); return result; } @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; if (l != other.l) return false; if (r != other.r) return false; return true; } } public static void sort(int[] array) { ArrayList<Integer> copy = new ArrayList<>(); for (Integer i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (Long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(double[] array) { ArrayList<Double> copy = new ArrayList<>(); for (Double i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static long gcd(long a,long b) { if (b == 0) return a; return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long power(long x, long y) { long temp; if (y == 0) // a^b= (a^b/2)^2 if b is even return 1; // = (a*a^(b-1)) if b is odd temp = power(x, y / 2); if (y % 2 == 0) return temp * temp; else return x * temp * temp; } static long mod(long x) { return ((x % Mod + Mod) % Mod); } static long add(long a, long b) { return mod(mod(a) + mod(b)); } static long mul(long a, long b) { return mod(mod(a) * mod(b)); } static long pow(long x, long y, int 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; } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
57292dbe28c4bc214a348c6d5636e8c8
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; 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 sout = new PrintWriter(outputStream); int t = in.nextInt(); for(int k = 0; k<t;k++){ int count = 0; int n = in.nextInt(); int arr[] = new int[n]; for(int j = 0; j<n;j++){ int c = in.nextInt(); arr[j] = c; } boolean flag = false; for(int i = 0; i<n;i++){ if(arr[i] != i+1 ){ flag = true; break; } } if(flag){ count = 2; if(arr[0]==n && arr[n-1]==1){ count++; } else if(arr[0]==1 || arr[n-1]==n) { count--; } } sout.println(count); } sout.close(); } public static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextToken() { 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(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
69e1017678dcfcea6967a0055ba281ce
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Sol53 { 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 count=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<n;i++) { if(a[i]!=i+1) count++; } if(count==0) System.out.println("0"); else if(a[0]==1 || a[n-1]==n) System.out.println("1"); else if(a[0]==n && a[n-1]==1) System.out.println("3"); else System.out.println("2"); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
94939b3f334b0284125ceefb93b63190
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
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()); for(int z=1;z<=t;z++) { int size= Integer.parseInt(br.readLine()); int num[]=new int[size]; String str[]=br.readLine().split(" "); for(int i=0;i<str.length;i++){ num[i]=Integer.valueOf(str[i]); } Boolean flag=true; for(int i=0;i<num.length-1;i++){ if(num[i]>num[i+1])flag=false; } if(flag){ System.out.println("0"); continue; } if(num[0]==num.length && num[num.length-1]==1) { System.out.println("3"); continue; } if(num[0]==1 || num[num.length-1]==num.length){ System.out.println("1"); continue; } System.out.println("2"); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
e73db9f9238c5761fa84d36798db4842
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
/* package codechef; // don't place package name! */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { FastReader sc= new FastReader(); int t=sc.nextInt(); for(int i=1;i<=t;i++) { int n=sc.nextInt(); int f=0,j; int a[]=new int [n]; int b[]=new int [n]; for(j=0;j<n;j++) { a[j]=sc.nextInt(); } for(j=0;j<n;j++) { b[j]=j+1; } for(j=0;j<n;j++) { if(a[j]!=b[j]) { f=1; break; } } if(f==0) { System.out.println("0"); } else if(a[0]==1 || a[n-1]==n) { System.out.println("1"); } else if(a[n-1]==1 && a[0]==n) { System.out.println("3"); } else { System.out.println("2"); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
af1a15f42aaeb2a1346a7ed1314a057d
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Main { static long mod = (long) Math.pow(10, 9) + 7; public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t--!=0) { int n = sc.nextInt(); int [] ar = new int[n]; int min = 2147483647; int max = -1; int [] arr = new int[n]; for(int i = 0;i<n;i++) { ar[i] = sc.nextInt(); arr[i] = ar[i]; if(min>ar[i]) min = ar[i]; if(max<ar[i]) max = ar[i]; } Arrays.sort(arr); boolean ok = true; for(int i = 0;i<n;i++) { if(ar[i]!=arr[i]) ok = false; } boolean ok1 = false; if(ar[0] == max && ar[n - 1] == min) ok1 = true; if(ok1 == true) System.out.println(3); else if(ok) System.out.println(0); else { if(ar[0] == min || ar[n - 1] == max) System.out.println(1); else System.out.println(2); } } } static long lcm(int a, int b) { return (a / gcd(a, b)) * b; } static long gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static void no() { System.out.println("NO"); } static void yes() { System.out.println("YES"); } public 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9b5372c7d32efd71955cf93429763545
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// * * * its fun to do the impossible * * * // import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B { static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a , int b){ this.a = a; this.b = b; } public int compareTo(Pair o){ return this.a - o.a; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int a[] = sc.readArray(n); int count = 0; if(a[0] != 1){ if(a[n-1] == n){ System.out.println(1); continue; } else{ if(a[0] == n && a[n-1] == 1){ System.out.println(3); continue; } System.out.println(2); continue; } } for(int i=0;i<n;i++){ if(a[i] != i+1){ count++; break; } } System.out.println(count); } } static void swap(int[] a, int i, int j) { int x = a[i]; int y = a[j]; a[i] = y; a[j] = x; } // Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2 // worst case since it uses a version of quicksort. Although this would never // actually show up in the real world, in codeforces, people can hack, so // this is needed. static void ruffleSort(int[] a) { //ruffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner 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()); } double nextDouble() { return Double.parseDouble(next()); } String str = ""; String nextLine() { try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } // use this to find the index of any element in the array +1 /// // returns an array that corresponds to the index of the i+1th in the array a[] // runs only for array containing different values enclosed btw 0 to n-1 static int[] indexOf(int[] a) { int[] toRet=new int[a.length]; for (int i=0; i<a.length; i++) { toRet[a[i]]=i+1; } return toRet; } static int gcd(int a, int b) { if (b==0) return a; return gcd(b, a%b); } //generates all the prime numbers upto n static void sieveOfEratosthenes(int n , ArrayList<Integer> al) { 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] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) al.get(i); } } static final int mod=100000000 + 7; static final int max_val = 2147483647; static final int min_val = max_val + 1; //fastPow static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } //multiply two long numbers static long mul(long a, long b) { return a*b%mod; } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // to generate the lps array // lps means longest preffix that is also a suffix static void generateLPS(int lps[] , String p){ int l = 0; int r = 1; while(l < p.length() && l < r && r < p.length()){ if(p.charAt(l) == p.charAt(r)){ lps[r] = l + 1; l++; r++; } else{ if(l > 0) l = lps[l - 1]; else r++; } } } //count sort --> it runs in O(n) time but compromises in space static ArrayList<Integer> countSort(int a[]){ int max = Integer.MIN_VALUE; for(int i=0;i<a.length;i++){ max = Math.max(max , a[i]); } int posfre[] = new int[max+1]; boolean negPres = false; for(int i=0;i<a.length;i++){ if(a[i]>=0){ posfre[a[i]]++; } else{ negPres = true; } } ArrayList<Integer> res = new ArrayList<>(); if(negPres){ int min = Integer.MAX_VALUE; for(int i=0;i<a.length;i++){ min = Math.min(min , a[i]); } int negfre[] = new int[-1*min+1]; for(int i=0;i<a.length;i++){ if(a[i]<0){ negfre[-1*a[i]]++; } } for(int i=min;i<0;i++){ for(int j=0;j<negfre[-1*i];j++){ res.add(i); } } for(int i=0;i<=max;i++){ for(int j=0;j<posfre[i];j++){ res.add(i); } } return res; } for(int i=0;i<=max;i++){ for(int j=0;j<posfre[i];j++){ res.add(i); } } return res; } // returns the index of the element which is just smaller than or // equal to the tar in the given arraylist static int lowBound(ArrayList<Integer> ll , long tar , int l , int r){ if(l > r) return l; int mid = l + (r - l) / 2; if(ll.get(mid) >= tar){ return lowBound(ll , tar , l , mid - 1); } return lowBound(ll , tar , mid + 1 , r); } // returns the index of the element which is just greater than or // equal to the tar in the given arraylist static int upBound(ArrayList<Integer> ll , long tar , int l , int r){ if(l > r) return l; int mid = l + (r - l) / 2; if(ll.get(mid) <= tar){ return upBound(ll , tar , l , mid - 1); } return upBound(ll , tar , mid + 1 , r); } // a -> z == 97 -> 122 // String.format("%.9f", ans) ,--> to get upto 9 decimal places , (ans is double) // write }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
bee50331342938956f978bc47f4eeac4
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class MyClass { public static void main(String []args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()); String s[] = br.readLine().split(" "); int arr[] =new int[s.length]; int b[] = new int[s.length]; for(int i=0;i<arr.length;i++) { arr[i] = Integer.parseInt(s[i]); b[i] = arr[i]; } Arrays.sort(b); int c[] =new int[b.length]; int in = 0; for(int i = b.length-1;i>=0;i--) { c[in++] = b[i]; } if(Arrays.equals(arr,b)) { System.out.println("0"); } else if(arr[0]==b[0]) { System.out.println("1"); } else if(Arrays.equals(arr,c)) { System.out.println("3"); } else if(arr.length>3&&arr[b.length-1]==b[0]&&arr[0]==b[b.length-1]) { System.out.println("3"); } else if(arr[b.length-1]==b[b.length-1]) { System.out.println("1"); } else { System.out.println("2"); } } } } /* 3 2 1 3 2 1 */
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
15e7fab9ac3e072177c829c805a60b71
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.Arrays; public class PermutationSort { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader sc = new Reader(); OutputStream outputStream = System.out; PrintWriter w = new PrintWriter(outputStream); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } w.println(solve(arr, n)); } w.close(); } static int solve(int[] arr, int n) { int flag = 0; for(int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { flag = 1; } } if(flag == 0) { return 0; } int first = arr[0]; int last = arr[n - 1]; Arrays.sort(arr); if(arr[0] == first || arr[n - 1] == last) { return 1; } if(arr[0] == last && arr[n - 1] == first) { return 3; } return 2; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
2d3be4f6120a03d5e03bcbaecdd5bf82
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; public class B{ public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); for(int tt=0;tt<t;tt++) { int n = fs.nextInt(); int[] arr = new int[n+1]; for(int i=1;i<=n;i++) { arr[i] = fs.nextInt(); } boolean flag = true; for(int i=1;i<=n;i++) { if(arr[i]!=i) { flag = false; break; } } if(flag == true) { out.println("0"); } else { if(arr[1] == 1 || arr[n] == n) { out.println("1"); } else if(arr[1] == n && arr[n] == 1) { out.println("3"); } else { out.println("2"); } } } out.close(); } 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[] sort(int[] arr) { List<Integer> temp = new ArrayList(); for(int i:arr)temp.add(i); Collections.sort(temp,Collections.reverseOrder()); int start = 0; for(int i:temp)arr[start++]=i; return arr; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
19140a52aca2286374b95bc1cec30968
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; //import Number_theory.pair; public class hacker49 { public static int r1=0; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class pair{ private long cnt; private long[] fq; private long[] pref; pair(){ fq=new long[41]; pref=new long[41]; cnt=(long)0; } } public static void main(String[] args) { OutputStream outputStream =System.out; PrintWriter out =new PrintWriter(outputStream); FastReader s=new FastReader(); int t=s.nextInt(); while(t>0) { int n=s.nextInt(); int[] a=new int[n+1]; int k=0; int j=0; for(int i=1;i<=n;i++) { a[i]=s.nextInt(); if(a[i]==1) { k=i; } if(a[i]==n) { j=i; } } int g=0; if(n%2==0) { g=n/2; }else { g=n/2+1; } boolean p=true; out:for(int i=1;i<=n;i++) { if(a[i]!=i) { p=false; break out; } } // out.println(k+" "+j); if(p) { out.println(0); }else { if(a[1]==1 || a[n]==n) { out.println(1); }else if(k==n && j==1){ out.println(3); }else { out.println(2); } } t--; } out.close(); } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } // static class node{ // private int a; // private int b; // private int c; // private int d; // // } static ArrayList<Integer>[][] f1=new ArrayList[101][101]; static boolean[][] vis=new boolean[101][101]; public static void dfs(int node,int c) { vis[c][node]=true; for(int i=0;i<f1[c][node].size();i++) { if(!vis[c][f1[c][node].get(i)]) { dfs(f1[c][node].get(i),c); } } } public static class node{ private int a; private int b; node(int a,int b){ this.a=a; this.b=b; } } public static long GCD(long a,long b) { if(b==(long)0) { return a; } return GCD(b , a%b); } public static void Create(node[] arr,node[] segtree,int low,int high,int pos) { if(low==high) { segtree[pos]=arr[low]; return; } int mid=(low+high)/2; Create(arr,segtree,low,mid,2*pos+1); Create(arr,segtree,mid+1,high,2*pos+2); if(segtree[2*pos+1].a+segtree[2*pos+2].a>=10) { int a=segtree[2*pos+1].a; int b=segtree[2*pos+2].a; int c=segtree[2*pos+1].b; int d=segtree[2*pos+2].b; segtree[pos]=new node((a+b)%10,1+c+d); }else { int a=segtree[2*pos+1].a; int b=segtree[2*pos+2].a; int c=segtree[2*pos+1].b; int d=segtree[2*pos+2].b; segtree[pos]=new node(a+b,c+d); } } public static node Query(node[] segtree,int qlow,int qhigh,int low,int high,int pos) { if(low>=qlow && high<=qhigh) { return segtree[pos]; } if(qhigh<low || qlow>high) { return new node(0,0); } int mid=(low+high)/2; node a=Query(segtree,qlow,qhigh,low,mid,2*pos+1); node b=Query(segtree,qlow,qhigh,mid+1,high,2*pos+2); int c=a.a; int d=b.a; if(c+d>=10) { node e=new node((c+d)%10,1+a.b+b.b); return e; }else { node e=new node(c+d,a.b+b.b); return e; } } static class pair1 implements Comparable<pair1>{ private int a; private int b; private int c; private int d; pair1(int a,int b,int c,int d){ this.a=a; this.b=b; this.c=c; this.d=d; } public int compareTo(pair1 o) { if(this.a<o.a) { return 1; }else if(this.a==o.a) { if(this.b<o.b) { return 1; }else { return -1; } }else { return -1; } } } // public static class pair5{ // private int a; // private int b; // pair5(int a,int b){ // this.a=a; // this.b=b; // } // public int compareTo(pair5 o) { // return Integer.compare(o.b, this.b); // } // } // public static pair5[] merge_sort(pair5[] A, int start, int end) { // if (end > start) { // int mid = (end + start) / 2; // pair5[] v = merge_sort(A, start, mid); // pair5[] o = merge_sort(A, mid + 1, end); // return (merge(v, o)); // } else { // pair5[] y = new pair5[1]; // y[0] = A[start]; // return y; // } // } // public static pair5[] merge(pair5 a[], pair5 b[]) { //// int count=0; // pair5[] temp = new pair5[a.length + b.length]; // int m = a.length; // int n = b.length; // int i = 0; // int j = 0; // int c = 0; // while (i < m && j < n) { // if (a[i].a < b[j].a) { // temp[c++] = a[i++]; // } else { // temp[c++] = b[j++]; // } // } // while (i < m) { // temp[c++] = a[i++]; // } // while (j < n) { // temp[c++] = b[j++]; // } // return temp; // } //// // public static int upper_bound(long[] a ,int n,long x) { // int l=-1; // int r=n; // while(r>l+1) { // int mid=(l+r)/2; // if(a[mid]<x) { // l=mid; // }else { // r=mid; // } // } // return r; // // } // // // // public static int lower_bound(pair5[] a ,int n,int x) { // int l=-1; // int r=n; // while(r>l+1) { // int mid=(l+r)/2; // if(a[mid].a<x) { // l=mid; // }else { // r=mid; // } // } // return l; // // } static boolean isValid(int x,int y,int n,int m) { if(x>=1 && x<=n && y>=1 && y<=m) { return true; }else { return false; } } public static boolean equal_Sum_Partition(long[] a,int n) { long sum=0; for(int i=1;i<=n;i++) { sum+=a[i]; } if(sum%2!=0) { return false; }else { return subset_Sum_Using_Knapsack(a,n,sum/2); } } public static boolean subset_Sum_Using_Knapsack(long[] a,int n,long sum) { int[][] dp=new int[n+1][(int) (sum+1)]; for(int i=0;i<=n;i++) { dp[i][0]=1; } for(int i=1;i<=n;i++) { for(int j=1;j<=sum;j++) { if(a[i]<=j) { dp[i][j]=Math.max((dp[i-1][j]),(dp[i-1][(int) (j-a[i])])); }else { dp[i][j]=dp[i-1][j]; } } } return dp[n][(int) sum]==1; } static long[] fac=new long[1000001]; static void fac() { fac[0]=1; for(int i=1;i<=1000000;i++) { fac[i]=((fac[i-1]%mod)*(i%mod))%mod; } } static ArrayList<Integer>[] f=new ArrayList[2001]; public static void init(int n) { for(int j=1;j<=n;j++) { for (int l=1; l<=Math.sqrt(j); l++) { if (j%l==0) { // If divisors are equal, print only one if (j/l == l) { f[j].add(l);} else { // Otherwise print both // System.out.print(i+" " + n/i + " " ); f[j].add(l); f[j].add(j/l); } } } } } public static int rod_cutting_with_left_right_strategy(int[] a,int n) { int[] dp=new int[n+1]; dp[1]=a[1]; for(int i=2;i<=n;i++) { dp[i]=a[i]; int left=1; int right=i-1; while(left<=right) { dp[i]=Math.max(dp[left]+dp[right],dp[i]); left++; right--; } } return dp[n]; } public static long[] merge_sort(long[] A, int start, int end) { if (end > start) { int mid = (end + start) / 2; long[] v = merge_sort(A, start, mid); long[] o = merge_sort(A, mid + 1, end); return (merge(v, o)); } else { long[] y = new long[1]; y[0] = A[start]; return y; } } public static long[] merge(long a[], long b[]) { // int count=0; long[] temp = new long[a.length + b.length]; int m = a.length; int n = b.length; int i = 0; int j = 0; int c = 0; while (i < m && j < n) { if (a[i] > b[j]) { temp[c++] = a[i++]; } else { temp[c++] = b[j++]; } } while (i < m) { temp[c++] = a[i++]; } while (j < n) { temp[c++] = b[j++]; } return temp; } public static long[] merge_sort1(long[] A, int start, int end) { if (end > start) { int mid = (end + start) / 2; long[] v = merge_sort1(A, start, mid); long[] o = merge_sort1(A, mid + 1, end); return (merge1(v, o)); } else { long[] y = new long[1]; y[0] = A[start]; return y; } } public static long[] merge1(long a[], long b[]) { // int count=0; long[] temp = new long[a.length + b.length]; int m = a.length; int n = b.length; int i = 0; int j = 0; int c = 0; while (i < m && j < n) { if (a[i] > b[j]) { temp[c++] = a[i++]; } else { temp[c++] = b[j++]; } } while (i < m) { temp[c++] = a[i++]; } while (j < n) { temp[c++] = b[j++]; } return temp; } static long mod=1000000007; static class pair2{ private long a; private int b; pair2(long a,int b){ this.a=a; this.b=b; } } // for(int i=2;i<=100000;i++) { }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
318c01ddcb76f3d38bd59b04a23705df
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Checking { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100); private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100); private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; t = fs.nextInt(); while (t-- > 0) { solve(); } fw.out.close(); } private static void solve() { int n = fs.nextInt(); int[] arr = new int[n]; int [] arr2 = new int[n]; for(int i = 0; i<n ; i++){ arr[i] = fs.nextInt(); arr2[i] = arr[i]; } Arrays.sort(arr2); int ans = 2; if(Arrays.equals(arr, arr2)){ ans = 0; } else if(arr[0] == 1 || arr[n-1] == n) { ans = 1; }else if(arr[0] == n && arr[n-1] == 1){ ans = 3; } fw.out.println(ans); } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } // private static class Calc_nCr { // private final long[] fact; // private final long[] invfact; // private final int p; // // Calc_nCr(int n, int prime) { // fact = new long[n + 5]; // invfact = new long[n + 5]; // p = prime; // // fact[0] = 1; // for (int i = 1; i <= n; i++) { // fact[i] = (i * fact[i - 1]) ; // } // // invfact[n] = pow(fact[n], p - 2); // for (int i = n - 1; i >= 0; i--) { // invfact[i] = (invfact[i + 1] * (i + 1)) ; // } // } // // private long nCr(int n, int r) { // if (r > n || n < 0 || r < 0) return 0; // return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; // } // } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) ; } a = (a * a) ; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static int noOfSetBits(long x) { int cnt = 0; while (x != 0) { x = x & (x - 1); cnt++; } return cnt; } private static boolean isPerfectSquare(long num) { long sqrt = (long) Math.sqrt(num); return ((sqrt * sqrt) == num); } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static void randomizeIntArr(int[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInIntArr(arr, i, j); } } private static void randomizeLongArr(long[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInLongArr(arr, i, j); } } private static void swapInIntArr(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void swapInLongArr(long[] arr, int a, int b) { long temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static int[] readIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static long[] readLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextLong(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static List<Long> readLongList(int n) { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextLong()); return list; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
50cc9a5b30fb80ef35a4be00582d18a0
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer st; public static void main(String[] YDSV) throws IOException{ //int t=1; int t=Integer.parseInt(br.readLine()); while(t-->0) Solve(); bw.flush(); } public static void Solve() throws IOException{ st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int[] ar=getArrIn(n); int[] brr=ar.clone(); Arrays.sort(brr); if(Arrays.equals(ar,brr)) bw.write("0\n"); else if(ar[0]==1 || ar[n-1]==n) bw.write("1\n"); else if(ar[n-1]==1 && ar[0]==n) bw.write("3\n"); else bw.write("2\n"); } /** Helpers**/ public static int Gcd(int a,int b){ if(b==0) return a; return Gcd(b,a%b); } public static int[] getArrIn(int n) throws IOException{ st=new StringTokenizer(br.readLine()); int[] ar=new int[n]; for(int i=0;i<n;i++) ar[i]=Integer.parseInt(st.nextToken()); return ar; } public static List<Integer> getListIn(int n) throws IOException{ st=new StringTokenizer(br.readLine()); List<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++) al.add(Integer.parseInt(st.nextToken())); return al; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
e3895e323ada6064e6b0a2014179e0ff
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class test { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); int[] a = new int[n]; StringTokenizer tokenizer = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(tokenizer.nextToken()); } pw.println(solve(a, n)); } pw.flush(); pw.close(); br.close(); } public static int solve(int[] a, int n) { boolean sorted = true; for (int i = 0; i < n; i++) { if (a[i] != i + 1) { sorted = false; break; } } if (sorted) return 0; if (a[0] == 1 || a[n - 1] == n) { return 1; } if (a[0] == n && a[n - 1] == 1) { return 3; } return 2; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
d610a8fa899477488551eca4156fee7b
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import com.sun.security.jgss.GSSUtil; import java.util.*; import java.io.*; public class cf1525B { public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); ArrayList<Integer> list = new ArrayList<>(); boolean isSorted = true; for (int j = 0; j < n; j++) { int temp = in.nextInt(); list.add(temp); if (temp != j + 1){ isSorted = false; } } if (isSorted){ System.out.println(0); continue; } if (list.get(0) == 1 || list.get(list.size() - 1) == n){ System.out.println(1); } else if (list.get(0) == n && list.get(list.size() - 1) == 1){ System.out.println(3); } else { System.out.println(2); } } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
d695f25bbc119fb17507cb427a120084
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.math.*; import java.text.DecimalFormat; //import java.io.*; public class Experiment { static Scanner in=new Scanner(System.in); // static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); public static void sort(int ar[],int l,int r) { if(l<r) { int m=l+(r-l)/2; sort(ar,l,m); sort(ar,m+1,r); merge(ar,l,m,r); } } public static int hcf(int x,int y) { if(y==0) return x; return hcf(y,x%y); } public static void merge(int ar[],int l,int m,int r) { int n1=m-l+1;int n2=r-m; int L[]=new int[n1]; int R[]=new int[n2]; for(int i=0;i<n1;i++) L[i]=ar[l+i]; for(int i=0;i<n2;i++) R[i]=ar[m+i+1]; int i=0;int j=0;int k=l; while(i<n1 && j<n2) { if(L[i]<=R[j]) { ar[k++]=L[i++]; }else { ar[k++]=R[j++]; } } while(i<n1) ar[k++]=L[i++]; while(j<n2) ar[k++]=R[j++]; } public static int[] sort(int ar[]) { sort(ar,0,ar.length-1); //Array.sort uses O(n^2) in its worst case ,so better use merge sort return ar; } public static void func() { int n=in.nextInt(); int ar[]=new int[n];int max=Integer.MIN_VALUE;int j=0; for(int i=1;i<=n;i++) { ar[i-1]=in.nextInt(); if(ar[i-1]>max) { max=ar[i-1];j=i-1; } } int a[]=ar.clone(); sort(a); int count=0; for(int i=0;i<n;i++) { if(a[i]!=ar[i]) count++; } if(count==0) System.out.println(0); else if(j==ar.length-1 || ar[0]==a[0]) System.out.println(1); else if(ar[0]==a[ar.length-1] && ar[ar.length-1]==a[0]) System.out.println(3); else System.out.println(2); } public static void main(String[] args) { int t=in.nextInt(); while(t!=0) { func(); t--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
3811600e27df7d6fa5591301dd06a4ac
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; /** * Provide prove of correctness before implementation. Implementation can cost a lot of time. * Anti test that prove that it's wrong. * <p> * Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation * <p> * Will program ever exceed limit? * Try all approaches with prove of correctness if task is not obvious. * If you are given formula/rule: Try to play with it. * Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data * Number theory * Game theory (optimal play) that consider local and global strategy. */ public class CF1525B { private void solveOne() { int n = nextInt(); int[] a = nextIntArr(n); int min = a[n - 1]; int max = a[n - 1]; boolean sorted = true; for (int i = 0; i < n - 1; i++) { sorted &= a[i] < a[i + 1]; min = Math.min(min, a[i]); max = Math.max(max, a[i]); } if(sorted) { System.out.println(0); } else if(a[0] == min || a[n - 1] == max) { System.out.println(1); } else if(a[0] == max && a[n - 1] == min) { System.out.println(3); } else { System.out.println(2); } } private void solve() { int t = System.in.readInt(); for (int tt = 0; tt < t; tt++) { solveOne(); } } class AssertionRuntimeException extends RuntimeException { AssertionRuntimeException(Object expected, Object actual, Object... input) { super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input)); } } private int nextInt() { return System.in.readInt(); } private long nextLong() { return System.in.readLong(); } private String nextString() { return System.in.readString(); } private int[] nextIntArr(int n) { return System.in.readIntArray(n); } private long[] nextLongArr(int n) { return System.in.readLongArray(n); } public static void main(String[] args) { new CF1525B().run(); } static class System { private static FastInputStream in; private static FastPrintStream out; } private void run() { System.in = new FastInputStream(java.lang.System.in); System.out = new FastPrintStream(java.lang.System.out); solve(); System.out.flush(); } private static class FastPrintStream { private static final int BUF_SIZE = 8192; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastPrintStream() { this(java.lang.System.out); } public FastPrintStream(OutputStream os) { this.out = os; } public FastPrintStream(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastPrintStream print(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastPrintStream print(char c) { return print((byte) c); } public FastPrintStream print(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastPrintStream print(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } //can be optimized public FastPrintStream print0(char[] s) { if (ptr + s.length < BUF_SIZE) { for (char c : s) { buf[ptr++] = (byte) c; } } else { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } } return this; } //can be optimized public FastPrintStream print0(String s) { if (ptr + s.length() < BUF_SIZE) { for (int i = 0; i < s.length(); i++) { buf[ptr++] = (byte) s.charAt(i); } } else { for (int i = 0; i < s.length(); i++) { buf[ptr++] = (byte) s.charAt(i); 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 FastPrintStream print(int x) { if (x == Integer.MIN_VALUE) { return print((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { print((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 FastPrintStream print(long x) { if (x == Long.MIN_VALUE) { return print("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { print((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 FastPrintStream print(double x, int precision) { if (x < 0) { print('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } print((long) x).print("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; print((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastPrintStream println(char c) { return print(c).println(); } public FastPrintStream println(int x) { return print(x).println(); } public FastPrintStream println(long x) { return print(x).println(); } public FastPrintStream println(String x) { return print(x).println(); } public FastPrintStream println(double x, int precision) { return print(x, precision).println(); } public FastPrintStream println() { return print((byte) '\n'); } 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"); } } } private static class FastInputStream { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastInputStream(InputStream stream) { this.stream = stream; } public double[] readDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) { array[i] = readDouble(); } return array; } public String[] readStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) { array[i] = readString(); } return array; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public void readLongArrays(long[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readLong(); } } } public void readDoubleArrays(double[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readDouble(); } } } public char[][] readTable(int rowCount, int columnCount) { char[][] table = new char[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = this.readCharArray(columnCount); } return table; } public int[][] readIntTable(int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = readIntArray(columnCount); } return table; } public double[][] readDoubleTable(int rowCount, int columnCount) { double[][] table = new double[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = this.readDoubleArray(columnCount); } return table; } public long[][] readLongTable(int rowCount, int columnCount) { long[][] table = new long[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = readLongArray(columnCount); } return table; } public String[][] readStringTable(int rowCount, int columnCount) { String[][] table = new String[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = this.readStringArray(columnCount); } return table; } public String readText() { StringBuilder result = new StringBuilder(); while (true) { int character = read(); if (character == '\r') { continue; } if (character == -1) { break; } result.append((char) character); } return result.toString(); } public void readStringArrays(String[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readString(); } } } public long[] readLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } 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 peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int peekNonWhitespace() { while (isWhitespace(peek())) { read(); } return peek(); } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { 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 String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return readString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
486142864a1dda5cbc474c2f4f1d0477
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class specialPerm { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t-->0){ int n = scan.nextInt(); int[] arr = new int[n+1]; boolean found = false; for(int i=1;i<=n;i++){ arr[i] = scan.nextInt(); if(i!=arr[i]) found=true; } if(!found) System.out.println("0"); else{ if(1==arr[1] || n==arr[n]) System.out.println("1"); else if(arr[1]==n && arr[n]==1) System.out.println("3"); else if(arr[1]==n && arr[n]!=1) System.out.println("2"); else System.out.println("2"); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
6394c27efec9802c3ae87eab957f9763
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class A { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static int createPalindrome(int input, int b, int isOdd) { int n = input; int palin = input; if (isOdd == 1) n /= b; while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin; } static void generatePalindromes(int n) { int number; for (int j = 0; j < 2; j++) { int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { System.out.print(number + " "); i++; } } } static void swap(int c,int d) { c^=d; d^=c; c^=d; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc= new FastReader(); int q= sc.nextInt(); while(q-->0) { int n= sc.nextInt(); int arr[]= new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); int x=0; for(int i=0;i<n-1;i++) { if(arr[i]>arr[i+1]) { x=1; break; } } if(x==0) System.out.println(0); else if(arr[0]==n && arr[n-1]==1) System.out.println(3); else if(arr[0]==1 || arr[n-1]==n) System.out.println(1); else System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
0e970585fff47d26f8da18fde15a9ec7
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Main { public static void main(String[] srgs) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- >0){ int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } System.out.println(PermutationSort(arr)); } } public static int PermutationSort(int[] arr){ boolean flag=true; for(int i=0;i<arr.length;i++){ if (arr[i]!=(i+1)){ flag=false; break; } } if (flag){ return 0; } else if(arr[0]==1 || arr[arr.length-1]==arr.length){ return 1; } else if (arr[0]==arr.length && arr[arr.length-1]==1){ return 3; } else{ return 2; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c5952b37954c847677564ae583d7179c
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class B_Permutation_Sort { public static void main (String[] args) throws java.lang.Exception { FastReader sc =new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int arr[]=sc.readArray(n); int arr2[]=new int[n]; int ans=2; for(int i=0;i<arr.length;i++){ arr2[i]=arr[i]; } Arrays.sort(arr); if(Arrays.equals(arr, arr2)){ ans=0; } else if(arr2[0]==1 || arr2[n-1]==n){ ans=1; } else if(arr2[0]==n && arr2[n-1]==1){ ans=3; } System.out.println(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()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for(int v : a) { c0[(v&0xff)+1]++; c1[(v>>>8&0xff)+1]++; c2[(v>>>16&0xff)+1]++; c3[(v>>>24^0x80)+1]++; } for(int i = 0;i < 0xff;i++) { c0[i+1] += c0[i]; c1[i+1] += c1[i]; c2[i+1] += c2[i]; c3[i+1] += c3[i]; } int[] t = new int[n]; for(int v : a)t[c0[v&0xff]++] = v; for(int v : t)a[c1[v>>>8&0xff]++] = v; for(int v : a)t[c2[v>>>16&0xff]++] = v; for(int v : t)a[c3[v>>>24^0x80]++] = v; return a; } static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } static boolean palindrome_array(int arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) return false; else return true; } static boolean allElementsEqual(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]==arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } static boolean allElementsDistinct(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]!=arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } public static void reverse_Long(long[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily long temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static boolean isReverseSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static int[] rearrangeEvenAndOdd(int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); int[] array = list.stream().mapToInt(i->i).toArray(); return array; } static long[] rearrangeEvenAndOddLong(long arr[], int n) { ArrayList<Long> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); long[] array = list.stream().mapToLong(i->i).toArray(); return array; } static boolean isPrime(long n) { // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcdLong(long a, long b) { if (b == 0) return a; return gcdLong(b, a % b); } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
bac47c90ffb0f3bc7feb7207035653f6
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// created by faizal import java.io.PrintWriter; import java.util.*; public class UziUzi { static int[] dp; public static void main(String[] args) { long start = System.currentTimeMillis(); Scanner fk = new Scanner(System.in); PrintWriter pr = new PrintWriter(System.out); int t = fk.nextInt(); while(t-- > 0){ int n = fk.nextInt(); int[] arr = new int [n]; boolean isSorted = true; for(int i =0; i<n; i++) { arr[i] = fk.nextInt(); if(i != 0 && arr[i] < arr[i-1] && isSorted) isSorted = false; } int k = 0; if(arr[0] != 1 && arr[n-1] != n){ if(arr[0] == n && arr[n-1] == 1) k = 3; else k = 2; }else k = 1; pr.println(isSorted? "0" : k); } pr.close(); } private static int fxn(int target, int[] arr) { if(target == 0) return 0; int ans = Integer.MAX_VALUE; for(int i : arr){ if(target - i >= 0){ int min; if(dp[target - i] != -1) min = dp[target-i]; else { min = fxn(target - i, arr); } if (min != Integer.MAX_VALUE && min + 1 < ans) { ans = min + 1; dp[target] = ans; } } } return dp[target] = ans; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
138c40ea7b84c60643a941de18dad767
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0) { int n=s.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); b[i]=a[i]; } Arrays.sort(b); if(Arrays.equals(a,b)) { System.out.println("0"); } else if(a[0]==1||a[n-1]==n) { System.out.println("1"); } else if(a[0]==n&&a[n-1]==1) { System.out.println("3"); } else{ System.out.println("2"); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
d164e2c9aa106b610a7eca2a4acd3e34
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Practise { public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String args[]) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-->0) { int n=in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for(int i=0;i<n;i++) { int temp = in.nextInt(); a[i]=temp; b[i]=temp; } Arrays.sort(b); int flag = 0; for(int i=0;i<n;i++) { if(a[i]!=b[i]) { flag=1; break; } } if(flag==0) { System.out.println("0"); } else { int j=0; for(int i=n-1;i>=0;i--) { if(a[j]!=b[i]) { flag=1; break; } j++; } if(flag==0 || (a[0]==b[n-1] && a[n-1]==b[0])) { System.out.println("3"); } else { if(a[0]==b[0] || a[n-1] == b[n-1]) System.out.println("1"); else System.out.println("2"); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
5f413f67fc9cd30d3183161c7b57cea1
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//1525B import java.util.*; public class PermutationSort { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); //upper bound 3 int[] a = new int[n]; for(int i = 0; i<n; i++) { int x = s.nextInt(); a[i]=x; } if(countDecrements(a)==0) { System.out.println(0); } else if((a[0]==1&&countDecrements(a)>0)||(a[n-1]==n&&countDecrements(a)>0)) { System.out.println(1); } else if(a[0]==n&&a[n-1]==1) { System.out.println(3); } else { System.out.println(2); } } } public static int countDecrements(int[] arr) { int counter = 0; for(int i = 0; i<arr.length-1; i++) { if(arr[i+1]<arr[i]) { counter++; } } return counter; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
90feaddfb5902d3f6f6c5cc43b79a057
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//1525B import java.util.*; public class PermutationSort { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); //upper bound 3 int[] a = new int[n]; int[] b = new int[n]; for(int i = 0; i<n; i++) { int x = s.nextInt(); a[i]=x; b[i]=x; } Arrays.sort(b); if(countDecrements(a)==0) { System.out.println(0); } else if((a[0]==1&&countDecrements(a)>0)||(a[n-1]==n&&countDecrements(a)>0)) { System.out.println(1); } else if(a[0]==n&&a[n-1]==1) { System.out.println(3); } else { System.out.println(2); } } } public static int countDecrements(int[] arr) { int counter = 0; for(int i = 0; i<arr.length-1; i++) { if(arr[i+1]<arr[i]) { counter++; } } return counter; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
286b9e11b86fa4064fa8f3ebcc4a8e49
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// Author : RegalBeast import java.io.*; import java.util.*; public class Main implements Runnable { static Input in = new Input(); static PrintWriter out = Output(); public static void main(String[] args) { new Thread(null, new Main(), String.join( "All that is gold does not glitter,", "Not all those who wander are lost;", "The old that is strong does not wither,", "Deep roots are not reached by the frost.", "From the ashes a fire shall be woken,", "A light from the shadows shall spring;", "Renewed shall be blade that was broken,", "The crownless again shall be king." ), 1<<25).start(); } public void run() { int tests = in.nextInt(); for (int t = 0; t < tests; t++) { int n = in.nextInt(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { permutation[i] = in.nextInt(); } int movesRequired = computeMovesRequired(permutation); out.println(movesRequired); } in.close(); out.close(); } static int computeMovesRequired(int[] permutation) { boolean sorted = true; for (int i = 0; i < permutation.length; i++) { if (permutation[i] != i+1) { sorted = false; break; } } if (sorted) { return 0; } if (permutation[0] == 1 || permutation[permutation.length-1] == permutation.length) { return 1; } if (permutation[0] > permutation[permutation.length-1]) { if (permutation[0] == permutation.length && permutation[permutation.length-1] == 1) { return 3; } } return 2; } static PrintWriter Output() { return new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } static PrintWriter Output(String fileName) { PrintWriter pw = null; try { pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); } catch (IOException ex) { ex.printStackTrace(); } return pw; } } class Input { BufferedReader br; StringTokenizer st; public Input() { br = new BufferedReader(new InputStreamReader(System.in)); } public Input(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (IOException ex) { ex.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException ex) { ex.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Float nextFloat() { return Float.parseFloat(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { if (st.hasMoreElements()) { StringBuilder sb = new StringBuilder(); while (st.hasMoreElements()) { sb.append(next()); } return sb.toString(); } String str = null; try { str = br.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return str; } public void close() { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
b936381b0afd15c1d139ce7ff0643723
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static FastReader sc = new FastReader(); static void solve(){ int n = sc.nextInt(); boolean av = true; int[] arr = new int[n]; arr[0] = sc.nextInt(); int max = arr[0] ,min = arr[0]; int M=0,m=0; for(int i=1;i<n;i++){ arr[i] = sc.nextInt(); if(arr[i] < arr[i-1]) av = false; if(arr[i] > max){ max = arr[i]; M = i; } if(arr[i] < min){ min = arr[i]; m =i; } } if(av){ System.out.println("0"); return;} if(M > m) if(M==(n-1) || m==0) System.out.println("1"); else System.out.println("2"); else if(M==0 && m ==(n-1))System.out.println("3"); else System.out.println("2"); } public static void main(String[] args){ int t = sc.nextInt(); while(t-->0){ solve(); } } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
ed2d6983fb31353110b4ab59d83eaea6
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static FastReader sc = new FastReader(); static void solve(){ int n = sc.nextInt(); boolean av = true; int[] arr = new int[n]; arr[0] = sc.nextInt(); int max = arr[0] ,min = arr[0]; int M=0,m=0; for(int i=1;i<n;i++){ arr[i] = sc.nextInt(); if(arr[i] < arr[i-1]) av = false; if(arr[i] > max){ max = arr[i]; M = i; } if(arr[i] < min){ min = arr[i]; m =i; } } if(av){ System.out.println("0"); return;} if(M > m) if(M==(n-1) || m==0) System.out.println("1"); else System.out.println("2"); else if(M==0 && m ==(n-1))System.out.println("3"); else System.out.println("2"); } public static void main(String[] args){ int t = sc.nextInt(); while(t-->0){ solve(); } } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8ce4a3cf95a76d75e923666b74f0c51f
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// MZML BOY// import java.io.*; import java.util.*; public class Main{ static FastReader sc = new FastReader(); static void solve(){ int n = sc.nextInt(); boolean av = true; int[] arr = new int[n]; arr[0] = sc.nextInt(); int max = arr[0] ,min = arr[0]; int M=0,m=0; for(int i=1;i<n;i++){ arr[i] = sc.nextInt(); if(arr[i] < arr[i-1]){ av = false; } if(arr[i] > max){ max = arr[i]; M = i; } if(arr[i] < min){ min = arr[i]; m =i; } } if(av){System.out.println("0");return;} //System.out.println(M+" "+m+"_____"); if(M > m){ if(M==(n-1) || m==0){ System.out.println("1"); return ; }else{ System.out.println("2"); return; } }else{ if(M==0 && m ==(n-1)){ System.out.println("3"); return ; } System.out.println("2"); } } public static void main(String[] args){ int t = sc.nextInt(); while(t-->0){ solve(); } } } 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
62892489d083a12b816a7ef8a3a372e7
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class test{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); for(int i=0;i<t;i++){ int n = scn.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for(int j=0;j<n;j++){ a[j]=scn.nextInt(); b[j]=a[j]; } Arrays.sort(b); if(Arrays.equals(a,b)){ System.out.println(0); }else if(b[0]==a[0] || b[n-1]==a[n-1]){ System.out.println(1); } else if (b[n-1]==a[0] && b[0]==a[n-1]){ System.out.println(3); } else{ System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
5d8211c760ea722c8a00449ea56b9e19
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); boolean good = false; boolean bad1 = false; boolean bad2 = false; boolean right = true; for(int i = 0; i < n; i++) { int x = in.nextInt(); if(i == 0 && x == 1 || i == n - 1 && x == n) { good = true; } if(i == 0 && x == n) { bad1 = true; } if(i == n - 1 && x == 1) { bad2 = true; } if(x != i + 1) { right = false; } } if(right) { pw.println(0); } else if(good) { pw.println(1); } else if(bad1 && bad2) { pw.println(3); } else { pw.println(2); } } pw.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8895c56ab0f32839fd6bfdcd34fa09fb
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { try{ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int arr[]=new int[n]; int pos=0; int pos1=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); if(arr[i]==1) pos=i; if(arr[i]==n) pos1=i; } if(pos==0){ boolean yes=true; for(int i=1;i<n;i++){ if(arr[i]!=i+1){ yes=false; break; } } if(yes) System.out.println("0"); else System.out.println("1"); } else if(pos==n-1){ if(pos1!=0) System.out.println("2"); else System.out.println("3"); } else{ boolean yes=true; for(int i=pos+1;i<n;i++){ if(arr[i]!=i+1){ yes=false; break; } } if(yes) System.out.println("1"); else if(yes==false&&pos1==n-1) System.out.println("1"); else System.out.println("2"); } } }catch(Exception e){ return; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
974464b3a7afd3997b7fd0e5fb2e0881
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.util.Scanner; public class PermutationSort { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int t = sc.nextInt(); boolean isSorted =false; while(t--!=0) { int n =sc.nextInt(); int[] a = new int[n]; for(int i=0 ;i<n;i++) { a[i] = sc.nextInt(); } if(isSorted(a,n)) { System.out.println(0); }else if(a[0] ==1 || a[n-1]==n) { System.out.println(1); }else if(a[0]==n && a[n-1]==1) { System.out.println(3); }else { System.out.println(2); } } } public static boolean isSorted(int a[], int n){ for(int i=0; i<n-1; i++) { if(a[i]>a[i+1]) { return false; } } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9efb55d1001b34d8278369211a7576d2
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class rand2 { public static void main(String[] args) throws IOException { InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); int T=Integer.parseInt(br.readLine()); int arr2[]=new int[T]; for(int i=0;i<T;i++) { int b=Integer.parseInt(br.readLine()); int c=b; String s= br.readLine(); StringTokenizer st=new StringTokenizer(s); int arr[]=new int[b]; int arr4[]=new int[b]; int min=b+1; int max=0; int arr1[][]=new int[2][2]; for(int j=0;j<b;j++) { if (st.hasMoreTokens()) { arr4[j]=j+1; arr[j] = Integer.parseInt(st.nextToken()); if(arr4[j]==arr[j]) c--; } if(arr[j]>max) { max=arr[j]; arr1[1][0]=max; arr1[1][1]=j; } if(arr[j]<min){ min=arr[j]; arr1[0][0]=min; arr1[0][1]=j; } } if(c==0) { arr2[i]=0; } else if(arr1[0][1]==0||arr1[1][1]==b-1) { arr2[i]=1; } else if(arr1[0][1]==b-1&&arr1[1][1]==0) { arr2[i]=3; } else { arr2[i]=2; } } for(int i=0;i<T;i++) { System.out.println(arr2[i]); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
4d59a3e14c8e6ae1c88b3c7ebe809e16
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.*; public class PermutationSort { 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int diff; int count; public Pair(int diff, int count) { super(); this.diff = diff; this.count = count; } } public static void main(String[] args) { FastScanner f = new FastScanner(); PrintWriter p = new PrintWriter(System.out); int t = f.nextInt(); while (t-- > 0) { int n = f.nextInt(); int arr[] = new int[n + 1]; boolean sorted = true; boolean reverse = true; for (int i = 1; i <= n; i++) { arr[i] = f.nextInt(); if (arr[i] != i) { sorted = false; } } if (sorted == true) { p.println(0); } else if (arr[1] == n && arr[n] == 1) { p.println(3); } else { HashSet<Integer> first = new HashSet<Integer>(); HashSet<Integer> second = new HashSet<Integer>(); for (int i = 1; i <= n - 1; i++) { first.add(arr[i]); } for (int i = 2; i <= n; i++) { second.add(arr[i]); } boolean one = true; boolean two = true; for (int i = 1; i <= n - 1; i++) { if (first.contains(i) == false) { one = false; break; } } for (int i = 2; i <= n; i++) { if (second.contains(i) == false) { two = false; break; } } if (one == true || two == true) { p.println(1); } else { p.println(2); } } } p.close(); } /// Ceil static long ceil(long x, long m) { long res = x / m; if (x % m != 0) { res++; } return res; } // ------------------------------------------------------------------------------------------------ // makes the prefix sum array static long[] prefixSum(long arr[], int n) { long psum[] = new long[n]; psum[0] = arr[0]; for (int i = 1; i < n; i++) { psum[i] = psum[i - 1] + arr[i]; } return psum; } // ------------------------------------------------------------------------------------------------ // makes the suffix sum array static long[] suffixSum(long arr[], int n) { long ssum[] = new long[n]; ssum[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { ssum[i] = ssum[i + 1] + arr[i]; } return ssum; } //------------------------------------------------------------------------------------------ // BINARY EXPONENTIATION OF A NUMBER MODULO M FASTER METHOD WITHOUT RECURSIVE // OVERHEADS static long m = (long) (1e9 + 7); static long binPower(long a, long n, long m) { if (n == 0) return 1; long res = 1; while (n > 0) { if ((n & 1) != 0) { res *= a; } a *= a; n >>= 1; } return res; } //------------------------------------------------------------------------------------------- // gcd static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } //------------------------------------------------------------------------------------------ // lcm static long lcm(long a, long b) { return a / gcd(a, b) * b; } //------------------------------------------------------------------------------------------ // BRIAN KERNINGHAM TO CHECK NUMBER OF SET BITS // O(LOGn) static int setBits(int n) { int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ // 0 based indexing static boolean KthBitSet(int n, int k) { int mask = 1; mask = mask <<= k; if ((mask & n) != 0) return true; else return false; } //------------------------------------------------------------------------------------------ // EXTENDED EUCLIDEAN THEOREM // TO REPRESENT GCD IN TERMS OF A AND B // gcd(a,b) = a.x + b.y where x and y are integers static long x = -1; static long y = -1; static long gcdxy(long a, long b) { if (b == 0) { x = 1; y = 0; return a; } else { long d = gcdxy(b, a % b); long x1 = y; long y1 = x - (a / b) * y; x = x1; y = y1; return d; } } //-------------------------------------------------------------------------------------------------F }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
796616c263e09101fec27fa87031f743
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B109 { public static boolean isIntegerArraySorted(int[] arr) { for (int i = 0; i < arr.length - 1; i += 1) { if (arr[i] > arr[i + 1]) { return false; } } return true; } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- int t, n; t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i += 1) { arr[i] = sc.nextInt(); } if (isIntegerArraySorted(arr)) { out.println(0); } else if (arr[0] == 1 || arr[n - 1] == n) { out.println(1); } else if (arr[0] == n && arr[n - 1] == 1) { out.println(3); } else { out.println(2); } } // Stop writing your solution here. ------------------------------------- out.close(); } // -----------PrintWriter for faster output--------------------------------- public static PrintWriter out; // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
a9b0eebf586533a5a40d3afa6ffb4dda
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class PotionSort { public static void main(String []args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t--!=0){ int n=sc.nextInt(); int ar[]=new int[n]; int a=1; for(int i=0;i<n;i++){ ar[i]=sc.nextInt(); if(ar[i]!=i+1) a=0; } if(a==1){ System.out.println("0"); continue; } if(ar[0]==1 || ar[n-1]==n) { System.out.println("1"); continue; } if(ar[0]==n && ar[n-1]==1){ System.out.println("3"); continue; } else { System.out.println("2"); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
a55ea8f71a1b45afc82607bc7d016e32
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) solve(in, out); out.close(); } static long pow(long x,long n,long M) { if(n==0) return 1; else if(n%2==0) return pow((x*x)%M,n/2, M); else return (x*pow((x*x)%M,n/2, M))%M; } static int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } static void solve(FastScanner in,PrintWriter out) { int n=in.nextInt(); int a[]=new int[n]; a=in.readArray(n); int b[]=new int[n]; b=a.clone(); sort(b); int min=1,max=0,fg=0; for (int i = 0; i < n; i++) { if(a[i]!=b[i]) fg=1; min=Math.min(a[i],min); max=Math.max(a[i],max); } if(fg==0) out.println(0); else{ if(a[0]==min||a[n-1]==max) out.println(1); else if(a[0]==max&&a[n-1]==min) out.println(3); else out.println(2); } } static class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>> { public U x; public V y; public pair(U x, V y) { this.x = x; this.y = y; } public int compareTo(pair<U, V> other) { int i = other.y.compareTo(y); if (i != 0) return i; return other.x.compareTo(x); } public String toString() { return x.toString() + " " + y.toString(); } public boolean equals(Object obj) { if (this.getClass() != obj.getClass()) return false; pair<U, V> other = (pair<U, V>) obj; return x.equals(other.x) && y.equals(other.y); } public int hashCode() { return 31 * x.hashCode() + y.hashCode(); } } 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 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 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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
174a0a5836278620ddc7c93f3a84a6b0
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; // Java Code for Palindrome Partitioning // Problem public class Code { // Driver code 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 max=Integer.MIN_VALUE,min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } boolean flag=false; for(int i=0;i<n-1;i++) { if(a[i+1]<a[i]) { flag=true; break; } } if(!flag) { System.out.println(0); } else { if(a[0]==1||a[n-1]==n) { System.out.println(1); } else if(a[0]==n&&a[n-1]==1) { System.out.println(3); } else { System.out.println(2); } } t--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
55f0d078343c9c1d220d420434b6e24d
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public final class Solution { static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); int t = sc.nextInt(); while (t-- > 0) { int count = 0; boolean flag = false; int n = sc.nextInt(); boolean isrev = false; int arr[]= new int[n+1]; for (int i = 1; i <= n; i++) { int x = sc.nextInt(); arr[i] = x; if (x == i && i == 1 || x == i && i == n) { flag = true; } if (x != i) { count++; } } if(arr[1]==n && arr[n]==1){ isrev=true; } // System.out.println(sb + " " + sb2.reverse()); if (count == 0) { System.out.println(0); } else if (isrev) { System.out.println(3); } else if (flag) { System.out.println(1); } else { System.out.println(2); } } op.flush(); } } 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(); } } // BufferedWriter output = new BufferedWriter( // new OutputStreamWriter(System.out)); // while(t-->0){ // int k=sc.nextInt(); // int [] arr= new int[(2*k)+1]; // int ans = 0; // System.out.println(k+"=> "); // for(int i=(2*k);i<(4*k)+1;i++){ // int one =k+(i*i); // int two=k+((i+1)*(i+1)); // int val = gcd(one,two); // System.out.print("["+i+" "+"("+one+"-"+two+") =>"+val+" diff=> "+(two-one)+" // ]"); // ans+=val; // } // System.out.println(); // System.out.println(); // // op.write(ans+"\n"); // }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
10bc8efc1b42d507f045a2aa0a7f3c0a
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class SortingSubArray { public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i]=sc.nextInt(); } if(sorted(arr,n)){ System.out.println(0); }else{ int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; int minIndex =0 ,maxIndex=0; for (int i = 0; i < n; i++) { int a = arr[i]; if(a<min){ min=a; minIndex=i; } if(a>max){ max=a; maxIndex=i; } } if(minIndex==0 || maxIndex==n-1){ System.out.println(1); }else if(minIndex==n-1 && maxIndex==0){ System.out.println(3); }else{ System.out.println(2); } } t--; } } static boolean sorted(int arr[], int n) { if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) if (arr[i - 1] > arr[i]) return false; return true; } //Fast Reader Class static class FastReader { BufferedReader reader; StringTokenizer mStringTokenizer; public FastReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (mStringTokenizer == null || !mStringTokenizer.hasMoreElements()) { try { mStringTokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return mStringTokenizer.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) { e.printStackTrace(); } return str; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
4fb2fa25252a871257229d704276ba91
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Codeforce{ static FastReader fs = new FastReader(); public static void main(String[] args) { int t = fs.nextInt(); while(t-- >0){ int n = fs.nextInt(), ans = 0; int[] arr = fs.readArray(n); for(int i=0;i<n;i++){ if((i+1)!=arr[i])ans=1; } if(ans==1){ if(arr[0]==1 || arr[n-1]==n) ans = 1; else if(arr[0]==n && arr[n-1]==1) ans = 3; else ans=2; } System.out.println(ans); } } public static void sort(int[] arr){ ArrayList<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); int index =0; for(int i:list) {arr[index]=i; index++;} } public static void reverse(int[] arr){ ArrayList<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list, Collections.reverseOrder()); int index =0; for(int i:list) {arr[index]=i; index++;} } static public void printArray(int[] arr){ for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } } // class Data implements Comparable<Data>{ // double x; // double a; // public Data(double x, double a){ // this.x = x; // this.a = a; // } // @Override // public int compareTo(Data o) { // if(x>o.x) return 1; // else if(x<o.x) return -1; // else return 0; // } // } class FastReader{ private BufferedReader br; private StringTokenizer str; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } private String next(){ while(str==null || !str.hasMoreTokens()){ try{ str = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return str.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(){ String s = ""; try{ s = br.readLine(); }catch(IOException e){ e.printStackTrace(); } return s; } public int[] readArray(int n){ int[] arr = new int[n]; for(int i =0;i<n;i++) arr[i] = nextInt(); return arr; } public long[] readArrayL(int n){ long[] arr = new long[n]; for(int i =0;i<n;i++) arr[i] = nextLong(); return arr; } public double[] readArrayD(int n){ double[] arr = new double[n]; for(int i =0;i<n;i++) arr[i] = nextDouble(); return arr; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
bac4272f700fa8449dc4af5acf13f957
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.util.function.BiConsumer; import javax.sound.midi.SysexMessage; import java.io.IOException; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class S2 { static 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 long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } private static int inf = 1<<27; private static long ans; private static int n; private static int k; private static int[] arr; private static char[] str; private final static int qwerty = 1000000007; private static boolean bruh; public static void main(String[] args) throws IOException { ans = 0; Reader.init(System.in); OutputStream out = new BufferedOutputStream(System.out); int tc=1; tc = Reader.nextInt(); main_loop: for(int tn=0; tn<tc; tn++) { ans=0; bruh = false; // n=tn+1; n = Reader.nextInt(); // k = Reader.nextInt(); arr = new int[n]; for(int i=0; i<n; i++) { int a = Reader.nextInt(); if(a!=i+1) { bruh = true; } arr[i] = a; } if(bruh) { if(arr[0]==1 || arr[n-1]==n) { ans=1; } else if(arr[0]==n && arr[n-1]==1){ ans=3; } else { ans=2; } } else { ans=0; } // out.write(("YES\n").getBytes()); // out.write(("NO\n").getBytes()); out.write((ans+"\n").getBytes()); } out.flush(); out.close(); } private static void dbg(int[][] dp) { // TODO Auto-generated method stub for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { System.err.print(dp[i][j]+" "); } System.err.println(); } for(int i=0; i<1001; i++) { int j=0; System.err.print(dp[i][j]+" "); } System.err.println(); for(int i=0; i<1001; i++) { int j=1; System.err.print(dp[i][j]+" "); } System.err.println();System.err.println(); for(int i=0; i<1001; i++) { int j=0; System.err.print(dp[j][i]+" "); } System.err.println(); for(int i=0; i<1001; i++) { int j=1; System.err.print(dp[j][i]+" "); } System.err.println(); System.err.println(); System.err.println(); for(int i=0; i<100; i++) { int j=249; System.err.print(dp[j][i]+" "); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8dfaa8450007fdd9cf721cbf7dbd6fde
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// https://codeforces.com/contest/1525/problem/B import java.util.Scanner; public class p_15 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = sc.nextInt(); int ar[] = new int[test]; int an = 0; for (int i = 0; i < test; i++) { int count = 0; int a = sc.nextInt(); int arr[] = new int[a]; for (int j = 0; j < a; j++) { arr[j] = sc.nextInt(); } int f = 0; for (int j = 0; j < a; j++) { if (arr[j] == j + 1) { f++; } } if (f == a) { ar[an] = 0; an++; } else if(arr[0] == 1 || arr[a-1] == a){ ar[an] = 1; an++; }else if(arr[0] == a && arr[a-1] == 1){ ar[an] = 3; an++; }else{ ar[an] = 2; an++; } } for (int i = 0; i < test; i++) { System.out.println(ar[i]); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
6df892f421f2a806b6adcc07ca3a1db9
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] arr= new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } int f=1; for(int i=1;i<n;i++){ if(arr[i]<arr[i-1]){ f=0; } } if(arr[0]==n && arr[n-1]==1){ System.out.println(3); } else if(f==1){ System.out.println(0); } else if(arr[n-1]==n || arr[0]==1){ System.out.println(1); } else{ System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
4cff971d99fc16922bc4a276a737fc32
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dauom */ 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); BPermutationSort solver = new BPermutationSort(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BPermutationSort { public final void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int ans = 0; for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { ans = 1; break; } } if (ans == 1 && !(a[0] == 1 || a[n - 1] == n)) { if (a[0] == n && a[n - 1] == 1) { ans += 2; } else { ans++; } } out.println(ans); } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1 << 18]; private int curChar; private int numChars; public InputReader() { this.stream = System.in; } public InputReader(final InputStream stream) { this.stream = stream; } private int read() { if (this.numChars == -1) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public final int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public final String next() { int c; while (isSpaceChar(c = this.read())) { } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } private static boolean isSpaceChar(final int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t' } public final int[] nextIntArray(final int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 11
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
2903f7b5ddbc155c275a45c4ba6a4425
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
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.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static boolean[] isPrime; static int[] smallestFactorOf; static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3; static int cmp; @SuppressWarnings({"unused"}) public static void main(String[] args) throws Exception { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); int[] arr = fr.nextIntArray(n); if (isSorted(arr)) { out.println(0); continue OUTER; } // when can we get done in one operation? // -- // when the last or the first element is // in its rightful position int[] sorted = arr.clone(); sort(sorted); if (arr[0] == sorted[0] || arr[n - 1] == sorted[n - 1]) { out.println(1); continue OUTER; } if (arr[0] == sorted[n - 1] && arr[n - 1] == sorted[0]) { out.println(3); continue OUTER; } out.println(2); } out.close(); } static boolean isPalindrome(char[] s) { char[] rev = s.clone(); reverse(rev); return Arrays.compare(s, rev) == 0; } static class Segment implements Comparable<Segment> { int size; long val; int stIdx; Segment left, right; Segment(int ss, long vv, int ssii) { size = ss; val = vv; stIdx = ssii; } @Override public int compareTo(Segment that) { cmp = size - that.size; if (cmp == 0) cmp = stIdx - that.stIdx; if (cmp == 0) cmp = Long.compare(val, that.val); return cmp; } } static class Pair implements Comparable<Pair> { int first, second; int idx; Pair() { first = second = 0; } Pair (int ff, int ss) {first = ff; second = ss;} Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; } public int compareTo(Pair that) { cmp = first - that.first; if (cmp == 0) cmp = second - that.second; return (int) cmp; } } // (range add - segment min) segTree static int nn; static int[] arr; static int[] tree; static int[] lazy; static void build(int node, int leftt, int rightt) { if (leftt == rightt) { tree[node] = arr[leftt]; return; } int mid = (leftt + rightt) >> 1; build(node << 1, leftt, mid); build(node << 1 | 1, mid + 1, rightt); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return; if (segL <= leftt && rightt <= segR) { tree[node] += val; if (leftt != rightt) { lazy[node << 1] += val; lazy[node << 1 | 1] += val; } lazy[node] = 0; return; } int mid = (leftt + rightt) >> 1; segAdd(node << 1, leftt, mid, segL, segR, val); segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static int minQuery(int node, int leftt, int rightt, int segL, int segR) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10; if (segL <= leftt && rightt <= segR) return tree[node]; int mid = (leftt + rightt) >> 1; return Math.min(minQuery(node << 1, leftt, mid, segL, segR), minQuery(node << 1 | 1, mid + 1, rightt, segL, segR)); } static void compute_automaton(String s, int[][] aut) { s += '#'; int n = s.length(); int[] pi = prefix_function(s.toCharArray()); for (int i = 0; i < n; i++) { for (int c = 0; c < 26; c++) { int j = i; while (j > 0 && 'A' + c != s.charAt(j)) j = pi[j-1]; if ('A' + c == s.charAt(j)) j++; aut[i][c] = j; } } } static void timeDFS(int current, int from, UGraph ug, int[] time, int[] tIn, int[] tOut) { tIn[current] = ++time[0]; for (int adj : ug.adj(current)) if (adj != from) timeDFS(adj, current, ug, time, tIn, tOut); tOut[current] = ++time[0]; } static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) { // we will check if c3 lies on line through (c1, c2) long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return a == 0; } static int[] treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n + 1]; diamDFS(farthest, -1, 0, ug, distTo); distTo[n] = farthest; return distTo; } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class TreeDistFinder { UGraph ug; int n; int[] depthOf; LCA lca; TreeDistFinder(UGraph ug) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(0, -1, ug, 0, depthOf); lca = new LCA(ug, 0); } TreeDistFinder(UGraph ug, int a) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(a, -1, ug, 0, depthOf); lca = new LCA(ug, a); } private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) { depthOf[current] = depth; for (int adj : ug.adj(current)) if (adj != from) depthCalc(adj, current, ug, depth + 1, depthOf); } public int dist(int a, int b) { int lc = lca.lca(a, b); return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]); } } public static long[][] GCDSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; } else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeGCDQ(long[][] table, int l, int r) { // [a,b) if(l > r)return 1; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return gcd(table[t][l], table[t][r-(1<<t)]); } static class Trie { TrieNode root; Trie(char[][] strings) { root = new TrieNode('A', false); construct(root, strings); } public Stack<String> set(TrieNode root) { Stack<String> set = new Stack<>(); StringBuilder sb = new StringBuilder(); for (TrieNode next : root.next) collect(sb, next, set); return set; } private void collect(StringBuilder sb, TrieNode node, Stack<String> set) { if (node == null) return; sb.append(node.character); if (node.isTerminal) set.add(sb.toString()); for (TrieNode next : node.next) collect(sb, next, set); if (sb.length() > 0) sb.setLength(sb.length() - 1); } private void construct(TrieNode root, char[][] strings) { // we have to construct the Trie for (char[] string : strings) { if (string.length == 0) continue; root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0); if (root.next[string[0] - 'a'] != null) root.isLeaf = false; } } private TrieNode put(TrieNode node, char[] string, int idx) { boolean isTerminal = (idx == string.length - 1); if (node == null) node = new TrieNode(string[idx], isTerminal); node.character = string[idx]; node.isTerminal |= isTerminal; if (!isTerminal) { node.isLeaf = false; node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1); } return node; } class TrieNode { char character; TrieNode[] next; boolean isTerminal, isLeaf; boolean canWin, canLose; TrieNode(char c, boolean isTerminallll) { character = c; isTerminal = isTerminallll; next = new TrieNode[26]; isLeaf = true; } } } static class Edge implements Comparable<Edge> { int from, to; long weight, ans; int id; // int hash; Edge(int fro, int t, long wt, int i) { from = fro; to = t; id = i; weight = wt; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] minSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMinQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } public static long[][] maxSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMaxQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MIN_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.max(table[t][l], table[t][r-(1<<t)]); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; Edge backEdge; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); backEdge = new Edge(from, current, 1, 0); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; levelDFS(0, -1, 0); // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private void levelDFS(int current, int from, int lvl) { levelOf[current] = lvl; for (int adj : tree.adj(current)) if (adj != from) levelDFS(adj, current, lvl + 1); } private int dpDFS(int current, int from) { dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(Comparator<T> cmp) { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefix_function(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefix_function(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i-1]; while (j > 0 && s[i] != s[j]) j = pi[j-1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");} static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static long mapTo1D(long row, long col, long n, long m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} } /* * * int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780 , 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650}; int n = arr.length; sort(arr); int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0; for (int i = 0; i < n; i++) if (arr[i] < 1700) bel1700++; else if (1700 <= arr[i] && arr[i] < 1900) bet1700n1900++; else if (arr[i] >= 1900) abv1900++; out.println("COUNT: " + n); out.println("PERFS: " + toString(arr)); out.println("MEDIAN: " + arr[n / 2]); out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble()); out.println("[0, 1700): " + bel1700 + "/" + n); out.println("[1700, 1900): " + bet1700n1900 + "/" + n); out.println("[1900, 2400): " + abv1900 + "/" + n); * * */ // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 17
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
96e548147bc34453b54ba2a59baf3747
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; //import java.util.*; public class PermutationSort { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()), sorted = 1; String[] str = br.readLine().split("\\s+"); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = Integer.parseInt(str[i]); if(arr[i]!=i+1) sorted = 0; } if(sorted==1) System.out.println(0); else if(arr[0]==1 || arr[n-1]==n) System.out.println(1); else if(arr[0]==n && arr[n-1]==1) System.out.println(3); else System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 17
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9da22c5b5b6ce74f9801b7b92bd74b0e
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public final class D { static int[][] dp; public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int[] arr = fs.nextIntArray(n); final List<Integer> one = new ArrayList<>(); final List<Integer> zero = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == 0) { zero.add(i); } else { one.add(i); } } dp = new int[one.size()][zero.size()]; for (int[] row : dp) { Arrays.fill(row, -1); } System.out.println(dfs(one, zero, 0, 0)); } private static int dfs(List<Integer> one, List<Integer> zero, int i, int j) { if (i == one.size()) { return 0; } if (j == zero.size()) { return (int) 1e9; } if (dp[i][j] != -1) { return dp[i][j]; } int res = (int) 1e9; res = Math.min(res, dfs(one, zero, i, j + 1)); res = Math.min(res, Math.abs(one.get(i) - zero.get(j)) + dfs(one, zero, i + 1, j + 1)); return dp[i][j] = res; } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a9e7074d915e36e10574f4cee76685b5
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public final class D { static int[][] dp; public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int[] arr = fs.nextIntArray(n); final List<Integer> one = new ArrayList<>(); final List<Integer> zero = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == 0) { zero.add(i); } else { one.add(i); } } dp = new int[one.size()][zero.size()]; for (int[] row : dp) { Arrays.fill(row, -1); } System.out.println(dfs(one, zero, 0, 0)); } private static int dfs(List<Integer> one, List<Integer> zero, int i, int j) { if (i == one.size()) { return 0; } if (j == zero.size()) { return (int) 1e9; } if (dp[i][j] != -1) { return dp[i][j]; } int res = (int) 1e9; res = Math.min(res, dfs(one, zero, i, j + 1)); res = Math.min(res, Math.abs(one.get(i) - zero.get(j)) + dfs(one, zero, i + 1, j + 1)); return dp[i][j] = res; } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
289417c973f00e9a4e62eaa3ee054478
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); ArrayList<Integer> occupied = new ArrayList<>(); ArrayList<Integer> vacant = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if (x == 1) occupied.add(i); else vacant.add(i); } Solution Solution = new Solution(occupied, vacant); // System.out.println(Solution.tabulation()); System.out.println(Solution.memoization()); } } class Solution { ArrayList<Integer> occupied, vacant; int x, y; public Solution(ArrayList<Integer> occupied, ArrayList<Integer> vacant) { this.occupied = occupied; this.vacant = vacant; x = occupied.size(); y = vacant.size(); } int tabulation() { return tabulation(x, y); } int tabulation(int x, int y) { int[][] dp = new int[x+1][y+1]; for (int i = 0; i <= x; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE/2); } for (int i = 0; i <= x; i++) { dp[i][0] = 0; } for (int i = 0; i <= y; i++) { dp[0][i] = 0; } for (int i = 1; i <= x; i++) { for (int j = 1; j <= y; j++) { if(i == j) { dp[i][j] = dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1)); } else { dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1))); } } } return dp[x][y]; } int memoization() { int[][] dp = new int[x][y]; for (int i = 0; i < x; i++) { Arrays.fill(dp[i], -1); } return memoization(dp, x-1, y-1); } int memoization(int[][] dp, int n, int m) { if(n < 0) { return 0; } if(m < n) { return Integer.MAX_VALUE; } if(dp[n][m] != -1) { return dp[n][m]; } int first = memoization(dp, n, m-1); int second = memoization(dp, n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m)); dp[n][m] = Math.min(first, second); return dp[n][m]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
465f394c527189dda7a7039ef23f8891
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); ArrayList<Integer> occupied = new ArrayList<>(); ArrayList<Integer> vacant = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if (x == 1) occupied.add(i); else vacant.add(i); } Solution Solution = new Solution(occupied, vacant); System.out.println(Solution.tabulation()); // System.out.println(Solution.memoization()); } } class Solution { ArrayList<Integer> occupied, vacant; int x, y; public Solution(ArrayList<Integer> occupied, ArrayList<Integer> vacant) { this.occupied = occupied; this.vacant = vacant; x = occupied.size(); y = vacant.size(); } int tabulation() { return tabulation(x, y); } int tabulation(int x, int y) { int[][] dp = new int[x+1][y+1]; for (int i = 0; i <= x; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE/2); } for (int i = 0; i <= x; i++) { dp[i][0] = 0; } for (int i = 0; i <= y; i++) { dp[0][i] = 0; } for (int i = 1; i <= x; i++) { for (int j = 1; j <= y; j++) { if(i == j) { dp[i][j] = dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1)); } else { dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1))); } } } return dp[x][y]; } int memoization() { int[][] dp = new int[x][y]; for (int i = 0; i < x; i++) { Arrays.fill(dp[i], -1); } return memoization(dp, x-1, y-1); } int memoization(int[][] dp, int n, int m) { if(n < 0) { return 0; } if(m < n) { return Integer.MAX_VALUE; } if(dp[n][m] != -1) { return dp[n][m]; } int first = memoization(dp, n, m-1); int second = memoization(dp, n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m)); dp[n][m] = Math.min(first, second); return dp[n][m]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
0b7370c4d3431f7cc0221ad229d575d1
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); ArrayList<Integer> occupied = new ArrayList<>(); ArrayList<Integer> vacant = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if (x == 1) occupied.add(i); else vacant.add(i); } Solution Solution = new Solution(occupied, vacant); System.out.println(Solution.tabulation()); // System.out.println(Solution.memoization()); } } class Solution { ArrayList<Integer> occupied, vacant; int x, y; int[][] tab; int[][] memo; public Solution(ArrayList<Integer> occupied, ArrayList<Integer> vacant) { this.occupied = occupied; this.vacant = vacant; x = occupied.size();y = vacant.size(); tab = new int[x+1][y+1]; for (int i = 0; i <= x; i++) { Arrays.fill(tab[i], Integer.MAX_VALUE/2); } for (int i = 0; i <= x; i++) { tab[i][0] = 0; } for (int i = 0; i <= y; i++) { tab[0][i] = 0; } memo = new int[x][y]; for (int i = 0; i < x; i++) { Arrays.fill(memo[i], -1); } } int tabulation() { return tabulation(x, y); } int tabulation(int x, int y) { for (int i = 1; i <= x; i++) { for (int j = 1; j <= y; j++) { if(i == j) { tab[i][j] = tab[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1)); } else { tab[i][j] = Math.min(tab[i][j-1], tab[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1))); } } } return tab[x][y]; } int memoization() { return memoization(x-1, y-1); } int memoization(int n, int m) { if(n < 0) { return 0; } if(m < n) { return Integer.MAX_VALUE; } if(memo[n][m] != -1) { return memo[n][m]; } int first = memoization(n, m-1); int second = memoization(n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m)); memo[n][m] = Math.min(first, second); return memo[n][m]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
dae8c6010788d63efa5bcf527eaae6fb
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); occupied = new ArrayList<>(); vacant = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if(x == 1) occupied.add(i); else vacant.add(i); } int x = occupied.size(); int y = vacant.size(); dp = new int[x][y]; for (int i = 0; i < x; i++) { Arrays.fill(dp[i], -1); } System.out.println(rec(x-1, y-1)); } static ArrayList<Integer> occupied; static ArrayList<Integer> vacant; static int[][] dp; static int rec(int n, int m) { if(n < 0) { return 0; } if(m < n) { return Integer.MAX_VALUE; } if(dp[n][m] != -1) { return dp[n][m]; } int first = rec(n, m-1); int second = rec(n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m)); dp[n][m] = Math.min(first, second); return dp[n][m]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
db622f50b91d13e886fa57abf3cf54c2
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class Solve{ static int[][] dp; static ArrayList<Integer> o; static ArrayList<Integer> z; public static void main(String[] args){ Scanner sc= new Scanner(System.in); int n=sc.nextInt(); dp=new int[n+1][n+1]; for(int i=0;i<=n;i++)Arrays.fill(dp[i],-1); o =new ArrayList<>(); z=new ArrayList<>(); for(int i=0;i<n;i++){ int a=sc.nextInt(); if(a==1)o.add(i); else z.add(i); } System.out.println(memo(0,0)); } static int memo(int i,int j){ if(i>=o.size())return 0; if(j>=z.size())return 10000000; if(dp[i][j]!=-1)return dp[i][j]; dp[i][j]=Math.min(Math.abs(o.get(i)-z.get(j))+memo(i+1,j+1),memo(i,j+1)); return dp[i][j]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
c8b42bfdd62675c647f3b804f6d9b7a4
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Solve { static int mod = 1000000000 + 7; static int INF = 1000_000_00; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int a[] = sc.nextIntArray(n); ArrayList<Integer> ones = new ArrayList<Integer>(); ArrayList<Integer> zeros = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (a[i] == 1) ones.add(i); if (a[i] == 0) zeros.add(i); } if (ones.size() == 0) { pw.println(0); pw.flush(); return; } if (ones.size() == 1) { pw.println(1); pw.flush(); return; } if (n == 2) { pw.println(1); pw.flush(); return; } int sz0 = zeros.size(); int sz1 = ones.size(); int dp[][] = new int[sz1 + 1][sz0 + 1]; for (int i = 0; i < sz1; i++) Arrays.fill(dp[i], INF); dp[0][0] = 0; Arrays.fill(dp[0], 0); for (int i = 1; i <= sz1; i++) { for (int j = 1; j <= sz0; j++) { if (i > j) { dp[i][j] = INF; continue; } int oneIndex = ones.get(i - 1); int zeroIndex = zeros.get(j - 1); int cost = Math.abs(oneIndex - zeroIndex); dp[i][j] = Math.min(dp[i][j - 1], cost + dp[i - 1][j - 1]); } } pw.println(dp[sz1][sz0]); // dp[i][j] = minimum distance we can have using first 1 ones and first j zeros pw.flush(); } public static int primeFactors(int n) { int count = 0; // Print the number of 2s that divide n while (n % 2 == 0) { n /= 2; } if (n == 1) return 0; // 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) { n /= i; count++; } } if (n > 1) count++; return count; } static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; return gcd(b, a % b); } 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; } static long nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int C[] = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } 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); } } class Pair implements Comparable<Pair> { int tower; int value = 0; Pair(int x, int y) { tower = x; value = y; } public int compareTo(Pair o) { return this.value - o.value; } } class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } int[] nextIntArray(int n) throws NumberFormatException, IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } long[] nextLongArray(int n) throws NumberFormatException, IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
d74a5106699c21571f2eebc57e45c211
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class A { static long modInverse(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { long q = a / m; long t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } static void pla() { int a = 0; int b = 2; int c = 0; int d = 0; a = (int) Math.pow(2, 32); c = a + b; b = c / a; d = a + b + c; } static int mod = (int) 1e9 + 7; static Scanner sc = new Scanner(System.in); static StringBuilder out = new StringBuilder(); public static void main(String[] args) throws IOException { int t = 1;// sc.nextInt(); while (t-- > 0) { A run = new A(); run.run(); } System.out.println(out); } public static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } public void run() throws IOException { // int k = sc.nextInt(); // if(100%k==0)out.append((100/k)+"\n"); // // else { // out.append(100+"\n"); // } // int ans=(int)1e9; // for(int i=1;i<=k;i++) { // // // if(i*100%k==0) { // // ans=Math.min(ans,i*) // // // } // // } // // int ans = 100 - k; // if (k == 100) // out.append(1); // else { // int g = gcd(k, ans); // out.append((k / g) + (ans / g)); // } // out.append("\n"); // // int n = sc.nextInt(); // int a[] = new int[n]; // // for(int i=0;i<n;i++)a[i]=sc.nextInt(); // int min = Integer.MAX_VALUE, mx = Integer.MIN_VALUE; // for (int i = 0; i < n; i++) { // min = Math.min(min, a[i]); // mx = Math.max(mx, a[i]); // } // int b[] = a.clone(); // sort(b,n); // if (Arrays.equals(a, b)) { // out.append(0); // } else if (a[0] == min || a[n - 1] == mx) { // out.append(1); // } else if (a[0] == mx && a[n - 1] == min) { // out.append(3); // } else { // out.append(2); // } // out.append("\n"); int n = sc.nextInt(); int a[] = new int[n]; TreeSet<Integer> ts = new TreeSet<>(); ArrayList<Integer> a1 = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (a[i] == 1) a1.add(i); else b.add(i); } int dp[] = new int[n]; int sum = 0; memo = new int[n][n]; for (int tem[] : memo) Arrays.fill(tem, -1); sum = solve(0, 0, a1, b); out.append(sum + "\n"); } static int memo[][]; static int solve(int i, int j, ArrayList<Integer> a, ArrayList<Integer> b) { if(i==a.size())return 0; if(a.size()-i>b.size()-j)return (int)1e9; if(j==b.size())return (int)1e9; if(memo[i][j]!=-1)return memo[i][j]; int ans = (int) 1e9; ans = Math.min(solve(i + 1, j+1 , a, b) + Math.abs(a.get(i) - b.get(j)),solve(i,j+1,a,b)); return memo[i][j]=ans; } static boolean check(int[] dp, int cnt) { int count = 0; for (int i = 0; i < dp.length; i++) { if (dp[i] == 1) count++; } return (count == cnt); } static void sort(int a[], int n) { ArrayList<Integer> al = new ArrayList<>(); for (int i = 0; i < n; i++) { al.add(a[i]); } Collections.sort(al); for (int i = 0; i < n; i++) { a[i] = al.get(i); } } static void sort(long a[], int n) { ArrayList<Long> al = new ArrayList<>(); for (int i = 0; i < n; i++) { al.add(a[i]); } Collections.sort(al); for (int i = 0; i < n; i++) { a[i] = al.get(i); } } // static Reader sc = new Reader(); 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(); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5e752ce281f015d7eae3a0c0b61c72fb
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { 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; } } static class TreeMultiSet<T> implements Iterable<T> { private final TreeMap<T,Integer> map; private int size; public TreeMultiSet(){map=new TreeMap<>(); size=0;} public TreeMultiSet(boolean reverse) { if(reverse) map=new TreeMap<>(Collections.reverseOrder()); else map=new TreeMap<>(); size=0; } public void clear(){map.clear(); size=0;} public int size(){return size;} public int setSize(){return map.size();} public boolean contains(T a){return map.containsKey(a);} public boolean isEmpty(){return size==0;} public Integer get(T a){return map.getOrDefault(a,0);} public void add(T a, int count) { int cur=get(a);map.put(a,cur+count); size+=count; if(cur+count==0) map.remove(a); } public void addOne(T a){add(a,1);} public void remove(T a, int count){add(a,Math.max(-get(a),-count));} public void removeOne(T a){remove(a,1);} public void removeAll(T a){remove(a,Integer.MAX_VALUE-10);} public T ceiling(T a){return map.ceilingKey(a);} public T floor(T a){return map.floorKey(a);} public T first(){return map.firstKey();} public T last(){return map.lastKey();} public T higher(T a){return map.higherKey(a);} public T lower(T a){return map.lowerKey(a);} public T pollFirst(){T a=first(); removeOne(a); return a;} public T pollLast(){T a=last(); removeOne(a); return a;} public Iterator<T> iterator() { return new Iterator<>() { private final Iterator<T> iter = map.keySet().iterator(); private int count = 0; private T curElement; public boolean hasNext(){return iter.hasNext()||count>0;} public T next() { if(count==0) { curElement=iter.next(); count=get(curElement); } count--; return curElement; } }; } } static long abs(long x){ if(x<0) x*=-1; return x; } public static void main(String[] args) { MyScanner sc = new MyScanner(); int t = 1; while (t-- != 0) { int n = sc.nextInt(); int a[] = new int [n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); long dp[][] = new long[n][n]; int prev = -1; for(int i =0;i<n;i++){ if(a[i] == 0) continue; long prevSum = Long.MAX_VALUE; for(int j=0;j<n;j++){ if(a[j] == 0){ dp[i][j] = abs(i - j); if(prev != -1){ // not the first 1 if(prevSum != Long.MAX_VALUE)dp[i][j] += prevSum; else dp[i][j] = prevSum; prevSum = Math.min(prevSum, dp[prev][j]); } } } prev = i; } long ans = Long.MAX_VALUE; if(prev != -1) for(int i =0;i<n;i++){ if(a[i] == 0) ans = Math.min(ans,dp[prev][i]); } else ans = 0; System.out.println(ans); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
6f4406cac237ca2d0aaad67586592e66
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* JAI MATA DI */ import java.util.*; import javax.print.attribute.HashAttributeSet; import java.io.*; import java.math.BigInteger; import java.sql.Array; public class CP { 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 int mod = 1000000007; 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 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 class Pair implements Comparable<Pair>{ int ind; int val; Pair(int key , int value){ this.ind = key; this.val = value; } @Override public int compareTo(Pair o) { return this.val - o.val; } // @Override // public int hashCode(){ // return first + second; // } } /* ***************************************************************************************************************************************************/ static FR sc = new FR(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) { // int 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]; for(int i = 0 ; i< n ;i++) { arr[i] = sc.nextInt(); } ArrayList<Integer> ao = new ArrayList<Integer>(); ArrayList<Integer> az = new ArrayList<Integer>(); for(int i = 0 ; i< n ;i++) { if(arr[i] == 1) ao.add(i); else az.add(i); } long[][] dp = new long[n+1][n+1]; for(int i = 0 ; i<n ; i++) Arrays.fill(dp[i], -1); sb.append(fnc(dp, ao, az, 0, 0)); } static long fnc(long[][] dp ,ArrayList<Integer> ao , ArrayList<Integer> az ,int i , int j) { if(i == ao.size()) return 0; if(j == az.size()) return Long.parseLong("1000000000000"); if(dp[i][j] != -1) return dp[i][j]; long a = Math.abs(ao.get(i) - az.get(j)) + fnc(dp, ao, az, i+1, j+1); long b = fnc(dp, ao, az, i, j+1); dp[i][j] = Math.min(a, b); return dp[i][j]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
dc6d237fc23bdc7f3b328cc4c9f3c095
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { // InputReader sc = new InputReader(System.in); // PrintWriter out = new PrintWriter(System.out); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); FastReader reader = new FastReader(); BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); int test = 1; for (int o = 0; o < test; o++) { int n = reader.nextInt(); int[] arr = new int[n]; ArrayList<Integer> l1 = new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(); l1.add(0); l2.add(0); for (int i = 0; i < n; i++){ arr[i] = reader.nextInt(); if (arr[i] == 1){ l1.add(i + 1); } else { l2.add(i + 1); } } // System.out.println(l1); // System.out.println(l2); int[][] dp = new int[l1.size()][l2.size()]; for (int i = 0; i < dp.length; i++){Arrays.fill(dp[i],Integer.MAX_VALUE);} for (int i = 0; i < dp[0].length; i++){ dp[0][i ] = 0; } for (int i = 1; i < dp.length; i++){ for (int j = i; j < dp[0].length; j++){ dp[i][j] = Math.min(dp[i ][j - 1], dp[i - 1][j - 1] + Math.abs(l2.get(j) - l1.get(i ))); } } // for (int[] array: dp){ // System.out.println(Arrays.toString(array)); // } System.out.println(dp[dp.length - 1][dp[0].length - 1]); } } } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
88428d3da85c0f6b6176a7e5f86c9203
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.*; public class codeforces { static int dp[][]=new int[5001][5001]; public static void main(String[] args) { Scanner s=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; for(int tt=0;tt<t;tt++) { int n=s.nextInt(); int a[]=new int[n]; ArrayList<Integer> z=new ArrayList<>(); ArrayList<Integer> o=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=s.nextInt(); if(a[i]==1) { o.add(i); }else { z.add(i); } } for(int i=0;i<5001;i++) { Arrays.fill(dp[i], -1); } System.out.println(sol(0,0,z,o)); } out.close(); s.close(); } 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 sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if (x[c] != y[c]) return(int)( x[c] - y[c]); return (int)-(x[1]+x[2] - y[1]-y[2]); }); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int sol(int i,int j,ArrayList<Integer> z,ArrayList<Integer> o) { if(j==o.size()) { return 0; } int h=z.size()-i; int l=o.size()-j; if(i==z.size()) { return 10000000; } if(dp[i][j]!=-1) { //System.out.println(i+" "+j); return dp[i][j]; } int ans1=sol(i+1,j,z,o); int ans2=sol(i+1,j+1,z,o)+Math.abs(z.get(i)-o.get(j)); dp[i][j]=Math.min(ans1, ans2); return dp[i][j]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
1850b7595928e34cfa33d4af767588b7
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.*; public class codeforces { static int dp[][]=new int[5001][5001]; public static void main(String[] args) { Scanner s=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; for(int tt=0;tt<t;tt++) { int n=s.nextInt(); int a[]=new int[n]; ArrayList<Integer> z=new ArrayList<>(); ArrayList<Integer> o=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=s.nextInt(); if(a[i]==1) { o.add(i); }else { z.add(i); } } for(int i=0;i<5001;i++) { Arrays.fill(dp[i], -1); } System.out.println(sol(0,0,z,o)); } out.close(); s.close(); } 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 sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if (x[c] != y[c]) return(int)( x[c] - y[c]); return (int)-(x[1]+x[2] - y[1]-y[2]); }); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int sol(int i,int j,ArrayList<Integer> z,ArrayList<Integer> o) { if(j==o.size()) { return 0; } int h=z.size()-i; int l=o.size()-j; if(h<l) { return 10000000; } if(dp[i][j]!=-1) { return dp[i][j]; } int ans1=sol(i+1,j,z,o); int ans2=sol(i+1,j+1,z,o)+Math.abs(z.get(i)-o.get(j)); dp[i][j]=Math.min(ans1, ans2); return dp[i][j]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
523829bd8f7cd123bbbf6880680d2878
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.*; public class codeforces { public static void main(String[] args) { Scanner s=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; for(int tt=0;tt<t;tt++) { int n=s.nextInt(); int a[]=new int[n+1]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } a[n]=1; int dp[][]=new int[n+2][n+2]; for(int i=1;i<n+2;i++) { for(int j=0;j<=n+1;j++) dp[i][j]=10000000; } for(int i=1;i<=n;i++) { if(a[i-1]==0) { for(int j=0;j<=n;j++) { dp[i][j]=dp[i-1][j]; } }else { for(int j=0;j<n+1;j++) { if(a[j]==0) dp[i][j+1]=Math.min(dp[i][j+1], dp[i-1][j]+(Math.abs(i-j-1))); } } for(int j=1;j<=n;j++) { dp[i][j]=Math.min(dp[i][j], dp[i][j-1]); } } System.out.println(dp[n][n]); } out.close(); s.close(); } 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 sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if (x[c] != y[c]) return(int)( x[c] - y[c]); return (int)-(x[1]+x[2] - y[1]-y[2]); }); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5fea88362a7b75179e470bf8e4cb3cf6
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.*; public class codeforces { public static void main(String[] args) { Scanner s=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; for(int tt=0;tt<t;tt++) { int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int dp[][]=new int[5050][10100]; for(int i=0;i<5050;i++) { for(int j=0;j<10100;j++) { dp[i][j]=10000000; } } dp[0][5050]=0; for(int i=1;i<=n;i++){ if(a[i-1] == 0){ for(int j = -i+5050;j<5050;j++){ dp[i][j] = Math.min(dp[i-1][j],dp[i-1][j+1]-i); } for(int j = 5050;j<=i+5050;j++){ dp[i][j] =Math. min(dp[i-1][j],dp[i-1][j+1]+i); } }else{ for(int j = -i+5050;j<=5050;j++){ dp[i][j] = dp[i-1][j-1]+i; } for(int j = 5051;j<=i+5050;j++){ dp[i][j] = dp[i-1][j-1]-i; } } } System.out.println(dp[n][5050]); } out.close(); s.close(); } 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 sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if (x[c] != y[c]) return(int)( x[c] - y[c]); return (int)-(x[1]+x[2] - y[1]-y[2]); }); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a0c9dcf8516b62bbc2f4224377f52e5f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public final class Solution{ static FastReader sc=new FastReader(); static PrintWriter writer=new PrintWriter(System.out); static ArrayList<Integer>[] g; static int[] vis, dis, parent; public static int[][] dp; public static int solve(ArrayList<Integer> ones, ArrayList<Integer> zeros, int i, int j) { int n = ones.size(), m=zeros.size(); if(i==n) return 0; if(i==n || j==m) return Integer.MAX_VALUE; if(dp[i][j]!=-1) return dp[i][j]; int cost = Math.abs(zeros.get(j)-ones.get(i)); int temp = solve(ones, zeros, i+1, j+1); if(temp == Integer.MAX_VALUE) cost =0; int ans = Math.min( temp + cost, solve(ones, zeros, i, j+1)); return dp[i][j] = ans; } public static void main(String[] args){ int tc=1; for(int z=1;z<=tc;z++) { int n = sc.nextInt(); int[] a=new int[n]; ArrayList<Integer> ones = new ArrayList<>(), zeros = new ArrayList<>(); dp=new int[n][n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]==0) zeros.add(i); else ones.add(i); Arrays.fill(dp[i], -1); } int ans = solve(ones, zeros, 0, 0); System.out.println(ans); } writer.flush(); writer.close(); } static class Group{ int f, s, t; Group(int f, int s, int t) { this.f=f; this.s=s; this.t=t; } Group(int f, int s){ this.f=f; this.s=s; } } static class TreeNode{ int data; TreeNode left, right; TreeNode(int data) { this.data=data; } } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
0d037ef355d442b8085faa65afe694ff
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastReader() { 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 FastReader f = new FastReader(); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb = new StringBuilder(""); private static int m = (int) 1e9 + 7; static int MAX = 500005; static long[] fact; static int[] inputArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = f.nextInt(); } return a; } private static class SegmentTree { int[] array; int[] tree; int n; int max; SegmentTree(int a[], int n) { this.tree = new int[4 * n + 1]; this.array = a; this.n = n; buildTree(); } void buildTree() { buildTreeHelper(0, 0, n - 1); } void buildTreeHelper(int i, int start, int end) { if (start > end) { return; } if (start == end) { tree[i] = array[start]; return; } int mid = (start + end) / 2; buildTreeHelper(2 * i + 1, start, mid); buildTreeHelper(2 * i + 2, mid + 1, end); tree[i] = Math.max(tree[2 * i + 1], tree[2 * i + 2]); } char overlap(int start, int end, int qs, int qe) { if (qe < start || qs > end || start > end) { return 0; } if (qs <= start && qe >= end) { return 2; } return 1; } int query(int start, int end) { return andQueryHelper(0, 0, n - 1, start, end); } int andQueryHelper(int i, int start, int end, int qs, int qe) { if (overlap(start, end, qs, qe) == 0) { return 0; } if (overlap(start, end, qs, qe) == 1) { int mid = (start + end) / 2; return Math.max(andQueryHelper(2 * i + 1, start, mid, qs, qe), andQueryHelper(2 * i + 2, mid + 1, end, qs, qe)); } else { return tree[i]; } } } static int query(int l, int r) { System.out.println("? " + l + " " + r); System.out.flush(); int res = f.nextInt(); System.out.flush(); return res; } static long gcd(long a , long b) { if(a == 0 || b == 0) { return Math.max(a , b); } //System.out.println("a - " + a + " b - " + b); if(a % b == 0) { return b; } return gcd(b , a % b); } public static void main(String[] args) throws IOException { // System.out.println(gcd(11, 3)); int t = 1; while(t-- != 0) { int N = f.nextInt(); int a[] = inputArray(N); ArrayList<Integer> space = new ArrayList<>(); ArrayList<Integer> fill = new ArrayList<>(); for(int i = 0 ; i < N; i++) { if(a[i] == 0) { space.add(i); } else { fill.add(i); } } int n = fill.size(), m = space.size(); int[][] dp = new int[n+1][m+1]; // i - no of filled // j is no of space Arrays.fill(dp[0], 0); for(int i = 1 ; i <= n ; i++) { dp[i][0] = -1; } for(int i = 1 ; i <= n ; i++) { for(int j = 1 ; j <= m ; j++) { if(i > j) { dp[i][j] = -1; continue; } dp[i][j] = Integer.MAX_VALUE; if(dp[i-1][j-1] != -1) { dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1]) + Math.abs(fill.get(i-1) - space.get(j-1)); } if(dp[i][j-1] != -1) { dp[i][j] = Math.min(dp[i][j], dp[i][j-1]); } } } System.out.println(dp[n][m]); } System.out.println(sb); } } /* 5 2 1 1 1 500 4 217871987498122 10 100000000000000001 1 */
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3b91e32b71eac5ff732fb27246adf101
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// 17-05 // import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { static HashSet<Integer> set; static int n; static char s[]; static int dp[][]; static List<Integer> list = new ArrayList<>(); static List<Integer> ini = new ArrayList<>(); static boolean vis[]; public static void main(String[] args) { Scanner sc = new Scanner(); int t = 1; PrintWriter out = new PrintWriter(System.out); while (t-- > 0) { int n = sc.nextInt(); int a[] = sc.readArray(n); list = new ArrayList<>(); ini = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] == 0) { list.add(i); } else { ini.add(i); } } dp = new int[ini.size()][list.size()]; for (int d[] : dp) { Arrays.fill(d, -1); } int res = f(0, 0); System.out.println(res); } out.flush(); out.close(); } static int f(int i, int j) { if (i == ini.size()) { return 0; } if (j == list.size()) { return inf; } if (dp[i][j] != -1) { return dp[i][j]; } int take = f(i + 1, j + 1); if (take != inf) { take += Math.abs(ini.get(i) - list.get(j)); } int not = f(i, j + 1); return dp[i][j] = Math.min(not, take); } static class Scanner { 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()); } double nextDouble() { return Double.parseDouble(next()); } String str = ""; String nextLine() { try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static void sort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static final int M = 1_000_000_007; static final int inf = Integer.MAX_VALUE; static final int ninf = inf + 1; }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5702c324862459a8da6c8ed5403bf57f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// * * * its fun to do the impossible * * * // import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class upD { static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a , int b){ this.a = a; this.b = b; } public int compareTo(Pair o){ return this.a - o.a; } } static long solve(long dp[][] , ArrayList<Integer> one , ArrayList<Integer> zeroes , int i , int j){ if(i == one.size()){ return 0; } if(j == zeroes.size()){ return Integer.MAX_VALUE; } if(dp[i][j] != -1){ return dp[i][j]; } return dp[i][j] = Math.min(solve(dp , one , zeroes , i + 1 , j + 1) + Math.abs(one.get(i) - zeroes.get(j)) , solve(dp , one , zeroes , i , j + 1)); } public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); ArrayList<Integer> one = new ArrayList<>(); ArrayList<Integer> zeroes = new ArrayList<>(); int a[] = new int[n]; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); if(a[i] == 1){ one.add(i+1); } else{ zeroes.add(i+1); } } long dp[][] = new long[one.size()][zeroes.size()]; for(int i=0;i<one.size();i++){ for(int j=0;j<zeroes.size();j++){ dp[i][j] = -1; } } System.out.println(solve(dp , one , zeroes , 0 , 0)); } // Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2 // worst case since it uses a version of quicksort. Although this would never // actually show up in the real world, in codeforces, people can hack, so // this is needed. static void ruffleSort(int[] a) { //ruffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner 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()); } double nextDouble() { return Double.parseDouble(next()); } String str = ""; String nextLine() { try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } // use this to find the index of any element in the array +1 /// // returns an array that corresponds to the index of the i+1th in the array a[] // runs only for array containing different values enclosed btw 0 to n-1 static int[] indexOf(int[] a) { int[] toRet=new int[a.length]; for (int i=0; i<a.length; i++) { toRet[a[i]]=i+1; } return toRet; } static int gcd(int a, int b) { if (b==0) return a; return gcd(b, a%b); } //generates all the prime numbers upto n static void sieveOfEratosthenes(int n , ArrayList<Integer> al) { 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] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) al.get(i); } } static final int mod=100000000 + 7; static final int max_val = 2147483647; static final int min_val = max_val + 1; //fastPow static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } //multiply two long numbers static long mul(long a, long b) { return a*b%mod; } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // to generate the lps array // lps means longest preffix that is also a suffix static void generateLPS(int lps[] , String p){ int l = 0; int r = 1; while(l < p.length() && l < r && r < p.length()){ if(p.charAt(l) == p.charAt(r)){ lps[r] = l + 1; l++; r++; } else{ if(l > 0) l = lps[l - 1]; else r++; } } } //count sort --> it runs in O(n) time but compromises in space static ArrayList<Integer> countSort(int a[]){ int max = Integer.MIN_VALUE; for(int i=0;i<a.length;i++){ max = Math.max(max , a[i]); } int posfre[] = new int[max+1]; boolean negPres = false; for(int i=0;i<a.length;i++){ if(a[i]>=0){ posfre[a[i]]++; } else{ negPres = true; } } ArrayList<Integer> res = new ArrayList<>(); if(negPres){ int min = Integer.MAX_VALUE; for(int i=0;i<a.length;i++){ min = Math.min(min , a[i]); } int negfre[] = new int[-1*min+1]; for(int i=0;i<a.length;i++){ if(a[i]<0){ negfre[-1*a[i]]++; } } for(int i=min;i<0;i++){ for(int j=0;j<negfre[-1*i];j++){ res.add(i); } } for(int i=0;i<=max;i++){ for(int j=0;j<posfre[i];j++){ res.add(i); } } return res; } for(int i=0;i<=max;i++){ for(int j=0;j<posfre[i];j++){ res.add(i); } } return res; } // returns the index of the element which is just smaller than or // equal to the tar in the given arraylist static int lowBound(ArrayList<Integer> ll , long tar , int l , int r){ if(l > r) return l; int mid = l + (r - l) / 2; if(ll.get(mid) >= tar){ return lowBound(ll , tar , l , mid - 1); } return lowBound(ll , tar , mid + 1 , r); } // returns the index of the element which is just greater than or // equal to the tar in the given arraylist static int upBound(ArrayList<Integer> ll , long tar , int l , int r){ if(l > r) return l; int mid = l + (r - l) / 2; if(ll.get(mid) <= tar){ return upBound(ll , tar , l , mid - 1); } return upBound(ll , tar , mid + 1 , r); } // a -> z == 97 -> 122 // String.format("%.9f", ans) ,--> to get upto 9 decimal places , (ans is double) // write }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
80e09c8fe4f95c5949840cbd982f8a54
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// ----------------------------------- Duniya Madarchod Hai ----------------------------------- import java.io.*; import java.math.*; import java.util.*; public class Main { /* public String wrd() throws IOException{return(read.next());} public int ni() throws IOException{return(read.nextInt());} public double nd() throws IOException{return(read.nextDouble());} public long nl() throws IOException{return(read.nextLong());} public int[] ai(int n) throws IOException{int arr[] = new int[n];for(int i = 0; i<n; i++)arr[i] = read.nextInt();return(arr);} public double[] ad(int n) throws IOException {double arr[] = new double[n];for(int i = 0; i<n; i++)arr[i] = read.nextDouble();return(arr);} public long[] al(int n) throws IOException {long arr[] = new long[n];for(int i = 0; i<n; i++)arr[i] = read.nextLong();return(arr);} class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); if (System.getProperty("ONLINE_JUDGE") == null) { try { InputStream inputStream = new FileInputStream("input.txt"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); br = new BufferedReader(inputStreamReader); } catch (Exception 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;}} */ 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); if (System.getProperty("ONLINE_JUDGE") == null) { try { din = new DataInputStream(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { e.printStackTrace(); } } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public String readLine() throws IOException{return(read.readLine());} public int ni() throws IOException{return(read.nextInt());} public double nd() throws IOException{return(read.nextDouble());} public long nl() throws IOException{return(read.nextLong());} public static void main(String[] args) throws IOException{Main obj = new Main();obj.solve();} long gcd(long a, long b) { while (b != 0) { long t = a; a = b; b = t % b; } return a; } long getSum(long arr[], int start, int end) { if(start == 0) return arr[end]; return(arr[end] - arr[start-1]); } //long MODULO = 1000*1000l*1000l + 7l; StringBuilder sb; Reader read; //FastReader read; int count = 0; int dp[][]; public void solve() throws IOException { //Scanner sn = new Scanner(System.in); sb = new StringBuilder(); //read = new FastReader(); read = new Reader(); int tt = 1; //for(int tk = 0; tk < tt; tk++) //{ int n = ni(); ArrayList<Integer> empty = new ArrayList<>(n); ArrayList<Integer> full = new ArrayList<>((n/2)); for(int i = 0; i<n; i++) { if(ni() == 1) full.add(i); else empty.add(i); } if(full.size() == 0) { System.out.println(0); return; } dp = new int[full.size()][empty.size()]; //for(int aa[] : dp) // Arrays.fill(aa, -1); //sb.append(find(full, 0, empty, 0)); //} System.out.println(find(full, 0, empty, 0)); } int find(ArrayList<Integer> full, int idx1 , ArrayList<Integer> empty, int idx2) { if(idx1 == full.size()) return 0; if(idx2 == empty.size()) return 250000009; if((empty.size() - idx2) < (full.size() - idx1)) return 250000009; if(dp[idx1][idx2] != 0) return (dp[idx1][idx2]); int min = 250000009; int op1 = find(full, idx1, empty, idx2+1); int op2 = (int) Math.abs(full.get(idx1) - empty.get(idx2)) + find(full, idx1+1, empty, idx2+1); dp[idx1][idx2] = Math.min(op1, op2); return(dp[idx1][idx2]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
d9aac65d9ea90ff985ae156e6cb1f74d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.rmi.dgc.Lease; // Problem - Multiples of 3 onn codeforces MNedium difficulty level // or check on youtube channel CodeNCode public class Problem { // static int Mod = 1000000007; static int Mod=998244353; static long dp[][]; static int g[][]; static int vis[][]; static int ans; public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // int t = scan.nextInt(); int t = 1; while (t-- > 0) { int n= scan.nextInt(); int a[]= new int[n]; int ones=0; for(int i=0;i<n;i++){ a[i]= scan.nextInt(); if(a[i]==1) ones++; } int one[]= new int[ones]; int zero[]= new int[n-ones]; int p=0; int q=0; for(int i=0;i<n;i++){ if(a[i]==1) one[p++]=i; else zero[q++]=i; } dp= new long[ones][n-ones]; for(long d[]:dp) Arrays.fill(d,-1l); out.println(solve(one,zero,0,0)); } out.close(); } static long solve(int one[], int zero[], int i, int j){ if(i==one.length) return 0; if(j==zero.length && i<one.length) return Integer.MAX_VALUE; if(dp[i][j]!=-1) return dp[i][j]; return dp[i][j]= Math.min((long)Math.abs(zero[j]-one[i])+ solve(one,zero,i+1,j+1) , solve(one,zero,i,j+1) ); } static ArrayList<Integer> digits(long n){ ArrayList<Integer> list= new ArrayList<>(); while(n>0){ list.add((int)(n%10l)); n=n/10l; } Collections.reverse(list); return list; } int upper_bound(long[] arr, int key) { int i=0, j=arr.length-1; if (arr[j]<=key) return j+1; if(arr[i]>key) return i; while (i<j){ int mid= (i+j)/2; if(arr[mid]<=key){ i= mid+1; }else{ j=mid; } } return i; } static class Pair { int l; int r; Pair(int l, int r) { this.l = l; this.r = r; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + l; result = prime * result + r; return result; } @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; if (l != other.l) return false; if (r != other.r) return false; return true; } @Override public String toString() { return "Pair [l=" + l + ", r=" + r + "]"; } } public static void reverse(int a[]) { int n = a.length; for (int i = 0; i < n / 2; i++) { int temp = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = temp; } } public static void sort(int[] array) { ArrayList<Integer> copy = new ArrayList<>(); for (Integer i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (Long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long power(long x, long y) { long temp; if (y == 0) // a^b= (a^b/2)^2 if b is even return 1; // = (a*a^(b-1)) if b is odd temp = power(x, y / 2); if (y % 2 == 0) return temp * temp; else return x * temp * temp; } static long mod(long x) { return ((x % Mod + Mod) % Mod); } static long add(long a, long b) { return mod(mod(a) + mod(b)); } static int mod(int x) { return ((x % Mod + Mod) % Mod); } static int add(int a, int b) { return mod(mod(a) + mod(b)); } static int sub(int a, int b) { return mod(mod(a) - mod(b) + Mod); } static long mul(long a, long b) { return mod(mod(a) * mod(b)); } static long pow(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; } static long modInverse(long a, long m) { // int g = gcd(a, m); // if (g != 1) // System.out.println("Inverse doesn't exist"); // else { // // If a and m are relatively prime, then modulo // // inverse is a^(m-2) mode m // return power(a, m - 2, m); // } return pow(a, m - 2, m); } } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
029ff1881f2f750c9b0f4aee25f83152
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Problem { static int Mod = 1000000007; public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); //int t = scan.nextInt(); int t=1; while (t-- > 0) { int p=scan.nextInt(); int a[]=new int[p]; ArrayList<Integer> zero = new ArrayList<>(); ArrayList<Integer> one = new ArrayList<>(); for(int i=0;i<p;i++){ a[i]=scan.nextInt(); if(a[i]==0) zero.add(i); else one.add(i); } int n=one.size(); int m=zero.size(); long dp[][]=new long[n+1][m+1]; for(long i[] : dp){ Arrays.fill(i,-1); } out.println(solve(n,m,one,zero,dp)); // out.println(Integer.MIN_VALUE); } out.close(); } static long solve(int n, int m, ArrayList<Integer> one, ArrayList<Integer> zero,long dp[][]){ if(n==0) return dp[n][m]=0l; if(m==0) return dp[n][m]= Integer.MAX_VALUE; if(dp[n][m]!=-1) return dp[n][m]; return dp[n][m]= Math.min( solve(n-1,m-1,one,zero,dp) +Math.abs(one.get(n-1)-zero.get(m-1)) , solve(n,m-1,one,zero,dp) ); } static class Pair { long l; long r; Pair(long l, long r) { this.l = l; this.r = r; } @Override public String toString() { return "Pair [l=" + l + ", r=" + r + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (l ^ (l >>> 32)); result = prime * result + (int) (r ^ (r >>> 32)); return result; } @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; if (l != other.l) return false; if (r != other.r) return false; return true; } } public static void sort(int[] array) { ArrayList<Integer> copy = new ArrayList<>(); for (Integer i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (Long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(double[] array) { ArrayList<Double> copy = new ArrayList<>(); for (Double i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static long gcd(long a,long b) { if (b == 0) return a; return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long power(long x, long y) { long temp; if (y == 0) // a^b= (a^b/2)^2 if b is even return 1; // = (a*a^(b-1)) if b is odd temp = power(x, y / 2); if (y % 2 == 0) return temp * temp; else return x * temp * temp; } static long mod(long x) { return ((x % Mod + Mod) % Mod); } static long add(long a, long b) { return mod(mod(a) + mod(b)); } static long mul(long a, long b) { return mod(mod(a) * mod(b)); } static long pow(long x, long y, int 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; } } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
1aa679880eb8922ef5ccd649370d344f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Problem { static int Mod = 1000000007; public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); //int t = scan.nextInt(); int t=1; while (t-- > 0) { int p=scan.nextInt(); int a[]=new int[p]; ArrayList<Integer> zero = new ArrayList<>(); ArrayList<Integer> one = new ArrayList<>(); for(int i=0;i<p;i++){ a[i]=scan.nextInt(); if(a[i]==0) zero.add(i); else one.add(i); } int n=one.size(); int m=zero.size(); long dp[][]=new long[n+1][m+1]; for(long i[] : dp){ Arrays.fill(i,-1); } out.println(solve(n,m,one,zero,dp)); // out.println(Integer.MIN_VALUE); } out.close(); } static long solve(int n, int m, ArrayList<Integer> one, ArrayList<Integer> zero,long dp[][]){ if(n==0) return dp[n][m]=0l; if(m==0) return dp[n][m]= Integer.MAX_VALUE; if(dp[n][m]!=-1) return dp[n][m]; return dp[n][m]= Math.min( solve(n-1,m-1,one,zero,dp) + (long)Math.abs(one.get(n-1)-zero.get(m-1)) , solve(n,m-1,one,zero,dp) ); } static class Pair { long l; long r; Pair(long l, long r) { this.l = l; this.r = r; } @Override public String toString() { return "Pair [l=" + l + ", r=" + r + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (l ^ (l >>> 32)); result = prime * result + (int) (r ^ (r >>> 32)); return result; } @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; if (l != other.l) return false; if (r != other.r) return false; return true; } } public static void sort(int[] array) { ArrayList<Integer> copy = new ArrayList<>(); for (Integer i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (Long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static void sort(double[] array) { ArrayList<Double> copy = new ArrayList<>(); for (Double i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } public static long gcd(long a,long b) { if (b == 0) return a; return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long power(long x, long y) { long temp; if (y == 0) // a^b= (a^b/2)^2 if b is even return 1; // = (a*a^(b-1)) if b is odd temp = power(x, y / 2); if (y % 2 == 0) return temp * temp; else return x * temp * temp; } static long mod(long x) { return ((x % Mod + Mod) % Mod); } static long add(long a, long b) { return mod(mod(a) + mod(b)); } static long mul(long a, long b) { return mod(mod(a) * mod(b)); } static long pow(long x, long y, int 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; } } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
db94a4548e74bf1b82bc00f0b0589af3
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class A{ // author: Tarun Verma static FastScanner sc = new FastScanner(); static int inf = 1000000007; static long mod = 1000000007; 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; } 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; } } //////////////////////////////////////////////////////////////////////////////////// ////////////////////DO NOT TOUCH BEFORE THIS LINE ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// public static void solve() { int n = sc.nextInt(); int arr[] = sc.readArray(n); ArrayList<Integer> pos1 = new ArrayList<Integer>(); ArrayList<Integer> pos0 = new ArrayList<Integer>(); for(int i =0;i<n;i++) { if(arr[i] == 1) { pos1.add(i); }else { pos0.add(i); } } if(pos1.size() == 0) { System.out.println(0); return; } int dp[][] = new int [5005][5005]; for(int i = 0;i<5005;i++) { for(int j =0;j<5005;j++) { dp[i][j] = -1; } } System.out.println(rec(0, 0, pos1, pos0, dp)); } public static int rec(int i,int j, ArrayList<Integer> pos1, ArrayList<Integer> pos0, int [][]dp) { if(i == pos1.size()) { return 0; } if(j == pos0.size()) { return inf; } if(dp[i][j] != -1) { return dp[i][j]; } //skip int ans = 1_000_000_000; ans = min(ans, rec(i, j+1, pos1, pos0, dp)); //allow ans = min(ans, rec(i+1, j+1, pos1, pos0, dp) + abs(pos1.get(i) - pos0.get(j))); return dp[i][j] = 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 */ //////////////////////////////////////////////////////////////////////////////////// }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3dc3bbad785ffefefc3ee70722ae2a0b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class _1525_D { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); int[] a = new int[n]; StringTokenizer line = new StringTokenizer(in.readLine()); int c = 0; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(line.nextToken()); if (a[i] == 1) c++; } int[] pos = new int[c]; int count = 0; for (int i = 0; i < n; i++) { if (a[i] == 1) { pos[count] = i; count++; } } int[][] dp = new int[c + 1][n]; for (int i = 1; i <= c; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); } for (int i = 1; i <= c; i++) { for (int j = 0; j < n; j++) { if (j > 0) { if (a[j] == 0) { if (dp[i - 1][j - 1] != Integer.MAX_VALUE) { dp[i][j] = dp[i - 1][j - 1] + Math.abs(j - pos[i - 1]); } } dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]); } else { if (a[j] == 0 && i == 1) { dp[i][j] = Math.abs(j - pos[i - 1]); } } } } out.println(dp[c][n - 1]); in.close(); out.close(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3c57abba4af6215651afbc169aeb9635
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class _1525_D { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); int[] a = new int[n]; StringTokenizer line = new StringTokenizer(in.readLine()); int c = 0; for(int i = 0; i < n; i++) { a[i] = Integer.parseInt(line.nextToken()); if(a[i] == 1) c++; } int[] pos = new int[c]; int count = 0; for(int i = 0; i < n; i++) { if(a[i] == 1) { pos[count] = i; count++; } } int[][] dp = new int[c + 1][n + 1]; for(int i = 1; i <= c; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); } for(int i = 1; i <= c; i++) { for(int j = 1; j <= n; j++) { if(a[j - 1] == 0) { if(dp[i - 1][j - 1] != Integer.MAX_VALUE) { dp[i][j] = dp[i - 1][j - 1] + Math.abs(j - 1 - pos[i - 1]); } } dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]); } } out.println(dp[c][n]); in.close(); out.close(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
767088435a010a850f52ec499bb0b6c3
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public final class Solution { public static void main(String[] args) throws Exception { Reader sc = new Reader(); BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); ArrayList<Integer> fill= new ArrayList<Integer>(); ArrayList<Integer> unfilled= new ArrayList<>(); for(int i=0;i<n;i++){ int x =sc.nextInt(); if(x==1){ fill.add(i); }else{ unfilled.add(i); } } Collections.sort(fill); Collections.sort(unfilled); long[][] dp =new long[fill.size()+1][unfilled.size()+1]; for(int i=0;i<fill.size()+1;i++){ for(int j=0;j<unfilled.size()+1;j++){ dp[i][j]=Integer.MAX_VALUE; } } for(int i=0;i<unfilled.size()+1;i++){ dp[0][i]=0; } // for(int j=0;j<fill.size()+1;j++){ // dp[j][0]=0; // } for(int i=1;i<fill.size()+1;i++){ for(int j=1;j<unfilled.size()+1;j++){ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(fill.get(i-1)-unfilled.get(j-1))); } } System.out.println(dp[fill.size()][unfilled.size()]); // for(int i=0;i<fill.size()+1;i++){ // for(int j=0;j<unfilled.size()+1;j++) // { // System.out.print(dp[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(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e139d1c78501ea4e143bbcefb1272de8
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* 🅻🅴🅰🆁🅽🅸🅽🅶 */ //✅// import java.util.*; import java.io.*; import java.lang.*; import java.math.BigInteger; public class D { // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { int t = 1; while (t-- > 0) D.go(); out.flush(); } static void go() { int n=sc.nextInt(); int a[]=sc.intArray(n); ArrayList<Integer> oc=new ArrayList<>(); ArrayList<Integer> unoc=new ArrayList<>(); for(int i=0;i<n;i++) { if(a[i]==1) { oc.add(i); }else { unoc.add(i); } } for(int i=0;i<5004;i++) { Arrays.fill(dp[i],-1); } out.println(solve(oc,unoc,0,0)); } static int dp[][]=new int[5010][5010]; static int solve(ArrayList<Integer> oc,ArrayList<Integer> unoc,int pos1,int pos2) { if(pos1>=oc.size()) { return 0; } if(pos2>=unoc.size()) { return Integer.MAX_VALUE/2; } if(dp[pos1][pos2]!=-1) { return dp[pos1][pos2]; } int ans=0; ans=Math.min(Math.abs(oc.get(pos1)-unoc.get(pos2))+solve(oc,unoc,pos1+1,pos2+1),solve(oc,unoc,pos1,pos2+1)); dp[pos1][pos2]=ans; return ans; } static long convert(String x) { long two=0; for(int i=0;i<x.length();i++) { two=two+pow(2,x.length()-1-i)*(x.charAt(i)-'0'); } return two; } // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static void sort(long [] a) { ArrayList<Long> aa = new ArrayList<>(); for (long i : a) { aa.add(i); }Collections.sort(aa); for (int i = 0; i < a.length; i++) a[i] = aa.get(i); } static void sort(int [] a) { ArrayList<Integer> aa = new ArrayList<>(); for (int i : a) { aa.add(i); } Collections.sort(aa); for (int i = 0; i < a.length; i++) a[i] = aa.get(i); } static long pow(long x, long y) { long res = 1l; while (y != 0) { if (y % 2 == 1) { res = x * res; } y /= 2; x = x * x; } return res; } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st== null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int 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[] intArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } long[] longArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=sc.nextLong(); return a; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a40a7f82264b55adfbc58713c59f0334
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; 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); DArmchairs solver = new DArmchairs(); solver.solve(1, in, out); out.close(); } static class DArmchairs { static ArrayList<Integer> empty; static ArrayList<Integer> chair; static long[][] dp; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.nextIntArray(n); empty = new ArrayList<>(); chair = new ArrayList<>(); for (int i = 0; i < n; i++) { int a = arr[i]; if (a == 1) chair.add(i); else empty.add(i); } dp = new long[chair.size()][empty.size()]; for (long[] row : dp) Arrays.fill(row, -1); long ans = rec(0, 0); out.println(ans); } static long rec(int i, int j) { if (i == chair.size()) return 0; int req = chair.size() - i; int have = empty.size() - j; if (req > have) return Integer.MAX_VALUE; if (dp[i][j] != -1) return dp[i][j]; long opt1 = Math.abs(chair.get(i) - empty.get(j)) + rec(i + 1, j + 1); long opt2 = rec(i, j + 1); dp[i][j] = Math.min(opt1, opt2); return dp[i][j]; } } 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 { BufferedReader reader; 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
de3670022a3811f26b3d384ec4ada255
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class d { static BufferedReader br; static long mod = 1000000000 + 7; static HashSet<Integer> p = new HashSet<>(); static boolean debug =true; // Arrays.sort(time , (a1,a2) -> (a1[0]-a2[0])); 2d array sort lamda public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int tc = 1; //tc = cinI(); while (tc-- > 0) { int n =cinI(); int[] ar=readArray(n,0,0); ArrayList<Integer> empty =new ArrayList<>(); ArrayList<Integer> filled =new ArrayList<>(); for(int i=0;i<n;i++){ if(ar[i]==0){ empty.add(i); } else { filled.add(i); } } long inf =(long)1e12; long[][] dp = new long[filled.size()][empty.size()]; for(int i=0;i<filled.size();i++){ for(int j=0;j<empty.size();j++){ dp[i][j]=inf; } } if(filled.size()==0){ System.out.println(0); System.exit(0); } if(filled.size()>=1) dp[0][0]=Math.abs(filled.get(0)-empty.get(0)); for(int j=1;j<empty.size();j++){ dp[0][j]=Math.min(dp[0][j-1],Math.abs(filled.get(0)-empty.get(j))); } for(int i=1;i<filled.size();i++){ for(int j=1;j<empty.size();j++){ long cost1 = dp[i-1][j-1]+Math.abs(filled.get(i)-empty.get(j)); dp[i][j]=min(cost1,dp[i][j-1]); } } long min=inf; for(int i=0;i<empty.size();i++){ min=min(min,dp[filled.size()-1][i]); } System.out.println(min); } } public static <E> void print(String var ,E e){ if(debug==true){ System.out.println(var +" "+e); } } private static long[] sort(long[] e){ ArrayList<Long> x=new ArrayList<>(); for(long c:e){ x.add(c); } Collections.sort(x); long[] y = new long[e.length]; for(int i=0;i<x.size();i++){ y[i]=x.get(i); } return y; } public static void printDp(long[][] dp) { int n = dp.length; for (int i = 0; i < n; i++) { for (int j = 0; j < dp[0].length; j++) { System.out.print(dp[i][j] + " "); } System.out.println(); } } private static long gcd(long a, long b) { if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a % b, b); return gcd(a, b % a); } public static long min(long a, long b) { return Math.min(a, b); } public static int min(int a, int b) { return Math.min(a, b); } public static void sieve() { int[] pf = new int[100000000 + 1]; //0 prime //1 not prime pf[0] = 1; pf[1] = 1; for (int j = 2; j <= 10000; j++) { if (pf[j] == 0) { p.add(j); for (int k = j * j; k < pf.length; k += j) { pf[k] = 1; } } } } public static int[] readArray(int n, int x, int z) throws Exception { int[] arr = new int[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getI(ar[i - x]); } return arr; } public static long[] readArray(int n, int x) throws Exception { long[] arr = new long[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getL(ar[i - x]); } return arr; } public static void arrinit(String[] a, long[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Long.parseLong(a[i]); } } public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception { HashSet<Integer>[] tree = new HashSet[n]; for (int j = 0; j < edge; j++) { String[] uv = cinA(); int u = getI(uv[0]); int v = getI(uv[1]); if (directed == 0) { tree[v].add(u); } tree[u].add(v); } return tree; } public static void arrinit(String[] a, int[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Integer.parseInt(a[i]); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b * b - 4 * a * c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double) (-b + sqrt_val) / (2 * a), (double) (-b - sqrt_val) / (2 * a)); } public static String cin() throws Exception { return br.readLine(); } public static String[] cinA() throws Exception { return br.readLine().split(" "); } public static String[] cinA(int x) throws Exception { return br.readLine().split(""); } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } public static Integer cinI() throws Exception { return Integer.parseInt(br.readLine()); } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static long max(long a, long b) { return Math.max(a, b); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x) { System.out.println(String.valueOf(x)); } public static void coutI(long x) { System.out.println(String.valueOf(x)); } public static Long cinL() throws Exception { return Long.parseLong(br.readLine()); } public static void arrInit(String[] arr, int[] arr1) throws Exception { for (int i = 0; i < arr.length; i++) { arr1[i] = getI(arr[i]); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
580d86da0f831ff2a28ced0bcf96d3d5
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package currentContest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class P4 { static int dp[][]=new int[5000+1][5000+1]; public static void main(String[] args) { // TODO Auto-generated method stub FastReader sc=new FastReader(); int t=1; //t=sc.nextInt(); StringBuilder s=new StringBuilder(); while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { P4.dp[i][j]=-1; } } ArrayList<Integer> one=new ArrayList<>(); ArrayList<Integer> zero=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]==0) { zero.add(i); }else { one.add(i); } } Collections.sort(zero); Collections.sort(one); long ans=sol(0,0,zero.size(),one.size(),a,zero,one); System.out.println(ans); } //System.out.println(s); } private static long sol(int i, int j, int n, int m,int a[], ArrayList<Integer> zero, ArrayList<Integer> one) { //System.out.println(i+" "+j); // TODO Auto-generated method stub if(j==m) { return 0; } int av=n-i; int rem=m-j; if(av<rem) { return Integer.MAX_VALUE-1; } if(dp[i][j]!=-1) { return dp[i][j]; } long ans1=sol(i+1,j,n,m,a, zero, one); long ans2=Math.abs(zero.get(i)-one.get(j))+sol(i+1,j+1,n,m,a, zero, one); dp[i][j]=(int) Math.min(ans1, ans2); return dp[i][j]; } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5953ae4c7ae347ded7aa642d690d9f62
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//package currentContest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class P4 { static int dp[][]=new int[5000+1][5000+1]; public static void main(String[] args) { // TODO Auto-generated method stub FastReader sc=new FastReader(); int t=1; //t=sc.nextInt(); StringBuilder s=new StringBuilder(); while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { P4.dp[i][j]=-1; } } ArrayList<Integer> one=new ArrayList<>(); ArrayList<Integer> zero=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]==0) { zero.add(i); }else { one.add(i); } } Collections.sort(zero); Collections.sort(one); long ans=sol(0,0,zero.size(),one.size(),a,zero,one); System.out.println(ans); } //System.out.println(s); } private static long sol(int i, int j, int n, int m,int a[], ArrayList<Integer> zero, ArrayList<Integer> one) { //System.out.println(i+" "+j); // TODO Auto-generated method stub if(j==m) { return 0; } int av=n-i; int rem=m-j; if(av<rem) { return Integer.MAX_VALUE/2; } if(dp[i][j]!=-1) { return dp[i][j]; } long ans1=sol(i+1,j,n,m,a, zero, one); long ans2=Math.abs(zero.get(i)-one.get(j))+sol(i+1,j+1,n,m,a, zero, one); dp[i][j]=(int) Math.min(ans1, ans2); return dp[i][j]; } 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
72f2c4737cc48d71d756b2167f352125
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//https://codeforces.com/contest/1525/problem/D //D. Armchairs import java.util.*; import java.io.*; public class CF_1525_D{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); StringTokenizer st; int n = Integer.parseInt(br.readLine()); int a[] = new int[n]; ArrayList<Integer> pos = new ArrayList<Integer>(); st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ a[i] = Integer.parseInt(st.nextToken()); if(a[i]==1) pos.add(i); } int z = pos.size(); int dp[][] = new int[n+1][z+1]; for(int i=0;i<=n;i++) Arrays.fill(dp[i], Integer.MAX_VALUE); dp[0][0] = 0; for(int i=0;i<n;i++){ for(int j=0;j<=z;j++){ if(dp[i][j] == Integer.MAX_VALUE) continue; dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]); if(j<z && a[i]==0) dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j]+Math.abs(pos.get(j)-i)); } } pw.print(dp[n][z]); pw.flush(); pw.close(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
de3b8134eee551dfded490608ee1b105
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class a2oj implements Runnable { static FastReader sc; static PrintWriter out; static int mod = 1000000007; public static void main(String[] args) { new Thread(null, new a2oj(), "coderrohan14", 1 << 26).start(); } @Override public void run() { try { ioSetup(); } catch (IOException e) { return; } } public static void ioSetup() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { File f1 = new File("input.txt"); File f2 = new File("output.txt"); Reader r = new FileReader(f1); sc = new FastReader(r); out = new PrintWriter(f2); double prev = System.currentTimeMillis(); solve(); out.println("\n\nExecuted in : " + ((System.currentTimeMillis() - prev) / 1e3) + " sec"); } else { sc = new FastReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } out.flush(); out.close(); } static int n, arr[], dp[][]; static ArrayList<Integer> ones, zeroes; static void solve() { // int t = sc.nextInt(); // StringBuilder ans = new StringBuilder(""); // while (t-- > 0) { // } // out.println(ans); n = sc.nextInt(); ones = new ArrayList<>(); zeroes = new ArrayList<>(); arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); if (arr[i] == 1) { ones.add(i); } else { zeroes.add(i); } } dp = new int[zeroes.size() + 1][ones.size() + 1]; for (int i = 0; i <= zeroes.size(); i++) { Arrays.fill(dp[i], -1); } out.println(armch(0, 0, zeroes.size(), ones.size())); } static int armch(int i, int j, int n, int m) { if (j == m) return 0; int zs = n - i, os = m - j; if (zs < os) return Integer.MAX_VALUE; if (dp[i][j] != -1) return dp[i][j]; int a1 = armch(i + 1, j, n, m); int a2 = armch(i + 1, j + 1, n, m); if (a2 != Integer.MAX_VALUE) a2 += Math.abs(zeroes.get(i) - ones.get(j)); int min = Math.min(a1, a2); return dp[i][j] = min; } /****************************************************************************************************************************************************************************************/ static long modInverse(long a, int mod) { long g = gcd(a, mod); if (g != 1) return -1; else { return modPower(a, mod - 2L, mod); } } static long modPower(long x, long y, int mod) { long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; x = (x * x) % mod; } return res; } static int gcd(int a, int b) { int tmp = 0; while (b != 0) { tmp = b; b = a % b; a = tmp; } return a; } static long gcd(long a, long b) { long tmp = 0; while (b != 0) { tmp = b; b = a % b; a = tmp; } return a; } static boolean isPrime(long n) { if (n == 2 || n == 3) return true; if (n % 2 == 0) return false; for (long i = 3; i * i <= n; i += 2) { if (n % i == 0) return false; } return n != 1; } static boolean isPerfectSquare(long x) { long sqrt = (long) Math.sqrt(x); return (sqrt * sqrt) == x; } static int digitsCount(long x) { return (int) Math.floor(Math.log10(x)) + 1; } static boolean isPowerTwo(long n) { return (n & n - 1) == 0; } static void sieve(boolean[] prime, int n) { // Sieve Of Eratosthenes for (int i = 1; i <= n; i++) { prime[i] = true; } for (int i = 2; i * i <= n; i++) { if (prime[i]) { for (int j = 2; i * j <= n; j++) { prime[i * j] = false; } } } } static long nCr(long n, long r) { // Combinations if (n < r) return 0; if (r > n - r) { // because nCr(n, r) == nCr(n, n - r) r = n - r; } long ans = 1L; for (long i = 0; i < r; i++) { ans *= (n - i); ans /= (i + 1); } return ans; } static int floor(int[] a, int v) { int l = 0, h = a.length - 1; while (l < h) { int mid = (l + h) / 2; if (a[mid] == v) return mid; if (v < a[mid]) h = mid; else { if (mid + 1 < h && a[mid + 1] < v) l = mid + 1; else return mid; } } return a[l] <= v ? l : -1; } static int floor(long[] a, long v) { int l = 0, h = a.length - 1; while (l < h) { int mid = (l + h) / 2; if (a[mid] == v) return mid; if (v < a[mid]) h = mid; else { if (mid + 1 < h && a[mid + 1] < v) l = mid + 1; else return mid; } } return a[l] <= v ? l : -1; } static int ceil(int[] a, int v) { int l = 0, h = a.length - 1; while (l < h) { int mid = (l + h) / 2; if (a[mid] == v) return mid; if (a[mid] < v) l = mid + 1; else h = mid; } return a[h] >= v ? h : -1; } static int ceil(long[] a, long v) { int l = 0, h = a.length - 1; while (l < h) { int mid = (l + h) / 2; if (a[mid] == v) return mid; if (a[mid] < v) l = mid + 1; else h = mid; } return a[h] >= v ? h : -1; } static long catalan(int n) { // n-th Catalan Number long c = nCr(2 * n, n); return c / (n + 1); } static class Pair implements Comparable<Pair> { // Pair Class int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Pair)) { return false; } Pair pair = (Pair) o; if (x != pair.x) { return false; } if (y != pair.y) { return false; } return true; } @Override public int hashCode() { long result = x; result = 31 * result + y; return (int) result; } @Override public int compareTo(Pair o) { return (int) (this.x - o.x); } } static class Trip { // Triplet Class long x; long y; long z; Trip(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Trip)) { return false; } Trip trip = (Trip) o; if (x != trip.x) { return false; } if (y != trip.y) { return false; } if (z != trip.z) { return false; } return true; } @Override public int hashCode() { long result = 62 * x + 31 * y + z; return (int) result; } } /**************************************************************************************************************************************************************************************/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(Reader r) { br = new BufferedReader(r); } 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()); } int[] readArrayI(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } return arr; } long[] readArrayL(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } return arr; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } /* * ASCII Range--->(A-Z)--->[65,90]<<::>>(a-z)--->[97,122] */ /******************************************************************************************************************/ static void printArray(int[] arr) { out.print("["); for (int i = 0; i < arr.length; i++) { if (i < arr.length - 1) out.print(arr[i] + ","); else out.print(arr[i]); } out.print("]"); out.println(); } static void printArray(long[] arr) { out.print("["); for (int i = 0; i < arr.length; i++) { if (i < arr.length - 1) out.print(arr[i] + ","); else out.print(arr[i]); } out.print("]"); out.println(); } static void printArray(double[] arr) { out.print("["); for (int i = 0; i < arr.length; i++) { if (i < arr.length - 1) out.print(arr[i] + ","); else out.print(arr[i]); } out.print("]"); out.println(); } /**********************************************************************************************************************/ }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3773a56475c3ea58e6f68878177669d0
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class B { static int mod=1000_000_007; static int max=5001; static List<Integer> rem=new ArrayList<>(); static List<Integer> ocu=new ArrayList<>(); static int dp[][]=new int[max][max]; static int r,o; public static void main(String[] args) throws Exception { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); int n=fs.nextInt(); for(int i=0;i<n;i++) { int a=fs.nextInt(); if(a==0) rem.add(i); else ocu.add(i); } r=rem.size(); o=ocu.size(); if(o==0) { System.out.println(0); return ; } for(int i=0;i<max;i++) Arrays.fill(dp[i], -1); Collections.sort(rem);; Collections.sort(ocu); int ans=solve(0,0); System.out.println(ans); } static int solve(int i,int j) { if(j==o) return 0; if(r-i<o-j) return Integer.MAX_VALUE/2; if(dp[i][j]!=-1) return dp[i][j]; int ans1=solve(i+1,j); int ans2=Math.abs(rem.get(i)-ocu.get(j))+solve(i+1,j+1); return dp[i][j]=Math.min(ans1, ans2); } static void sort(int[] a) { //suffle 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; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner 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
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
ee51da4d17c8c47a290e2245e9b3e141
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; 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.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { FastReader scn = new FastReader(); int n = scn.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scn.nextInt(); } ArrayList<Integer> one = new ArrayList<>(); ArrayList<Integer> two = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == 1) { one.add(i); } else { two.add(i); } } int[] arr1 = one.stream().mapToInt(i -> i).toArray(); int[] arr2 = two.stream().mapToInt(i -> i).toArray(); int[][] dp = new int[arr1.length + 1][arr2.length + 1]; for (int[] a : dp) { Arrays.fill(a, -1); } System.out.println(solve(arr1, 0, arr2, 0, dp)); } public static int solve(int[] arr1, int vidx1, int[] arr2, int vidx2, int[][] dp) { int n = arr1.length; int m = arr2.length; if (vidx1 == n) { return 0; } if (m - vidx2 < n - vidx1) { return 100000000; } if (dp[vidx1][vidx2] != -1) { return dp[vidx1][vidx2]; } int one = solve(arr1, vidx1 + 1, arr2, vidx2 + 1, dp) + Math.abs(arr1[vidx1] - arr2[vidx2]); int two = solve(arr1, vidx1, arr2, vidx2 + 1, dp); return dp[vidx1][vidx2] = Math.min(one, two); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
89d3cdb8fe96b7157c14aa389cd2a168
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public final class Solution { static int retAns(ArrayList<Integer> zeroes, ArrayList<Integer> ones, int dp[][], int i, int j) { if (i == ones.size()) { return 0; } else if (j == zeroes.size()) { return -1; } else if (dp[i][j] != 1000000000) { return dp[i][j]; } else { int val = retAns(zeroes, ones, dp, i, j + 1); int val1 = retAns(zeroes, ones, dp, i + 1, j + 1); int MINI = val; if (val1 != -1) { if (MINI == -1) { MINI = val1 + Math.abs(zeroes.get(j) - ones.get(i)); } else { MINI = Math.min(MINI, val1 + Math.abs(zeroes.get(j) - ones.get(i))); } } dp[i][j] = MINI; return dp[i][j]; } } public static void main(String[] args) throws IOException { FastScanner input = new FastScanner(false); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); ArrayList<Integer> zeroes = new ArrayList<>(); ArrayList<Integer> ones = new ArrayList<>(); for (int i = 0; i < n; i++) { int val = input.nextInt(); if (val == 1) { ones.add(i); } else { zeroes.add(i); } } if (ones.size() == 0) { out.println(0); } else { int dp[][] = new int[ones.size()][zeroes.size()]; for (int i = 0; i < ones.size(); i++) { for (int j = 0; j < zeroes.size(); j++) { dp[i][j] = 1000000000; } } out.println(retAns(zeroes, ones, dp, 0, 0)); } out.flush(); } private static class FastScanner { private final int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner(boolean usingFile) throws IOException { if (usingFile) din = new DataInputStream(new FileInputStream("path")); else din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private 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; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } 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++]; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 11
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output