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
sequencelengths
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
f571402bb7ec779328eb1064676bf0f4
train_000.jsonl
1580826900
You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Sumodd{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int count1 =0; int count2 =0; for(int i =0;i<a;i++){ int b = in.nextInt(); int[] arr = new int[b]; for(int k = 0;k<arr.length;k++){ arr[k] = in.nextInt(); if(arr[k]%2==0){ count1++; }else{ count2++; } } if((b%2==0 && count2==b) || count1==b ){ System.out.println("NO"); }else { System.out.println("YES"); } count1=0; count2=0; } } }
Java
["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"]
1 second
["YES\nNO\nYES\nNO\nNO"]
null
Java 11
standard input
[ "math" ]
2e8f7f611ba8d417fb7d12fda22c908b
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β€” the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β€” the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).
800
For each test case, print the answer on it β€” "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.
standard output
PASSED
535c09a8b4e2e9a5c479b0d49ba790f4
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class ff { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); HashMap<Integer,Integer> mp=new HashMap<Integer,Integer>(); int n=in.nextInt(); int x=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=in.nextInt(); map.putIfAbsent(a[i], 0); map.put(a[i], map.get(a[i])+1); } int max=Collections.max(map.values()); if(max>=2) System.out.println(0); else {int t=0; for(int i=0;i<n;i++) { if(map.containsKey(x&a[i])&&x!=a[i]&&((x&a[i])!=a[i])) { System.out.println(1);t=1;break; } mp.putIfAbsent(x&a[i], 0); mp.put(x&a[i], mp.get(x&a[i])+1); } if(t==0) if(Collections.max(mp.values())>=2) System.out.println(2); else System.out.println(-1); } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
fdd4f0de54f6889c41c59b84b7564bf2
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; public class a { static int mod = (int) 1e9 + 7; static int Infinity=Integer.MAX_VALUE; static int negInfinity=Integer.MIN_VALUE; public static void main(String args[]) { Scanner d= new Scanner(System.in); int n,x,i,z; n=d.nextInt(); x=d.nextInt(); int a[]=new int[n]; Set <Integer> s=new HashSet<>(); Set <Integer> s1=new HashSet<>(); for(i=0;i<n;i++) a[i]=d.nextInt(); z=-1; for(i=0;i<n;i++) { if(s.isEmpty()) {s.add(a[i]); s1.add(a[i]&x); } else if(s.contains(a[i])) { z=0; } else if(s.contains(a[i]&x) || s1.contains(a[i])) { if(z!=0) {z=1; s.add(a[i]);} } else { s.add(a[i]); s1.add(a[i]&x); } } if(s1.size()<s.size() && z==-1) System.out.println(2); else System.out.println(z); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
5f53dab0254a466d9e0c00c7d4796b60
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.*; import java.util.*; public class CFB { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; void solve() throws IOException { int n = nextInt(); int x = nextInt(); int[] arr = nextIntArr(n); int limit = 200000 + 10; int[] hist = new int[limit]; for (int v : arr) { hist[v]++; } for (int v : hist) { if (v >= 2) { outln(0); return; } } int res = Integer.MAX_VALUE; List<List<Integer>> cnts = new ArrayList<>(); for (int i = 0; i < limit; i++) { cnts.add(new ArrayList<>()); } for (int j = 0; j < limit; j++) { if (hist[j] > 0) { List<Integer> ls = findList(j, x); for (int i = 0; i < ls.size(); i++) { cnts.get(ls.get(i)).add(i); } } } for (List<Integer> cnt : cnts) { Collections.sort(cnt); if (cnt.size() >= 2) { res = Math.min(res, cnt.get(0) + cnt.get(1)); } } outln(res == Integer.MAX_VALUE ? -1 : res); } List<Integer> findList(int start, int x) { List<Integer> res = new ArrayList<>(); res.add(start); while ((start & x) != start) { res.add(start & x); start = start & x; } return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFB() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFB(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
44d3edf191999f51e3524356996f493f
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
//package codeforces.Round500; import java.util.HashMap; import java.util.Scanner; public class And { private static HashMap<Integer, Boolean> visited; private static HashMap<Integer, Boolean> visitedAnd; public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int x = s.nextInt(); visited = new HashMap<>(n); visitedAnd = new HashMap<>(n); boolean zero = false; boolean one = false; boolean two = false; for (int i = 0; i < n; i++) { int a = s.nextInt(); int inverse = a & x; if (visited.containsKey(a)) zero = true; else if (visited.containsKey(inverse)) one = true; else if (visitedAnd.containsKey(a)) one = true; else if (visitedAnd.containsKey(inverse)) two = true; visited.put(a, true); visitedAnd.put(inverse, true); } if (zero) System.out.println("0"); else if (one) System.out.println("1"); else if (two) System.out.println("2"); else System.out.println("-1"); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
37ecae2f73bff34e7a836c687b2e3712
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.*; import java.lang.*; public class CF1013B { public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int x = Integer.parseInt(s[1]); boolean[] arr = new boolean[100001]; boolean[] arr2 = new boolean[100001]; int[] a = new int[n]; s = br.readLine().split(" "); for(int i=0;i<n;i++){ a[i] = Integer.parseInt(s[i]); } int ans = 200; for(int i=0;i<n;i++){ if(arr[a[i]]){ ans = Math.min(ans, 0); }else if(arr[a[i]&x]){ ans = Math.min(ans, 1); //System.out.println(a[i] + " "+(a[i]&x)); break; }else if(arr2[a[i]]){ ans = Math.min(ans, 1); }else if(arr2[a[i] & x]){ ans = Math.min(ans, 2); } arr2[a[i]&x] = true; arr[a[i]] = true; } if(ans == 200){ ans = -1; } System.out.println(ans); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
7766750ef62e1da5d42329f11c2f50cc
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class And { public static void main(String[] args) { FastReader input = new FastReader(); OutputStream ob = System.out; PrintWriter out = new PrintWriter(ob); int n = input.nextInt(); int x = input.nextInt(); int[] arr = new int[n]; int[] count = new int[2000000]; int[] count2 = new int[2000000]; for(int i = 0;i < n;i++){ arr[i] = input.nextInt(); count[arr[i]]++; if(count[arr[i]] > 1) { out.print(0); out.flush(); return; } int val = arr[i] & x; count2[val]++; } for(int i = 0;i < n;i++){ int val = arr[i] & x; if(val == arr[i] && count[val] > 1){ out.print(1); out.flush(); return; } else if(val != arr[i] && count[val] > 0){ out.print(1); out.flush(); return; } } for(int i : count2){ if(i > 1){ out.print(2); out.flush(); return; } } out.print(-1); out.flush(); } 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
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
c09001dc608b22ac12b5b54391acfb00
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; import java.math.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; //--------------->>>>IF YOU ARE HERE FOR QUICKSORT HACK THEN SORRY NO HACK FOR YOU<<<------------------- public class a{ static int[] count,count1,count2; static Node[] nodes; static int[] arr; static int[] dp; static char[] ch,ch1; static int[] darr,farr; static Character[][] mat,mat1; static long x,h; static long maxl; static double dec; static String s; static long minl; static int mx = (int)1e9+5; static long mod = 998244353l; // static int minl = -1; // static long n; static int n,n1,n2; static long a; static long b; static long c; static long d; static long y,z; static int m; static long k; static String[] str,str1; static Set<Long> set,set1,set2; static List<Long> list,list1,list2,list3; static LinkedList<Node> ll; static Map<String,String> map; static StringBuilder sb,sb1,sb2; static int[] dx = {0,-1,0,1}; static int[] dy = {-1,0,1,0}; // public static void solve(){ // FastScanner sc = new FastScanner(); // int n = sc.nextInt(); // long m = sc.nextLong(); // list = new ArrayList<>(); // long sum = 0; // for(int i = 0 ; i < n ; i++){ // long a = sc.nextLong(); // long b = sc.nextLong(); // list.add(a-b); // sum += a; // } // if(sum <= m){ // System.out.println("0"); // return; // } // Collections.sort(list); // for(int i = n-1 ; i > -1 ; i--){ // sum -= list.get(i); // if(sum <= m){ // System.out.println(n-i); // return; // } // } // System.out.println("-1"); // } //--------------->>>>IF YOU ARE HERE FOR QUICKSORT HACK THEN SORRY NO HACK FOR YOU<<<------------------- public static void solve(){ count = new int[100005]; count1 = new int[100005]; for(int i = 0 ; i < n ; i++){ count[arr[i]] += 1; if(count[arr[i]] == 2){ System.out.println("0"); return; } } int minl = -1; for(int i = 0 ; i < n; i++){ count1[arr[i]&m] += 1; if(((count[arr[i]&m] == 1) && ((arr[i]&m) != arr[i]))){ System.out.println("1"); return; } if((count1[arr[i]&m] == 2)){ minl = 2; } } System.out.println(minl); } public static void main(String[] args) { FastScanner sc = new FastScanner(); // Scanner sc = new Scanner(System.in); // int t = sc.nextInt(); int t = 1; // int l = 1; while(t > 0){ // n = sc.nextInt(); // n = sc.nextLong(); // a = sc.nextLong(); // b = sc.nextLong(); // c = sc.nextLong(); // d = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // n = sc.nextLong(); n = sc.nextInt(); // n1 = sc.nextInt(); m = sc.nextInt(); // k = sc.nextLong(); // s = sc.next(); // ch = sc.next().toCharArray(); // ch1 = sc.next().toCharArray(); arr = new int[n]; for(int i = 0 ; i < n ; i++){ arr[i] = sc.nextInt(); } // m = n; // darr = new int[m]; // for(int i = 0; i < m ; i++){ // darr[i] = sc.nextInt(); // } // farr = new int[n]; // for(int i = 0; i < n ; i++){ // farr[i] = sc.nextInt(); // } // mat = new Character[n][n]; // for(int i = 0 ; i < n ; i++){ // String s = sc.next(); // for(int j = 0 ; j < n ; j++){ // mat[i][j] = s.charAt(j); // } // } // str = new String[n]; // for(int i = 0 ; i < n ; i++) // str[i] = sc.next(); // nodes = new Node[n]; // for(int i = 0 ; i < n ;i++) // nodes[i] = new Node(sc.nextInt(),sc.nextInt()); // System.out.println(solve()?"YES":"NO"); solve(); // System.out.println(solve()); t -= 1; } } public static int log(long n){ if(n == 0 || n == 1) return 0; if(n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if(den == 0) return 0; return (int)(num/den); } public static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } public static long gcd(long a,long b){ if(b%a == 0){ return a; } return gcd(b%a,a); } // public static void swap(int i,int j){ // long temp = arr[j]; // arr[j] = arr[i]; // arr[i] = temp; // } static final Random random=new Random(); static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class Node{ int first; int second; Node(int f,int s){ this.first = f; this.second = s; } } 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
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
79a681c648f919af2a0bcf171431b085
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; 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); TaskC solver = new TaskC(); solver.solve(in, out); out.close(); } static class TaskC { public void solve( InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); int[] arr = new int[n]; int[] freq = new int[100000+1]; boolean[] and = new boolean[100000+1]; for (int i = 0; i <n ; i++) { arr[i]=in.nextInt(); freq[arr[i]]++; } int min = 0; boolean ok = false; for (int i = 0; i <arr.length ; i++){ if (freq[arr[i]] > 1){ ok = true; break; } } if (ok){ out.println(min); return; } min=1; for (int i = 0; i <n; i++){ freq[arr[i]]--; int v = (arr[i]&x); freq[v]++; if (freq[v] > 1){ ok=true; break; } freq[arr[i]]++; freq[v]--; } if (ok){ out.println(min); return; } min = 2; for (int i = 0; i <arr.length ; i++) { freq[arr[i]]--; freq[(arr[i]&x)]++; if (freq[(arr[i]&x)] > 1){ ok = true; break; } } if (ok){ out.println(min); return; } out.println(-1); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
10d42c42b0c268d419a084a894037862
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.Scanner; public class CF1012B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); int[] arr = new int[n]; int[] freq = new int[100100]; for(int i=0; i<n; i++) { arr[i] = sc.nextInt(); freq[arr[i]]++; } boolean has = false; for(int i=0; i<n; i++) if(freq[arr[i]]>=2) { has = true; break; } if(has) System.out.println("0"); else { int[] m = new int[n]; for(int i=0; i<n; i++) m[i] = arr[i]&x; for(int i=0; i<n; i++) if(arr[i]!=m[i] && freq[m[i]]>=1) { has = true; break; } if(has) System.out.println("1"); else { int[] modFreq = new int[100100]; for(int i=0; i<n; i++) modFreq[m[i]]++; for(int i=0; i<n; i++) if(modFreq[m[i]]>=2) { has = true; break; } System.out.println(has ? "2" : "-1"); } } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
9ab36e45a28a220b7bf3e6de7e058539
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int[]a= new int[n]; int[]nums = new int[100001]; for (int i =0;i<n;i++) { a[i] = in.nextInt(); nums[a[i]]++; } int ans=-1; for (int i =0;i<n;i++) { nums[a[i]]--; if (nums[a[i]]>0) { ans = 0; break; } nums[a[i]]++; } if (ans==-1) for (int i =0;i<n;i++) { nums[a[i]]--; if (nums[a[i]&k]>0) { ans = 1; break; } nums[a[i]]++; } if (ans==-1) { nums = new int[100001]; for (int i =0;i<n;i++) { a[i] &= k; nums[a[i]]++; } for (int i =0;i<n;i++) { nums[a[i]]--; if (nums[a[i]&k]>0) { ans = 2; break; } nums[a[i]]++; } } out.printLine(ans); out.flush(); } static void MergeSort(int[] a, int[] b, int p, int r) { if (p < r) { int q = (r + p) / 2; MergeSort(a, b, p, q); MergeSort(a, b, q + 1, r); Merge(a, b, p, q, r); } } static void Merge(int[] a, int[] b, int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int[] R = new int[n1 + 1]; int[] L = new int[n2 + 1]; int[] R1 = new int[n1]; int[] L1 = new int[n2]; for (int i = 0; i < n1; i++) { R[i] = a[p + i]; R1[i] = b[p + i]; } R[n1] = Integer.MAX_VALUE; for (int i = 0; i < n2; i++) { L[i] = a[q + i + 1]; L1[i] = b[q + i + 1]; } L[n2] =Integer.MAX_VALUE; int n = a.length; int j = 0; int k = 0; for (int i = p; i <= r; i++) { if (L[j] < R[k]) { a[i] = L[j]; b[i] = L1[j]; j++; } else { a[i] = R[k]; b[i] = R1[k]; k++; } } } } class pair implements Comparable { int key; int value; public pair(Object key, Object value) { this.key = (int)key; this.value=(int)value; } @Override public int compareTo(Object o) { pair temp =(pair)o; return key-temp.key; } } class Graph { int n; ArrayList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
a9fcc1572c69aa52f5945620110931ad
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; public class and { public static void main(String args[])throws IOException { BufferedReader BR=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(BR.readLine()); int n=Integer.parseInt(st.nextToken()); int x=Integer.parseInt(st.nextToken()); StringTokenizer st1=new StringTokenizer(BR.readLine()); ArrayList<Integer> arr=new ArrayList<Integer>(); ArrayList<Integer> arr1=new ArrayList<Integer>(); HashMap<Integer,Integer> h=new HashMap<Integer,Integer>(); HashMap<Integer,Integer> h1=new HashMap<Integer,Integer>(); int c=Integer.MAX_VALUE; boolean b=true; for(int i=0;i<n;i++) { int y=Integer.parseInt(st1.nextToken()); int j=y&x; if(h.containsKey(y)) { c=Math.min(c,0); b=false; h.put(y,h.get(y)+1); } else { h.put(y,1); } } Iterator it = h.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); int a=(int) pair.getKey(); int j=a&x; if(h1.containsKey(j)) { h1.put(j,h1.get(j)+1); c=Math.min(c, 2); b=false; } else { h1.put(j,1); } if(a==j) { continue; } if(h.containsKey(j)) { c=Math.min(c,1); b=false; } } if(b) System.out.println(-1); else System.out.println(c); } } class n { int x=0; ArrayList<Integer> y=new ArrayList<Integer>(); }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
fc0d964249ceefe635468107aefa8a86
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 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.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[] ) { FastReader sc = new FastReader(); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; int[] and = new int[n]; int res=-1; HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer,HashSet<Integer>>(); for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); } for(int i=0;i<n;i++){ and[i] = arr[i]&k; if( map.containsKey(and[i]) ){ HashSet<Integer> set = map.get(and[i]); set.add(i); map.put(and[i], set); res=2; }else{ HashSet<Integer> set = new HashSet<Integer>(); set.add(i); map.put(and[i], set); } } for(int i=0;i<n;i++){ if(map.containsKey(arr[i])) { HashSet<Integer> set = map.get(arr[i]); if(!set.contains(i)||set.size()>1){ res=1; break; } } } Arrays.sort(arr); for(int i=0;i<n-1;i++){ if(arr[i]==arr[i+1]){ res=0; break; } } System.out.println(res); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
150c3752a552eb3b8c4b1d6e40afc187
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.util.*; import java.io.BufferedWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; public class B1013 { static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } } public static void main(String[] args) { //InputStream inputStream = System.in; OutputStream outputStream = System.out; //InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //int n = in.readInt(); int n = sc.nextInt(); int k = sc.nextInt(); //int[] temparr = IOUtils.readIntArray(in, n); int[] arr = new int[n]; Map<Integer, Integer> map = new HashMap<>(); Map<Integer, Integer> map1 = new HashMap<>(); Map<Integer, Integer> map2 = new HashMap<>(); Map<Integer, Integer> map3 = new HashMap<>(); Set<Integer> set = new HashSet<>(); int flag = 0; for (int i=0; i<n; i++) { arr[i] = sc.nextInt(); if (set.contains(arr[i])) { flag = 1; //break; } set.add(arr[i]); map.put(arr[i], i); } if (flag ==1 ) { System.out.println(0); } else { int ans = 0; set.clear(); for (int i=0; i<n; i++) { arr[i] &= k; if (map.containsKey(arr[i]) && map.get(arr[i]) != i) { //System.out.println("yo"); ans = 1; break; } map1.put(arr[i], i); } if (ans == 1) { System.out.println(1); } else if (map1.size() != n) { System.out.println(2); } else { ans = Integer.MAX_VALUE; for (int i=0; i<n; i++) { arr[i] &= k; if (map.containsKey(arr[i]) && map.get(arr[i]) != i) { ans = Math.min(ans, 2); //break; } else if (map1.containsKey(arr[i]) && map1.get(arr[i]) != i) { ans = Math.min(ans, 3); } else { map2.put(arr[i], i); } } if (ans != Integer.MAX_VALUE) { System.out.println(ans); } else if (map2.size()!=n) { System.out.println(4); }else { for (int i=0; i<n; i++) { arr[i] &= k; if (map.containsKey(arr[i]) && map.get(arr[i]) != i) { ans = Math.min(ans, 3); //break; } else if (map1.containsKey(arr[i]) && map1.get(arr[i]) != i) { ans = Math.min(ans, 3); } else if (map2.containsKey(arr[i]) && map2.get(arr[i]) != i) { ans = Math.min(ans, 4); } else { map3.put(arr[i], 1); } } } if (map3.size() != n) { System.out.println(Math.min(ans, 6)); } else { System.out.println(ans == Integer.MAX_VALUE ? -1 : ans); } } } //out.printLine(rating); out.close(); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
2d793af57fd83dbe7ee7638d78a28765
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int x = scanner.nextInt(); int[] a = new int[n]; Set<Integer> set = new TreeSet<>(); Set<Integer> setx = new TreeSet<>(); boolean f = false; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); set.add(a[i]); } if (set.size() != n) { System.out.println(0); return; } for (int i = 0; i < n; i++) { if (set.contains(a[i] & x) && a[i] != (a[i] & x)) { System.out.println(1); return; } else if (setx.contains(a[i] & x)) { f = true; } else { setx.add(a[i] & x); } } if (f) { System.out.println(2); } else { System.out.println(-1); } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
039aea370912043ec422c8c450fef461
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author shivam */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); int arr[] = new int[n]; int flag = 0; HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); if (set.contains(arr[i])) flag = 1; set.add(arr[i]); } if (flag == 1) { out.println(0); return; } int b[] = new int[n]; for (int i = 0; i < n; i++) { b[i] = arr[i] & x; } Arrays.sort(b); int flagx = 0; int flag2 = 0; for (int i = 1; i < n; i++) { if (b[i - 1] == b[i]) { if (set.contains(b[i])) flagx = 1; flag2 = 1; } } if (flag2 == 1 && flagx == 1) out.println(1); else if (flag2 == 1 && flagx == 0) out.println(2); else out.println(-1); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
dbff4aee3f1328896b6a313fbeaad6f3
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigDecimal; public class Solution { static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void main(String[] args)throws Exception { InputReader in=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); int n=in.nextInt(); int x=in.nextInt(); int[] ar=new int[n]; ar=in.nextIntArray(n); int[] fr=new int[100001]; for(int i=0;i<n;i++) { fr[ar[i]]++; } boolean pos=false; Arrays.sort(ar); for(int i=0;i<n;i++) { if(fr[ar[i]]>=2) { pos=true; break; } } if(!pos) { int min=Integer.MAX_VALUE; int[] count=new int[100001]; for(int i=n-1;i>=0;i--) { if((fr[ar[i]&x]>=1) && (ar[i]&x)!=ar[i]) { count[ar[i]&x]++; if(count[ar[i]&x]<min) min=count[ar[i]&x]; pos=true; } else { fr[ar[i]]--; ar[i]=ar[i]&x; fr[ar[i]]++; count[ar[i]]++; } } if(pos) { w.println(min); } else { w.println("-1"); } } else { w.println("0"); } w.close(); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
fd527eb16838d3c1095b688251793320
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; public class ques2 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=0,x=0,k=0,c=0; if(scan.hasNext()) n=scan.nextInt(); if(scan.hasNext()) x=scan.nextInt(); Set<Integer> set=new HashSet<>(),set2=new HashSet<>(); for (int i=0;i<n;i++){ if(scan.hasNext()) k=scan.nextInt(); set.add(k); if((k&x)!=k) set2.add(k&x); else c++; } if(set.size()!=n){ System.out.println(0); return; }else{ Iterator<Integer> it=set.iterator(); while(it.hasNext()){ if(set2.contains(it.next())){ System.out.println(1); return; } } if(set2.size()!=n-c) { System.out.println(2); return; } } System.out.println(-1); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
829b19753fc88ad0a6a8f208a57f4801
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.*; public class and{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int[] arr = new int[n]; int[] freq = new int[100000+1]; boolean[] and = new boolean[100000+1]; for (int i = 0; i <n ; i++) { arr[i]=in.nextInt(); freq[arr[i]]++; } int min = 0; boolean ok = false; for (int i = 0; i <arr.length ; i++){ if (freq[arr[i]] > 1){ ok = true; break; } } if (ok){ System.out.println(min); return; } min=1; for (int i = 0; i <n; i++){ freq[arr[i]]--; int v = (arr[i]&x); freq[v]++; if (freq[v] > 1){ ok=true; break; } freq[arr[i]]++; freq[v]--; } if (ok){ System.out.println(min); return; } min = 2; for (int i = 0; i <arr.length ; i++) { freq[arr[i]]--; freq[(arr[i]&x)]++; if (freq[(arr[i]&x)] > 1){ ok = true; break; } } if (ok){ System.out.println(min); return; } System.out.println(-1); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
636b9516d7699e5b3db60b06f0298264
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * @author Avto * @email [email protected] */ public class Problem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int x = scanner.nextInt(); int[] arr = new int[n]; boolean isDist = true; Set<Integer> was = new HashSet<>(); Set<Integer> dist = new HashSet<>(); for (int i = 0; i < n; i++) { int current = scanner.nextInt(); arr[i] = current; if (was.contains(current)) { System.out.println(0); return; } if (dist.contains(current & x)) { isDist = false; } dist.add(current & x); was.add(current); } if (isDist) { System.out.println(-1); return; } for (int i = 0; i < n; i++) { if ((arr[i] & x) != arr[i] && was.contains(arr[i] & x)) { System.out.println(1); return; } } System.out.println(2); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
ee641e43b2ff8575dfb24833aef9847b
train_000.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine().trim(), buffer[]; buffer = line.split("\\s+"); int N = Integer.parseInt(buffer[0]); int X = Integer.parseInt(buffer[1]); int nums[] = new int[N]; line = br.readLine().trim(); buffer = line.split("\\s+"); int possible = -1; HashMap<Integer, Integer> set = new HashMap<>(); for (int i = 0; i < N && possible == -1; i++) { nums[i] = Integer.parseInt(buffer[i]); if (set.containsKey(nums[i])) { possible = 0; } set.put(nums[i], 0); } for (int i = 0; i < N && possible != 0; i++) { int val = nums[i] & X; if (val == nums[i]) { continue; } if (set.containsKey(val)) { if (possible == -1) { possible = set.get(val) + 1; } else { possible = Math.min(set.get(val) + 1, possible); } } else { set.put(val, 1); } } System.out.println(possible); } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
09647a7ca7cbb2399f98cf1bc9e29ba5
train_000.jsonl
1565188500
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int q=in.nextInt(); for(int i=0;i<q;i++) { work(); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } long ret=0; long ml,mr,mu,md; boolean v,h; void work() { ml=0; mr=0; mu=0; md=0; v=false; h=false; String s=in.next(); int n=s.length(); int[] p=new int[2]; for(int i=0;i<n;i++) { char c=s.charAt(i); if(c=='W') p[0]--; else if(c=='S') p[0]++; else if(c=='A') p[1]--; else p[1]++; ml=Math.min(p[1], ml); mr=Math.max(p[1], mr); mu=Math.min(p[0], mu); md=Math.max(p[0], md); } dfs(s,0,0,0,0,0,0,0); long ret=(mr-ml+1)*(md-mu+1); if(h&&mr-ml>1) {//至少移一ζ­₯ ret=Math.min(ret,(md-mu+1)*(mr-ml)); } if(v&&md-mu>1) { ret=Math.min(ret,(mr-ml+1)*(md-mu)); } out.println(ret); } private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) { if(index==s.length()) { return new int[] {y,y,x,x}; } char c=s.charAt(index); int nx=x,ny=y; if(c=='W') nx--; else if(c=='S') nx++; else if(c=='A') ny--; else ny++; int nl=Math.min(ny, cl); int nr=Math.max(ny, cr); int nu=Math.min(nx, cu); int nd=Math.max(nx, cd); int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d p[0]=Math.min(ny, p[0]); p[1]=Math.max(ny, p[1]); p[2]=Math.min(nx, p[2]); p[3]=Math.max(nx, p[3]); if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) { h=true; } if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) { v=true; } return p; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3\nDSAWWAW\nD\nWA"]
2 seconds
["8\n2\n4"]
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
Java 8
standard input
[ "dp", "greedy", "math", "implementation", "data structures", "brute force", "strings" ]
a4f183775262fdc42dc5fc621c196ec9
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
2,100
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
standard output
PASSED
6efbdff96920549730888e2f0c0a49a0
train_000.jsonl
1565188500
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.NoSuchElementException; public class P1202C { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int caseNum = scanner.nextInt(); while (caseNum-- > 0) { char[] s = scanner.next().toCharArray(); int n = s.length; int[][] minR = new int[2][n + 1]; int[][] maxR = new int[2][n + 1]; int[][] minC = new int[2][n + 1]; int[][] maxC = new int[2][n + 1]; int[] r = new int[n + 1]; int[] c = new int[n + 1]; for (int i = 1; i <= n; ++i) { r[i] = r[i - 1]; c[i] = c[i - 1]; if (s[i - 1] == 'W') --r[i]; else if (s[i - 1] == 'S') ++r[i]; else if (s[i - 1] == 'A') --c[i]; else //s[i - 1] == 'D' ++c[i]; minR[0][i] = Math.min(minR[0][i - 1], r[i]); maxR[0][i] = Math.max(maxR[0][i - 1], r[i]); minC[0][i] = Math.min(minC[0][i - 1], c[i]); maxC[0][i] = Math.max(maxC[0][i - 1], c[i]); } minR[1][n] = r[n]; maxR[1][n] = r[n]; minC[1][n] = c[n]; maxC[1][n] = c[n]; for (int i = n - 1; i >= 0; --i) { minR[1][i] = Math.min(minR[1][i + 1], r[i]); maxR[1][i] = Math.max(maxR[1][i + 1], r[i]); minC[1][i] = Math.min(minC[1][i + 1], c[i]); maxC[1][i] = Math.max(maxC[1][i + 1], c[i]); } long height = maxR[0][n] - minR[0][n] + 1; long width = maxC[0][n] - minC[0][n] + 1; long ans = height * width; for (int i = 0; i < n; ++i) { ans = Math.min(ans, (Math.max(maxR[0][i], maxR[1][i] - 1) - Math.min(minR[0][i], minR[1][i] - 1) + 1) * width); ans = Math.min(ans, (Math.max(maxR[0][i], maxR[1][i] + 1) - Math.min(minR[0][i], minR[1][i] + 1) + 1) * width); ans = Math.min(ans, (Math.max(maxC[0][i], maxC[1][i] - 1) - Math.min(minC[0][i], minC[1][i] - 1) + 1) * height); ans = Math.min(ans, (Math.max(maxC[0][i], maxC[1][i] + 1) - Math.min(minC[0][i], minC[1][i] + 1) + 1) * height); } writer.println(ans); } writer.close(); } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\nDSAWWAW\nD\nWA"]
2 seconds
["8\n2\n4"]
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
Java 8
standard input
[ "dp", "greedy", "math", "implementation", "data structures", "brute force", "strings" ]
a4f183775262fdc42dc5fc621c196ec9
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
2,100
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
standard output
PASSED
b3bb385857e6cdf73f33dd6e2059b11c
train_000.jsonl
1565188500
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve() { int t=ni(); while(t-->0){ char s[]=ns().toCharArray(); int sz1=0,sz2=0; for(int i=0;i<s.length;i++){ if(s[i]=='A' || s[i]=='D') sz1++; else sz2++; } int a1[]=new int[sz1+1]; int a2[]=new int[sz2+1]; int i1=1,i2=1; for(int i=0;i<s.length;i++){ if(s[i]=='A') a1[i1++]=-1; else if(s[i]=='D') a1[i1++]=1; else if(s[i]=='W') a2[i2++]=1; else a2[i2++]=-1; } int ans1[]=find(a1),ans2[]=find(a2); long ans=Math.min(ans1[0]*1L*ans2[1],ans1[1]*1L*ans2[0]); pw.println(ans); } } int [] find(int a[]){ if(a.length==1) { return new int[]{1,1}; } int mx=0,mn=0; int c[]=new int[a.length]; for(int i=1;i<a.length;i++){ c[i]=c[i-1]+a[i]; mx=Math.max(mx,c[i]); mn=Math.min(mn,c[i]); } int ans[]={mx-mn+1,Integer.MAX_VALUE}; int sufMX[]=new int[a.length+1]; int sufMN[]=new int[a.length+1]; int prefMX[]=new int[a.length]; int prefMN[]=new int[a.length]; for(int i=a.length-1;i>=1;i--){ sufMX[i]=sufMN[i]=c[i]; if(i<a.length-1){ sufMX[i]=Math.max(sufMX[i],sufMX[i+1]); sufMN[i]=Math.min(sufMN[i],sufMN[i+1]); } } for(int i=1;i<a.length;i++){ prefMX[i]=prefMN[i]=c[i]; prefMX[i]=Math.max(prefMX[i],prefMX[i-1]); prefMN[i]=Math.min(prefMN[i],prefMN[i-1]); } for(int i=1;i<a.length;i++){ mx=Math.max(prefMX[i-1],Math.max(c[i-1]+1,sufMX[i]+1)); mn=Math.min(prefMN[i-1],Math.min(c[i-1]+1,sufMN[i]+1)); ans[1]=Math.min(ans[1],mx-mn+1); // pw.println(mx+" "+mn+" "+prefMX[i-1]+" "+sufMX[i-1]); mx=Math.max(prefMX[i-1],Math.max(c[i-1]-1,sufMX[i]-1)); mn=Math.min(prefMN[i-1],Math.min(c[i-1]-1,sufMN[i]-1)); ans[1]=Math.min(ans[1],mx-mn+1); // pw.println(mx+" "+mn); } // pw.println(ans[0]+" "+ans[1]); return ans; } long M = (long) 1e9 + 7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["3\nDSAWWAW\nD\nWA"]
2 seconds
["8\n2\n4"]
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
Java 8
standard input
[ "dp", "greedy", "math", "implementation", "data structures", "brute force", "strings" ]
a4f183775262fdc42dc5fc621c196ec9
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
2,100
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
standard output
PASSED
000eaea7e515a1fb76dc29d78dcb0066
train_000.jsonl
1565188500
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
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 [email protected] */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static final int[][] OFFSETS = new int[][]{ // Offsets for row, column. (0,0) is the top left corner. new int[]{-1, 0}, // W new int[]{+1, 0}, // S new int[]{0, -1}, // A new int[]{0, +1}, // D }; int[] offsetForMove(char c) { switch (c) { case 'W': return OFFSETS[0]; case 'S': return OFFSETS[1]; case 'A': return OFFSETS[2]; case 'D': return OFFSETS[3]; default: throw new AssertionError(); } } char reversePathMove(char c) { switch (c) { case 'W': return 'S'; case 'S': return 'W'; case 'A': return 'D'; case 'D': return 'A'; default: throw new AssertionError(); } } long adaptToReduceArea(TaskC.Box reducedBox, TaskC.Point startingPoint, String path) { if (!reducedBox.contains(startingPoint)) { return Long.MAX_VALUE; } TaskC.Point point = startingPoint; TaskC.Box box = new TaskC.Box(point, point); boolean hasCorrected = false; for (int i = 0; i < path.length(); ++i) { int[] off = offsetForMove(path.charAt(i)); TaskC.Point newPoint = new TaskC.Point(point.r + off[0], point.c + off[1]); if (!hasCorrected && !reducedBox.contains(newPoint)) { hasCorrected = true; // Push an immediate contra-move of this move, so that we stay in the reduced box. // We do this simply by ignoring this move, but we need to update the box to // account for the extra move. int[] contraOff = offsetForMove(reversePathMove(path.charAt(i))); TaskC.Point contraPoint = new TaskC.Point(point.r + contraOff[0], point.c + contraOff[1]); box = box.copyUpdate(contraPoint); } else { point = newPoint; box = box.copyUpdate(point); } } return box.area(); } long calcMinReducedArea(String path) { TaskC.Point startingPoint = new TaskC.Point(0, 0); TaskC.Point point = startingPoint; TaskC.Box box = new TaskC.Box(point, point); for (int i = 0; i < path.length(); ++i) { int[] off = offsetForMove(path.charAt(i)); point = new TaskC.Point(point.r + off[0], point.c + off[1]); box = box.copyUpdate(point); } // System.out.println(box); // System.out.println(box.area()); long minArea = box.area(); TaskC.Box withoutFirstCol = new TaskC.Box(new TaskC.Point(box.tl.r, box.tl.c + 1), box.br); minArea = Math.min(minArea, adaptToReduceArea(withoutFirstCol, startingPoint, path)); TaskC.Box withoutFirstRow = new TaskC.Box(new TaskC.Point(box.tl.r + 1, box.tl.c), box.br); minArea = Math.min(minArea, adaptToReduceArea(withoutFirstRow, startingPoint, path)); TaskC.Box withoutLastRow = new TaskC.Box(box.tl, new TaskC.Point(box.br.r - 1, box.br.c)); minArea = Math.min(minArea, adaptToReduceArea(withoutLastRow, startingPoint, path)); TaskC.Box withoutLastCol = new TaskC.Box(box.tl, new TaskC.Point(box.br.r, box.br.c - 1)); minArea = Math.min(minArea, adaptToReduceArea(withoutLastCol, startingPoint, path)); return minArea; } public void solve(int testNumber, InputReader in, PrintWriter out) { int tests = in.readInt(); for (int test = 0; test < tests; ++test) { String path = in.readString(); out.println(calcMinReducedArea(path)); } } static class Point { final int r; final int c; Point(int r, int c) { this.r = r; this.c = c; } public String toString() { return String.format("(%d,%d)", r, c); } } static class Box { final TaskC.Point tl; final TaskC.Point br; Box(TaskC.Point tl, TaskC.Point br) { this.tl = tl; this.br = br; } long area() { return ((long) br.r - tl.r + 1) * (br.c - tl.c + 1); } boolean contains(TaskC.Point point) { return tl.r <= point.r && point.r <= br.r && tl.c <= point.c && point.c <= br.c; } TaskC.Box copyUpdate(TaskC.Point point) { return new TaskC.Box( new TaskC.Point(Math.min(tl.r, point.r), Math.min(tl.c, point.c)), new TaskC.Point(Math.max(br.r, point.r), Math.max(br.c, point.c))); } public String toString() { return String.format("%s-%s", tl, br); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\nDSAWWAW\nD\nWA"]
2 seconds
["8\n2\n4"]
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
Java 8
standard input
[ "dp", "greedy", "math", "implementation", "data structures", "brute force", "strings" ]
a4f183775262fdc42dc5fc621c196ec9
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
2,100
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
standard output
PASSED
ed8539bf1bcc4e1d9c5c95992b3c52f5
train_000.jsonl
1565188500
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
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 [email protected] */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static final int[][] OFFSETS = new int[][]{ // Offsets for row, column. (0,0) is the top left corner. new int[]{-1, 0}, // W new int[]{+1, 0}, // S new int[]{0, -1}, // A new int[]{0, +1}, // D }; int[] offsetForMove(char c) { switch (c) { case 'W': return OFFSETS[0]; case 'S': return OFFSETS[1]; case 'A': return OFFSETS[2]; case 'D': return OFFSETS[3]; default: throw new AssertionError(); } } char reversePathMove(char c) { switch (c) { case 'W': return 'S'; case 'S': return 'W'; case 'A': return 'D'; case 'D': return 'A'; default: throw new AssertionError(); } } String reversePath(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); for (int i = 0; i < sb.length(); ++i) { sb.setCharAt(i, reversePathMove(sb.charAt(i))); } return sb.toString(); } long tryToAdaptToFit(TaskC.Box reducedBox, TaskC.Point startingPoint, String path) { TaskC.Point point = startingPoint; TaskC.Box box = new TaskC.Box(point, point); if (!reducedBox.contains(point)) { return -1; } boolean hasCorrected = false; for (int i = 0; i < path.length(); ++i) { int[] off = offsetForMove(path.charAt(i)); TaskC.Point newPoint = new TaskC.Point(point.r + off[0], point.c + off[1]); if (!hasCorrected && !reducedBox.contains(newPoint)) { hasCorrected = true; // Push an immediate contra-move of this move, so that we stay in the reduced box. // We do this simply by ignoring this move, but we need to update the box to // account for the extra move. int[] contraOff = offsetForMove(reversePathMove(path.charAt(i))); TaskC.Point contraPoint = new TaskC.Point(point.r + contraOff[0], point.c + contraOff[1]); box = TaskC.Box.copyUpdate(box, contraPoint); } else { point = newPoint; box = TaskC.Box.copyUpdate(box, point); } } return box.area(); } long calcMinReducedArea(String path) { // boxFromMove[0] - the bounding box of the whole path, including the point before // following any move. // boxFromMove[i] - the bounding box from the (i-1)th move on, with the (i-1)th move // already done. TaskC.Box[] boxFromMove = new TaskC.Box[path.length() + 1]; String reversedPath = reversePath(path); TaskC.Point point = new TaskC.Point(0, 0); TaskC.Box box = new TaskC.Box(point, point); boxFromMove[path.length()] = box; for (int i = 0; i < reversedPath.length(); ++i) { int[] off = offsetForMove(reversedPath.charAt(i)); point = new TaskC.Point(point.r + off[0], point.c + off[1]); box = TaskC.Box.copyUpdate(box, point); boxFromMove[path.length() - 1 - i] = box; } // System.out.println(box); // System.out.println(box.area()); TaskC.Box wholeBox = box; TaskC.Point startingPoint = point; long minArea = wholeBox.area(); { TaskC.Box withoutFirstCol = new TaskC.Box(new TaskC.Point(wholeBox.tl.r, wholeBox.tl.c + 1), wholeBox.br); long area = tryToAdaptToFit(withoutFirstCol, startingPoint, path); // System.out.println("area=" + area); if (area != -1) { minArea = Math.min(minArea, area); } } { TaskC.Box withoutFirstRow = new TaskC.Box(new TaskC.Point(wholeBox.tl.r + 1, wholeBox.tl.c), wholeBox.br); long area = tryToAdaptToFit(withoutFirstRow, startingPoint, path); if (area != -1) { minArea = Math.min(minArea, area); } } { TaskC.Box withoutLastRow = new TaskC.Box(wholeBox.tl, new TaskC.Point(wholeBox.br.r - 1, wholeBox.br.c)); long area = tryToAdaptToFit(withoutLastRow, startingPoint, path); if (area != -1) { minArea = Math.min(minArea, area); } } { TaskC.Box withoutLastCol = new TaskC.Box(wholeBox.tl, new TaskC.Point(wholeBox.br.r, wholeBox.br.c - 1)); long area = tryToAdaptToFit(withoutLastCol, startingPoint, path); if (area != -1) { minArea = Math.min(minArea, area); } } return minArea; } public void solve(int testNumber, InputReader in, PrintWriter out) { int tests = in.readInt(); for (int test = 0; test < tests; ++test) { String path = in.readString(); out.println(calcMinReducedArea(path)); } } static class Point { final int r; final int c; Point(int r, int c) { this.r = r; this.c = c; } public String toString() { return String.format("(%d,%d)", r, c); } } static class Box { final TaskC.Point tl; final TaskC.Point br; Box(TaskC.Point tl, TaskC.Point br) { this.tl = tl; this.br = br; } long area() { return ((long) br.r - tl.r + 1) * (br.c - tl.c + 1); } public String toString() { return String.format("%s-%s", tl, br); } boolean contains(TaskC.Point point) { return tl.r <= point.r && point.r <= br.r && tl.c <= point.c && point.c <= br.c; } static TaskC.Box copyUpdate(TaskC.Box existing, TaskC.Point point) { return new TaskC.Box( new TaskC.Point(Math.min(existing.tl.r, point.r), Math.min(existing.tl.c, point.c)), new TaskC.Point(Math.max(existing.br.r, point.r), Math.max(existing.br.c, point.c))); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\nDSAWWAW\nD\nWA"]
2 seconds
["8\n2\n4"]
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
Java 8
standard input
[ "dp", "greedy", "math", "implementation", "data structures", "brute force", "strings" ]
a4f183775262fdc42dc5fc621c196ec9
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
2,100
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
standard output
PASSED
c7d29130a691a4de39244c20a04b38e0
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t-->0) { int n =scan.nextInt(); String str= scan.next(); System.out.println(count(str,'a')); } scan.close(); } public static int count(String s, char c) { if(s.length()==1) { if(s.charAt(0)==c) return 0; else return 1; } int mid = s.length()/2; int lc = count(s.substring(0,mid),(char)(c+1)); lc+=mid-countChar(s.substring(mid,s.length()), c); int rc = count(s.substring(mid,s.length()),(char)(c+1)); rc+=mid-countChar(s.substring(0,mid), c); return Math.min(lc, rc); } public static int countChar(String s, char c) { int ans=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)==c) ans++; } return ans; } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
87ca6cc994feeb7a15aac0064f7dd353
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; public class Main { final static int maxn = 1000; static Scanner reader = new Scanner(System.in); static int n; static int val[][]; static int lens[]; static String s; static int cnt_dp(int let, int pos) { if(lens[let] == 1) return Math.min(val[let][pos] + (s.charAt(pos + 1) != ('a' + let + 1) ? 1 : 0), val[let][pos + 1] + (s.charAt(pos) != ('a' + let + 1) ? 1 : 0)); return Math.min(val[let][pos] + cnt_dp(let + 1, pos + lens[let]), val[let][pos + lens[let]] + cnt_dp(let + 1, pos)); } static void solve() { n = reader.nextInt(); s = reader.next(); if(n == 1) { System.out.println(s.equals("a") ? 0 : 1); return; } val = new int[20][n]; for(int i = 0; i < 20; i++) { for(int j = 0; j < n; j++) { val[i][j] = -1; } } int len = n; lens = new int[20]; for(int i = 0; i < 20; i++) { len /= 2; if(len == 0) break; lens[i] = len; for(int pos = 0; pos < n; pos += len) { int cur = 0; for(int j = 0; j < len; j++) { if(s.charAt(pos + j) != ('a' + i)) { cur++; } } val[i][pos] = cur; } } System.out.println(cnt_dp(0, 0)); } public static void main(String[] args) { int q = reader.nextInt(); for(int i = 0; i < q; i++) solve(); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
da4804696e78c86639fb61267657267d
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * @author Tran Anh Tai * @template for CP codes */ public class ProbD { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); for(int i = 0; i < t; i++){ int n = in.nextInt(); String s = in.nextToken(); int[][] cnt = new int[n + 1][26]; for(int j = 1; j <= n; j++){ for (int c = 0; c < 26; c++){ cnt[j][c] = cnt[j - 1][c]; } cnt[j][s.charAt(j - 1) - 'a']++; } int dp[][] = new int[n + 1][18]; int k = (int)(Math.log(n) / Math.log(2)); for (int j = 1; j <= n; j++){ dp[j][0] = (s.charAt(j - 1) - 'a' == k) ? 0 : 1; } assert (n == (1 << k)); for (int c = 1; c <= k; c++){ for (int j = 1; j <= n; j++){ if (j + (1 << c) - 1 <= n){ dp[j][c] = Math.min(dp[j][c - 1] + (1 << (c - 1)) - (cnt[j + (1 << c) - 1][k - c] - cnt[j + (1 << (c - 1)) - 1][k - c]), dp[j + (1 << (c - 1))][c - 1] + (1 << (c - 1)) - (cnt[j + (1 << (c - 1)) - 1][k - c] - cnt[j - 1][k - c])); } } } out.println(dp[1][k]); } } } public static class Segment implements Comparable<Segment>{ public int l, r; public Segment(int l, int r){ this.l = l; this.r = r; } @Override public int compareTo(Segment o) { if (o.r != this.r){ return Integer.compare(this.r, o.r); } return Integer.compare(this.l, o.l); } public static boolean isIntersect(Segment s1, Segment s2){ if (s1.l > s2.r || s2.l > s1.r){ return false; } return true; } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
1445e65ba737c234fa280472a3a47664
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main implements Runnable { class Pair implements Comparable<Pair>{ public int node; public int count; Pair(int nd, int c){ node=nd; count=c; } public int compareTo(Pair that) { return that.count - this.count; } } int getMin(int a[], int start, int end, int val){ if(start==end){ if(a[start]==val) return 0; else return 1; } int mid= (start+end)/2; int count1=0; for(int i=start;i<=mid;i++){ if(a[i]!=val) count1++; } int m1= count1+getMin(a,mid+1,end,val+1); int count2=0; for(int i=mid+1;i<=end;i++){ if(a[i]!=val) count2++; } int m2= count2+getMin(a,start,mid,val+1); return Math.min(m1, m2); } public void solve() throws Exception { int t=iread(); for(int cases=1;cases<=t;cases++){ int n= iread(); String s= readword(); int a[]= new int[n+1]; for(int i=0;i<n;i++) a[i]= (int)s.charAt(i); int result= getMin(a,0,n-1,(int)'a'); System.out.println(result); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
764fcf3268aadb87855b0407883e3575
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Q417July { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t!=0){ t--; int n = sc.nextInt(); String s = sc.next(); // System.out.println(strings); System.out.println(findMin(s,0,n-1,'a')); } } private static int findMin(String s, int l, int r, char ch){ if(l>=r){ if(s.charAt(l)!=ch){ return 1; } return 0; } int mid = (l+r)/2; int left =0; int right =0; for(int i=l;i<=mid;i++){ if(s.charAt(i)!=ch){ left++; } } for(int i=mid+1;i<=r;i++){ if(s.charAt(i)!=ch){ right++; } } ch = (char)(ch+1); return Math.min(left+ findMin(s,mid+1,r,ch), right+ findMin(s,l,mid,ch)); } private static int findCount(String s, String match){ int count=0; for(int i =0;i<s.length();i++){ if(s.charAt(i)!= match.charAt(i)){ count++; } } return count; } private static List<String> fillStrings(int length, char initial){ if(length == 1){ return new ArrayList<>( Collections.singletonList((Character.toString(initial)))); } List<String> s1 = fillStrings(length/2, (char)(initial+1)); List<String> s2 = fillStrings(length/2,(char)(initial+1)); return appendBeforeAfter(s1,s2,initial, length/2); } private static List<String> appendBeforeAfter(List<String> appendBeforeList, List<String> appendAfterString, char appendWith, int length){ String repeatedInitials = repeatedInitials(appendWith,length); List<String> newBefore = new ArrayList<>(); List<String> newAfter = new ArrayList<>(); for (String s : appendBeforeList) { s= repeatedInitials+s; newBefore.add(s); } for (String s : appendAfterString) { s+=repeatedInitials; newAfter.add(s); } newBefore.addAll(newAfter); return newBefore; } private static String repeatedInitials(char initials, int length){ String s = ""; for(int i =0;i<length;i++) { s+=(initials); } return s; } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
3a461460176264565e45e74389ad8e09
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class scratch_25 { static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } public static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public static int numEdg(){ int count=0; ArrayList<Integer> vrtc= new ArrayList<>(vt.keySet()); for (int i = 0; i <vrtc.size() ; i++) { count+=(vt.get(vrtc.get(i))).nb.size(); } return count/2; } public static boolean contEdg(int ver1, int ver2){ if(vt.get(ver1)==null || vt.get(ver2)==null){ return false; } Vertex v= vt.get(ver1); if(v.nb.containsKey(ver2)){ return true; } return false; } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } public class Pair{ int vname; ArrayList<Integer> psf= new ArrayList<>(); // path so far int dis; int col; } public HashMap<Integer,Integer> bfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; queue.addLast(strtp); while(!queue.isEmpty()){ Pair rp = queue.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; queue.addLast(np); } } } return ans; // return false; } public HashMap<Integer,Integer> dfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> stack= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; stack.addFirst(strtp); while(!stack.isEmpty()){ Pair rp = stack.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; stack.addFirst(np); } } } return ans; // return false; } public boolean isCycle(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ continue; } Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ return true; } prcd.put(rp.vname,true); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); Pair np= new Pair(); np.vname= u; queue.addLast(np); } } } return false; } public ArrayList<ArrayList<Integer>> genConnctdComp(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye ArrayList<ArrayList<Integer>> ans= new ArrayList<>(); // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue // int con=-1; ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ //return true; continue; } ArrayList<Integer> fu= new ArrayList<>(); fu.add(cur); Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ //return true; continue; } prcd.put(rp.vname,true); fu.add(cur); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); Pair np= new Pair(); np.vname= u; queue.addLast(np); } } ans.add(fu); } //return false; return ans; } public boolean isBip(int src){ // only for connected graph HashMap<Integer,Integer> clr= new HashMap<>(); // colors are 1 and -1 LinkedList<Integer>q = new LinkedList<Integer>(); clr.put(src,1); q.add(src); while(!q.isEmpty()){ int u = q.getFirst(); q.pop(); ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; ++i) { int x= arr.get(i); if(vt.get(u).nb.containsKey(x) && !clr.containsKey(x)){ if(clr.get(u)==1){ clr.put(x,-1); } else{ clr.put(x,1); } q.push(x); } else if(vt.get(u).nb.containsKey(x) && (clr.get(x)==clr.get(u))){ return false; } } } return true; } public static void printGr() { ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; i++) { int ver= arr.get(i); Vertex v1= vt.get(ver); ArrayList<Integer> arr1= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <arr1.size() ; j++) { System.out.println(ver+"-"+arr1.get(j)+":"+v1.nb.get(arr1.get(j))); } } } } public static void main(String[] args) throws IOException { Reader.init(System.in); int t = Reader.nextInt(); for (int j = 0; j < t; j++) { int n= Reader.nextInt(); char arr[]= Reader.next().toCharArray(); int x= good(arr,n,97); System.out.println(x); } } public static int good(char arr[],int n, int ac){ if(n==1){ if((int)arr[0]==ac){ return 0; } else{ return 1; } } int mid= arr.length/2; int count=0; int count1=0; for (int i = 0; i <mid ; i++) { char c= arr[i]; int num= (int)c; if(num!=ac){ count++; } } for (int i = mid; i <arr.length ; i++) { char c= arr[i]; int num= (int)c; if(num!=ac){ count1++; } } return Math.min( count1+good(Arrays.copyOfRange(arr,0,mid),n/2,ac+1),count+good(Arrays.copyOfRange(arr,mid,n),n/2,ac+1)); } public static ArrayList<Integer> Sieve(int n) { boolean arr[]= new boolean [n+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for (int i = 2; i*i <=n ; i++) { if(arr[i]==true){ for (int j = 2; j <=n/i ; j++) { int u= i*j; arr[u]=false; }} } ArrayList<Integer> ans= new ArrayList<>(); for (int i = 0; i <n+1 ; i++) { if(arr[i]){ ans.add(i); } } return ans; } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
c167887adf104d6e2a2cad8c3b6eb1bc
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); String str=sc.next(); int res=Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(res>(str.charAt(i)+0)) res=str.charAt(i)+0; } int k=rec(str,0,n-1,'a'); System.out.println(k); } } public static int rec( String str,int s,int e,char c) { if(s==e) { if(str.charAt(s)!=c) return 1; return 0; } if(s>e) { return 0; } int count1=0; int count2=0; for(int i=s;i<s+(e-s+1)/2;i++ ) { if(str.charAt(i)!=c) count1++; } for(int i=s+(e-s+1)/2;i<=e;i++) { if(str.charAt(i)!=c) count2++; } return Math.min( (count1+rec(str,s+(e-s+1)/2,e,(char)(c+1))), (count2+rec(str,s,s+((e-s+1)/2)-1,(char)(c+1)))); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
04c3773e3e4c3943e7a3985269f7b6d4
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int ntests = in.nextInt(); for (int itest = 0; itest < ntests; itest++) { int len = in.nextInt(); char[] s = in.nextLine(len).toCharArray(); int ans = rec(s, 0, s.length - 1, 'a'); out.println(ans); } } private int rec(char[] s, int le, int ri, char c) { if (le == ri) { return s[le] == c ? 0 : 1; } int mid = le + (ri - le) / 2; //1 int ans1 = 0; for (int i = le; i <= mid; i++) { if (s[i] != c) { ans1++; } } ans1 += rec(s, mid + 1, ri, (char) (c + 1)); //2 int ans2 = 0; for (int i = mid + 1; i <= ri; i++) { if (s[i] != c) { ans2++; } } ans2 += rec(s, le, mid, (char) (c + 1)); return Math.min(ans1, ans2); } } static class InputReader { final InputStream is; final byte[] buffer = new byte[1024]; int curCharIdx; int nChars; public InputReader(InputStream is) { this.is = is; } public int read() { if (curCharIdx >= nChars) { try { curCharIdx = 0; nChars = is.read(buffer); if (nChars == -1) { return -1; } } catch (IOException e) { throw new RuntimeException(e); } } return buffer[curCharIdx++]; } public int nextInt() { int sign = 1; int c = skipDelims(); if (c == '-') { sign = -1; c = read(); if (isDelim(c)) { throw new RuntimeException("Incorrect format"); } } int val = 0; while (c != -1 && !isDelim(c)) { if (!isDigit(c)) { throw new RuntimeException("Incorrect format"); } val = 10 * val + (c - '0'); c = read(); } return val * sign; } public String nextLine(int size) { int c = read(); while (c == '\n' || c == '\t' || c == '\r') { c = read(); } if (c == -1) { return null; } StringBuilder sb = new StringBuilder(size); while (c != -1 && c != '\n' && c != '\t' && c != '\r') { sb.appendCodePoint(c); c = read(); } return sb.toString(); } private final int skipDelims() { int c = read(); while (isDelim(c)) { c = read(); } return c; } private static boolean isDelim(final int c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\f'; } private static boolean isDigit(final int c) { return '0' <= c && c <= '9'; } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
14801bf036363719f726e9e2552b30e1
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int ntests = in.nextInt(); for (int itest = 0; itest < ntests; itest++) { int len = in.nextInt(); char[] s = in.nextLine().toCharArray(); int ans = rec(s, 0, s.length - 1, 'a'); out.println(ans); } } private int rec(char[] s, int le, int ri, char c) { if (le == ri) { return s[le] == c ? 0 : 1; } int mid = le + (ri - le) / 2; //1 int ans1 = 0; for (int i = le; i <= mid; i++) { if (s[i] != c) { ans1++; } } ans1 += rec(s, mid + 1, ri, (char) (c + 1)); //2 int ans2 = 0; for (int i = mid + 1; i <= ri; i++) { if (s[i] != c) { ans2++; } } ans2 += rec(s, le, mid, (char) (c + 1)); return Math.min(ans1, ans2); } } static class InputReader { final InputStream is; final byte[] buffer = new byte[1024]; int curCharIdx; int nChars; public InputReader(InputStream is) { this.is = is; } public int read() { if (curCharIdx >= nChars) { try { curCharIdx = 0; nChars = is.read(buffer); if (nChars == -1) { return -1; } } catch (IOException e) { throw new RuntimeException(e); } } return buffer[curCharIdx++]; } public int nextInt() { int sign = 1; int c = skipDelims(); if (c == '-') { sign = -1; c = read(); if (isDelim(c)) { throw new RuntimeException("Incorrect format"); } } int val = 0; while (c != -1 && !isDelim(c)) { if (!isDigit(c)) { throw new RuntimeException("Incorrect format"); } val = 10 * val + (c - '0'); c = read(); } return val * sign; } public String nextLine() { return nextLine(16); } public String nextLine(int size) { int c = read(); while (c == '\n' || c == '\t' || c == '\r') { c = read(); } if (c == -1) { return null; } StringBuilder sb = new StringBuilder(size); while (c != -1 && c != '\n' && c != '\t' && c != '\r') { sb.appendCodePoint(c); c = read(); } return sb.toString(); } private final int skipDelims() { int c = read(); while (isDelim(c)) { c = read(); } return c; } private static boolean isDelim(final int c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\f'; } private static boolean isDigit(final int c) { return '0' <= c && c <= '9'; } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
500c3971f4e33585d02d88ee3f193eff
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.Scanner; public class D{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); // input.nextLine(); while(t-- != 0){ int n = input.nextInt(); input.nextLine(); String s = input.nextLine(); System.out.println(solve(s, 'a', 0)); answer = Integer.MAX_VALUE; } } public static int answer = Integer.MAX_VALUE; public static int solve(String s, char ch, int ans){ if(ans > answer){ return answer; } int half = s.length()/2; int frst = 0; int scnd = 0; if(s.length() == 1){ if(s.charAt(0) == ch){ answer = Math.min(answer, ans); return ans; } ans += 1; answer = Math.min(answer, ans); return ans; } for(int i = 0; i < half; i++){ if(s.charAt(i) == ch){ frst++; } if(s.charAt(half+i) == ch){ scnd++; } } int ans1 = ans+half-frst; int ans2 = ans+half-scnd; ch++; return Math.min(solve(s.substring(half), ch, ans1), solve(s.substring(0, half), ch, ans2)); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
02920d500c608bcdb9b7a3f89e2c91fd
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.util.*; public class codeforces { public static void main(String[] args) { InputReader sc = new InputReader(System.in); int T=sc.nextInt(); for (int t = 0; t < T; t++) { int n=sc.nextInt(); String str=sc.nextLine(); out.println(recur('a',str)); } out.close(); } public static int recur(char ch,String str) { int s=0; int e=str.length(); if (s==e-1) { return str.charAt(s)==ch?0:1; } int ryt=recur((char)(ch+1),str.substring(e/2,e)); int lft=recur((char)(ch+1),str.substring(s,e/2)); for (int i = e/2; i < e; i++) { if (str.charAt(i)!=ch) lft++; } for (int i = 0; i < e/2; i++) { if (str.charAt(i)!=ch) ryt++; } // System.out.println(lft+" "+ryt+" "+ch+" "+" "+str+" "+" "); return Math.min(lft,ryt); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public double nextDouble() { return (Double.parseDouble(readString())); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static private PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static int mod = 1000000000 + 7; }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
2a1d7bdc50bfdce77300e4afbdc25284
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class Solution1385D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver1385D solver = new Solver1385D(); int n = in.nextInt(); for (int i = 0; i < n; i++) { solver.solve(i, in, out); } out.close(); } static class Solver1385D { public void solve(int testNumber, InputReader in, PrintWriter out) { int len = in.nextInt(); String s = in.next(); Map<Integer, Map<Integer, Map<Character, Integer>>> cache = new HashMap<>(); Map<Integer, Map<Integer, Map<Character, Integer>>> diffCache = new HashMap<>(); Set<Character> chars = new HashSet<>(); out.println(minChange(s, 0, len, 'a', cache, diffCache)); } private int minChange(String s, int start, int len, char c, Map<Integer, Map<Integer, Map<Character, Integer>>> cache, Map<Integer, Map<Integer, Map<Character, Integer>>> diffCache) { if (len == 1) { if (s.charAt(start) == c) { return 0; } return 1; } if (cache.containsKey(start) && cache.get(start).containsKey(len) && cache.get(start).get(len).containsKey(c)) { return cache.get(start).get(len).get(c); } if (!cache.containsKey(start)) { cache.put(start, new HashMap<>()); } Map<Integer, Map<Character, Integer>> startMap = cache.get(start); Map<Character, Integer> charMap = startMap.get(len); if (charMap == null) { charMap = new HashMap<>(); startMap.put(len, charMap); } int result = charDiff(s, start, len / 2, c, diffCache) + minChange(s, start + len / 2, len / 2, (char)(c+1), cache, diffCache); int tmp = charDiff(s, start + len / 2, len / 2, c, diffCache); if (tmp < result) { result = Math.min(result, tmp + minChange(s, start, len / 2, (char)(c+1), cache, diffCache)); } charMap.put(c, result); return result; } private int charDiff(String s, int start, int len, char c, Map<Integer, Map<Integer, Map<Character, Integer>>> cache) { if (cache.containsKey(start) && cache.get(start).containsKey(len) && cache.get(start).get(len).containsKey(c)) { return cache.get(start).get(len).get(c); } if (!cache.containsKey(start)) { cache.put(start, new HashMap<>()); } Map<Integer, Map<Character, Integer>> startMap = cache.get(start); Map<Character, Integer> charMap = startMap.get(len); if (charMap == null) { charMap = new HashMap<>(); startMap.put(len, charMap); } int result = 0; for (int i = start; i < start + len; i++) { if (s.charAt(i) != c) { result++; } } charMap.put(c, result); return result; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
96b87af808c0547e2b345d283cc0ac3b
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class Solution1385D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver1385D solver = new Solver1385D(); int n = in.nextInt(); for (int i = 0; i < n; i++) { solver.solve(i, in, out); } out.close(); } static class Solver1385D { public void solve(int testNumber, InputReader in, PrintWriter out) { int len = in.nextInt(); String s = in.next(); Map<Integer, Map<Integer, Map<Character, Integer>>> cache = new HashMap<>(); Map<Integer, Map<Integer, Map<Character, Integer>>> diffCache = new HashMap<>(); Set<Character> chars = new HashSet<>(); out.println(minChange(s, 0, len, 'a', cache, diffCache)); } private int minChange(String s, int start, int len, char c, Map<Integer, Map<Integer, Map<Character, Integer>>> cache, Map<Integer, Map<Integer, Map<Character, Integer>>> diffCache) { if (len == 1) { if (s.charAt(start) == c) { return 0; } return 1; } if (cache.containsKey(start) && cache.get(start).containsKey(len) && cache.get(start).get(len).containsKey(c)) { return cache.get(start).get(len).get(c); } if (!cache.containsKey(start)) { cache.put(start, new HashMap<>()); } Map<Integer, Map<Character, Integer>> startMap = cache.get(start); Map<Character, Integer> charMap = startMap.get(len); if (charMap == null) { charMap = new HashMap<>(); startMap.put(len, charMap); } int result = charDiff(s, start, len / 2, c, diffCache) + minChange(s, start + len / 2, len / 2, (char)(c+1), cache, diffCache); int tmp = charDiff(s, start + len / 2, len / 2, c, diffCache); if (tmp < result) { result = Math.min(result, tmp + minChange(s, start, len / 2, (char)(c+1), cache, diffCache)); } charMap.put(c, result); return result; } private int charDiff(String s, int start, int len, char c, Map<Integer, Map<Integer, Map<Character, Integer>>> cache) { if (cache.containsKey(start) && cache.get(start).containsKey(len) && cache.get(start).get(len).containsKey(c)) { return cache.get(start).get(len).get(c); } if (!cache.containsKey(start)) { cache.put(start, new HashMap<>()); } Map<Integer, Map<Character, Integer>> startMap = cache.get(start); Map<Character, Integer> charMap = startMap.get(len); if (charMap == null) { charMap = new HashMap<>(); startMap.put(len, charMap); } int result = 0; for (int i = start; i < start + len; i++) { if (s.charAt(i) != c) { result++; } } charMap.put(c, result); return result; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 262144); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
3f5e76206e16e5a0b5f19ed7b0109b5b
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.Scanner; public class CF_Round_656_Div3_ProblemD_ { public static void main(String[] args) { process(); } public static void process() { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for(int i = 0; i < t; ++i) { int n = scanner.nextInt(); String str = scanner.next(); int ret = solve(str); System.out.println(ret); } } public static int solve(String str) { return solve(str.toCharArray(), 0, str.length()-1, 'a'); } public static int solve(char[] arr, int from, int to, char target) { if(from == to) { if(arr[from] == target) { return 0; } else { return 1; } } else { char next = (char)(target+1); int mid = (from + to)/2; int leftCount = 0; for(int i = from; i <= mid; ++i) { if(arr[i] != target) { leftCount++; } } int rightCount = 0; for(int i = mid+1; i <= to; ++i) { if(arr[i] != target) { rightCount++; } } int left = leftCount + solve(arr, mid + 1, to, next); int right = solve(arr, from, mid, next) + rightCount; return Math.min(left, right); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
b024ad5caaf47473bcc2c89a2567cd0f
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class D { // C-good String으둜 λ§Œλ“œλŠ”λ° ν•„μš”ν•œ μ΅œμ†Œ λŒ€μ²΄ 수 λ°˜ν™˜ static int aGood(String S, char C) { if (S.length() == 1) {return S.charAt(0) != C ? 1 : 0;} int mid = S.length() / 2; // 1번 쑰건 λ§Œμ‘±μ‹œν‚€κΈ° int cand1 = 0; String preFix = S.substring(0, mid); for (int i = 0; i < preFix.length(); i++) if (preFix.charAt(i) != C) cand1++; cand1 += aGood(S.substring(mid), (char)(C + 1)); // 2번 쑰건 λ§Œμ‘±μ‹œν‚€κΈ° int cand2 = 0; preFix = S.substring(mid); for (int i = 0; i < preFix.length(); i++) if (preFix.charAt(i) != C) cand2++; cand2 += aGood(S.substring(0, mid), (char)(C + 1)); return Math.min(cand1, cand2); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(br.readLine()); for (int c = 0; c < T; c++) { br.readLine(); String S = br.readLine(); bw.write(String.valueOf(aGood(S, 'a'))); bw.newLine(); } bw.close(); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
7dce0099bf462b7061f9ce541b101755
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public final class CodeForces { static int ans; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()); String s = br.readLine(); ans = Integer.MAX_VALUE; if(n > 1) { solve(s, 'a', 0); System.out.println(ans); } else { System.out.println(s.charAt(0) == 'a' ? 0 : 1); } } br.close(); } private static void solve(String s, char c, int val) { int count1 = 0, count2 = 0; if(s.length() == 1) { if(s.charAt(0) == c) { ans = Math.min(ans, val); } else { ans = Math.min(ans, val+1); } return; } String s1 = s.substring(0, s.length()/2); String s2 = s.substring(s.length()/2); for(int i=0; i<s1.length(); i++) { if(s1.charAt(i) == c) count1++; if(s2.charAt(i) == c) count2++; } char next = (char) (c + 1); solve(s2, next, val + s1.length() - count1); solve(s1, next, val + s2.length() - count2); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
8e066b4408a10d6f05a736686c4ac06c
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import com.sun.org.apache.xpath.internal.SourceTree; import com.sun.org.apache.xpath.internal.functions.FuncFalse; import javafx.util.Pair; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Contest { public static class pair implements Comparable<pair> { long l; long r; public pair(long lef, long ri) { l = lef; r = ri; } @Override public int compareTo(pair p) { if (l == p.l) return Long.compare(r, p.r); return Long.compare(l, p.l); } } static int n, m; static ArrayList<Integer>[] adj; static int dist[]; static int parent[]; static long inf = (long) 1e18; static int INF = (int) 1e9; public static boolean isSimilar(char[] Arr, int s, int k) { for (int i = s; i < k - 1; i++) { if (Arr[i + 1] != Arr[i]) return false; } return true; } public static int ciel(int d, int mod) { if (d % mod == 0) return d / mod; return (d / mod) + 1; } public static long gcd(long u, long v) { if (v == 0) return u; return gcd(v, u % v); } static int k, Arr[], lefAcc[], riAcc[]; static PrintWriter pw; static long memo[][]; static char[][] Matrix; static int[] dx = new int[]{-1, 1, 0, 0}; static int[] dy = new int[]{0, 0, -1, 1}; static boolean valid(int i, int j) { return i != -1 && j != -1 && i != n && j != m; } static boolean[][] vis = new boolean[n][m]; static void dfs2(int i, int j) { vis[i][j] = true; //mark as visited for (int k = 0; k < 4; ++k) { int x = i + dx[k], y = j + dy[k]; if (valid(x, y) && Matrix[x][y] != '#' && !vis[x][y]) dfs2(x, y); } } public static int getnum(int[][] matrix, int i, int j) { int c = 0; for (int k = 0; k < 4; ++k) { int x = i + dx[k], y = j + dy[k]; if (valid(x, y)) c++; } return c; } static String str; public static int howManyChar(char c, int lo, int hi) { int cnt = 0; for (int i = lo; i <= hi; i++) { if (str.charAt(i) == c) cnt++; } return (hi - lo + 1) - cnt; } public static long divCon(int lo, int hi, char c) { if (lo == hi) return c == str.charAt(lo) ? 0 : 1; int mid = (lo + hi) >> 1; char next= (char) (c+1); return min(howManyChar(c, lo, mid) + divCon(mid + 1, hi, next), howManyChar(c, mid + 1, hi) + divCon(lo, mid, next)); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); str=sc.next(); pw.println(divCon(0, n-1, 'a')); } pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException, IOException { return br.ready(); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
43ebf485014dd60a741371166e824d3d
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
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 Pranay2516 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskD { char[] s; public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); s = in.next().toCharArray(); out.println(calc('a', 0, n - 1)); } int calc(char c, int l, int r) { if (l == r) return s[l] == c ? 0 : 1; int lcnt = 0, rcnt = 0, mid = (l + r + 1) / 2; for (int i = l; i < mid; i++) if (s[i] != c) lcnt++; for (int i = mid; i <= r; ++i) if (s[i] != c) rcnt++; c++; return Math.min(lcnt + calc(c, mid, r), rcnt + calc(c, l, mid - 1)); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
a1a8e0811f73caa5e74381e2fb044130
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; public class AGoodString656D{ static class FastReader { BufferedReader br; StringTokenizer st; private 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()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayOne(int n) { int[] a = new int[n+1]; for (int i = 1; i < n+1; i++) a[i] = nextInt(); return a; } 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 s =new FastReader(); int t = s.nextInt(); StringBuilder str = new StringBuilder(); while(t-- >0) { int n = s.nextInt(); String arr = s.nextLine(); int len = (int)(Math.log(n) / Math.log(2)); int freq[][] = new int[n][26]; fillFreq(arr,n,freq); int ans = func(arr,1,len,'a',freq); str.append(ans+"\n"); } System.out.println(str); } private static void fillFreq(String arr, int n, int[][] freq) { for(char c = 'a' ;c <= 'z';c++) { if(arr.charAt(0) == c) { freq[0][c - 'a'] = 1; }else { freq[0][c - 'a'] = 0; } } for(int i = 1;i<n;i++) { for(char c = 'a' ;c <= 'z';c++) { if(arr.charAt(i) == c) { freq[i][c - 'a'] = 1 + freq[i - 1][c - 'a']; }else { freq[i][c - 'a'] = freq[i - 1][c - 'a']; } } } } private static int func(String arr, int i, int len, char c, int[][] freq) { if(len == 0) { return c != arr.charAt(i - 1) ? 1 : 0; } int left = (1 << len - 1) - getCount(i,len - 1,c,freq); int right = (1 << len - 1) - getCount(i + (1 << (len - 1)) , len - 1, c,freq); return Math.min(left + func(arr,i + (1 << (len - 1)), len - 1, (char)(c + 1), freq), right + func(arr,i , len - 1, (char)(c + 1), freq)); } private static int getCount(int i, int len, char c, int[][] freq) { int j = i + (1 << len) - 1; return freq[j - 1][c - 'a'] - ((i - 1) == 0 ? 0 : freq[i - 2][c - 'a']); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
63e8ae36bf1cd81a3d938e9cec54bafe
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.Objects; import java.util.StringTokenizer; import java.util.function.BiFunction; import java.util.function.Function; public class Main { static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y); static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> { x.addAll(y); return x; }; static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first); static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second); static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(GET_FIRST).thenComparing(GET_SECOND); public static void main(String[] args) throws Exception { long startTime = System.nanoTime(); int t = in.nextInt(); while (t-- > 0) { solve(); } long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms"); exit(0); } static void solve() { int n = in.nextInt(); String s = in.next(); out.println(calc(s, 'a')); } static int calc(String s, char c) { if (s.length() == 1) { if (s.charAt(0) == c) { return 0; } return 1; } int mid = s.length() / 2; char next = (char) (c + 1); int count_l = calc(s.substring(0, mid), next); count_l += s.length() / 2 - count(s.substring(mid), c); int count_r = calc(s.substring(mid), next); count_r += s.length() / 2 - count(s.substring(0, mid), c); return (Math.min(count_l, count_r)); } static int count(final String substring, final char c) { int ans = 0; for (int i = 0; i < substring.length(); i++) { if (substring.charAt(i) == c) { ans++; } } return ans; } static void debug(Object... args) { for (Object a : args) { out.println(a); } } static void y() { out.println("YES"); } static void n() { out.println("NO"); } static <T> T min(T a, T b, Comparator<T> C) { if (C.compare(a, b) <= 0) { return a; } return b; } static <T> T max(T a, T b, Comparator<T> C) { if (C.compare(a, b) >= 0) { return a; } return b; } static void fail() { out.println("-1"); } static class Pair<T, R> { public T first; public R second; public Pair(T first, R second) { this.first = first; this.second = second; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(first, pair.first) && Objects.equals(second, pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "Pair{" + "a=" + first + ", b=" + second + '}'; } public T getFirst() { return first; } public R getSecond() { return second; } } static <T, R> Pair<T, R> make_pair(T a, R b) { return new Pair<>(a, b); } static class ArrayUtils { static void swap(int[] a, int i, int j) { int 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 print(char[] a) { for (char c : a) { out.print(c); } out.println(""); } static int[] reverse(int[] data) { int[] p = new int[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static void prefixSum(long[] data) { for (int i = 1; i < data.length; i++) { data[i] += data[i - 1]; } } static void prefixSum(int[] data) { for (int i = 1; i < data.length; i++) { data[i] += data[i - 1]; } } static long[] reverse(long[] data) { long[] p = new long[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static char[] reverse(char[] data) { char[] p = new char[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static int[] MergeSort(int[] A) { if (A.length > 1) { int q = A.length / 2; int[] left = new int[q]; int[] right = new int[A.length - q]; System.arraycopy(A, 0, left, 0, q); System.arraycopy(A, q, right, 0, A.length - q); int[] left_sorted = MergeSort(left); int[] right_sorted = MergeSort(right); return Merge(left_sorted, right_sorted); } else { return A; } } static int[] Merge(int[] left, int[] right) { int[] A = new int[left.length + right.length]; int i = 0; int j = 0; for (int k = 0; k < A.length; k++) { // To handle left becoming empty if (i == left.length && j < right.length) { A[k] = right[j]; j++; continue; } // To handle right becoming empty if (j == right.length && i < left.length) { A[k] = left[i]; i++; continue; } if (left[i] <= right[j]) { A[k] = left[i]; i++; } else { A[k] = right[j]; j++; } } return A; } static long[] MergeSort(long[] A) { if (A.length > 1) { int q = A.length / 2; long[] left = new long[q]; long[] right = new long[A.length - q]; System.arraycopy(A, 0, left, 0, q); System.arraycopy(A, q, right, 0, A.length - q); long[] left_sorted = MergeSort(left); long[] right_sorted = MergeSort(right); return Merge(left_sorted, right_sorted); } else { return A; } } static long[] Merge(long[] left, long[] right) { long[] A = new long[left.length + right.length]; int i = 0; int j = 0; for (int k = 0; k < A.length; k++) { // To handle left becoming empty if (i == left.length && j < right.length) { A[k] = right[j]; j++; continue; } // To handle right becoming empty if (j == right.length && i < left.length) { A[k] = left[i]; i++; continue; } if (left[i] <= right[j]) { A[k] = left[i]; i++; } else { A[k] = right[j]; j++; } } return A; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 2048); 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public int[] readAllInts(int n) { int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); } return p; } public int[] readAllInts(int n, int s) { int[] p = new int[n + s]; for (int i = s; i < n + s; i++) { p[i] = in.nextInt(); } return p; } public long[] readAllLongs(int n) { long[] p = new long[n]; for (int i = 0; i < n; i++) { p[i] = in.nextLong(); } return p; } public long[] readAllLongs(int n, int s) { long[] p = new long[n + s]; for (int i = s; i < n + s; i++) { p[i] = in.nextLong(); } return p; } public double nextDouble() { return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
486836da6cf4de505f88100ef4652fce
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; public class Main { public static int getAns(String str,char ch,HashMap<String,Integer> map) { String temp=str+"|"+ch; if(str.length()==1) { if(str.charAt(0)==ch)return 0; else return 1; } if(map.containsKey(temp))return map.get(temp); int firstHalf=0,secondHalf=0; for(int i=1;i<=str.length();i++) { if(str.charAt(i-1)!=ch) { if(i>(str.length()/2))secondHalf++; else firstHalf++; } } ch=(char)(ch+1); int min= Math.min(firstHalf+getAns(str.substring(str.length()/2,str.length()),ch,map),secondHalf+getAns(str.substring(0,str.length()/2),ch,map)); map.put(temp,min); return min; } public static void main(String[] args) { Scanner kb=new Scanner(System.in); int t=kb.nextInt(); while(t-->0) { int n=kb.nextInt(); String str=kb.next(); HashMap<String,Integer> map=new HashMap<>(); System.out.println(getAns(str,'a',map)); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
712520c80261878d7a6765a710ad36f3
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; public class Main { public static int getAns(String str,char ch) { if(str.length()==1) { if(str.charAt(0)==ch)return 0; else return 1; } int firstHalf=0,secondHalf=0; for(int i=1;i<=str.length();i++) { if(str.charAt(i-1)!=ch) { if(i>(str.length()/2))secondHalf++; else firstHalf++; } } ch=(char)(ch+1); return Math.min(firstHalf+getAns(str.substring(str.length()/2,str.length()),ch),secondHalf+getAns(str.substring(0,str.length()/2),ch)); } public static void main(String[] args) { Scanner kb=new Scanner(System.in); int t=kb.nextInt(); while(t-->0) { int n=kb.nextInt(); String str=kb.next(); System.out.println(getAns(str,'a')); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
fe46086f61692c4faf09b338554ff51b
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; public class Main{ public static int min(String s,int start,int end,char c){ if(start==end){ if(s.charAt(start)==c) return 0; else return 1; } int mid=(start+end)/2; char d=(char)(c+1); int cnt1=(end-start+1)/2; int cnt2=cnt1; for(int i=start;i<=mid;i++){ if(s.charAt(i)==c) cnt1--; } for(int i=mid+1;i<=end;i++){ if(s.charAt(i)==c) cnt2--; } //System.out.println(cnt1+" "+cnt2); int a=min(s,start,mid,d); int b=min(s,mid+1,end,d); return Math.min(cnt2+a,cnt1+b); } public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); String s=sc.next(); System.out.println(min(s,0,n-1,'a')); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
e859e6aac489e7fbeae472214784ce0f
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Scanner; public class Div656 { static Scanner sc =new Scanner(System.in); static PrintWriter out =new PrintWriter(System.out); public static void ThreePairwiseMaximums() { int t=sc.nextInt(); outer:for(int o=0;o<t;o++) { int x=sc.nextInt(); int y=sc.nextInt(); int z=sc.nextInt(); int []n= {x,y,z}; int a=0; int b=0; int c=0; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { for(int k=0;k<3;k++) { a=n[i]; b=n[j]; c=n[k]; if(x==Math.max(a,b)&&y==Math.max(a, c)&&z==Math.max(b, c)) { System.out.println("YES"); System.out.println(a+" "+b+" "+c); continue outer; } } } } System.out.println("NO"); } } public static void RestorethePermutationyMerger() { int t=sc.nextInt(); for(int o=0;o<t;o++) { int n=sc.nextInt(); LinkedHashSet<Integer>s =new LinkedHashSet<Integer>(); for(int i=0;i<2*n;i++) { s.add(sc.nextInt()); } for(Integer a:s) { System.out.print(a+" "); } System.out.println(); } } public static int aGoodStringRec(String s,int l,int r,char c,int[][]ch,int[]counterCh,int temp){ if(l==r&&s.charAt(l)==c)return 0; else if(l==r&&s.charAt(l)!=c)return 1; //int x=temp; //temp/=2; //(temp/2)-ch[(l+r)/2][c-97] int y=0; if(l>0) { y=ch[l-1][c-97]; ///System.out.println("y "+y+" "+c); } int fH=(temp/2)-(ch[(l+r)/2][c-97]-y); int sH=(temp/2)-(ch[r][c-97]-ch[(l+r)/2][c-97]); int mid=(l+r)/2; //System.out.println("fH "+fH+" "+s.substring(mid+1, r+1)+" "+c+" "+(int)(mid+1)+" "+r); int FT=fH+aGoodStringRec(s,mid+1,r,(char) (c+1),ch,counterCh,temp/2); //System.out.println(FT); //System.out.println("sH "+sH+" "+s.substring(l,mid+1)+" "+c+" "+l+" "+mid); int ST=sH+aGoodStringRec(s,l,mid,(char) (c+1),ch,counterCh,temp/2); //System.out.println(ST); return Math.min(FT,ST); } public static void aGoodString(){ int t=sc.nextInt(); sc.nextLine(); for(int o=0;o<t;o++) { int n=sc.nextInt(); sc.nextLine(); String s=sc.nextLine(); int [][]ch=new int[n][26]; int []counterCh=new int[26]; for(int i=0;i<s.length();i++) { counterCh[s.charAt(i)-97]++; for(int j=0;j<26;j++) { //System.out.println(j); ch[i][j]=counterCh[j]; } } // for(int i=0;i<n;i++) // System.out.println(Arrays.toString(ch[i])); // char c='a'; // int temp=n; // int l=0; // int r=n-1; // int count=0; // while(temp>1) { // int mid=(l+r)/2; // //System.out.println(l+" "+r+" "+mid); // //System.out.println(+" "+ch[r][c-97]); // if(ch[mid][c-97] >ch[r][c-97]-ch[mid][c-97]) { // // System.out.println(count+" "+c+" "+temp); // count+=(temp/2)-ch[(l+r)/2][c-97]; // l=mid; // } // else { // count+=(temp/2)-ch[r][c-97]; // r=mid; // // } // //int x=temp/2; // // count+=((temp/2)-Math.max(ch[(temp/2)-1][c-97], ch[temp-1][c-97])); // // temp/=2; // // c++; // } // //System.out.println(c+" "+l+" "+r); // if(s.charAt(l)!=c&&s.charAt(r)!=c)count++; // System.out.println(count); System.out.println(aGoodStringRec(s,0,n-1,'a',ch,counterCh,n)); } } public static void MakeItGood() { int t=sc.nextInt(); for(int o=0;o<t;o++) { int n=sc.nextInt(); int a[]=new int[n]; Integer b[]=new Integer[n]; HashMap<Integer,Integer>h=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ a[i]=sc.nextInt(); b[i]=a[i]; if(h.get(a[i])==null)h.put(a[i], 1); else h.put(a[i],h.get(a[i])+1); } if(n==1) { System.out.println(0); continue; } Arrays.sort(b); int l=0;int r=n-1; int m=0; int i=0; boolean f=true; while(l<r) { if(a[r]==b[i]) { h.put(a[r], h.get(a[r])-1); r--; i++; } else if(a[l]==b[i]&&f) { h.put(a[l], h.get(a[l])-1); l++; i++; } else if(a[l]==b[i]&&!f) { h.put(a[l], h.get(a[l])-1); m=l; f=true; i++; l++; } else { h.put(a[l], h.get(a[l])-1); f=false; l++; } } //if(!f)m+=(l); System.out.println(m); } } public static void MakeItGood2() { int t=sc.nextInt(); for(int o=0;o<t;o++) { int n=sc.nextInt(); int a[]=new int[n]; Integer b[]=new Integer[n]; HashMap<Integer,Integer>h=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ a[i]=sc.nextInt(); b[i]=a[i]; if(h.get(a[i])==null)h.put(a[i], 1); else h.put(a[i],h.get(a[i])+1); } if(n==1) { System.out.println(0); continue; } Arrays.sort(b); int l=0;int r=n-1; int m=0; //System.out.println(h); for(int i=0;i<b.length&&l<r;i++) { if(h.get(b[i])==null||h.get(b[i])==0)continue; if(a[l]==b[i]) { h.put(b[i],h.get(b[i])-1); l++; } else if(a[r]==b[i]) { h.put(b[i],h.get(b[i])-1); r--; } else { h.put(a[l],h.get(a[l])-1); for(int j=l+1;j<r;j++) { h.put(a[j],h.get(a[j])-1); if(a[j]==b[i]) { m=j; l=j+1; break; } } } //System.out.println(h); } System.out.println(m); } } public static void main(String[] args) { //ThreePairwiseMaximums(); // RestorethePermutationyMerger(); aGoodString(); //MakeItGood2(); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
b604a48f7563cfb3a955ae79ff9b58b5
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { private static FastReader fr = new FastReader(); private static Helper hp = new Helper(); private static StringBuilder result = new StringBuilder(); public static void main(String[] args) { Task solver = new Task(); solver.solve(); } static class Task { private int helper(String s, char ch){ if(s.length() == 0) return 0; if(s.length() == 1){ if(s.charAt(0) == ch) return 0; return 1; } int countLeft =0, countRight = 0; for(int i=0; i<s.length()/2; i++) if(s.charAt(i) == ch) countLeft++; for(int i=s.length()/2; i<s.length(); i++) if(s.charAt(i) == ch) countRight++; int op1 = helper(s.substring(0, s.length()/2), (char)(ch + 1)) + (s.length()/2 - countRight); int op2 = (s.length()/2 - countLeft) + helper(s.substring(s.length()/2), (char)(ch + 1)); return Math.min(op1, op2); } public void solve() { int nt = fr.ni(); while(nt-- > 0){ int n = fr.ni(); String s = fr.next(); int ans = helper(s, 'a'); result.append(ans).append("\n"); } System.out.println(result); } } static class Helper { public int[] ipArrInt(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fr.ni(); return arr; } public long[] ipArrLong(int n, int si) { long[] arr = new long[n]; for (int i = si; i < n; i++) arr[i] = fr.nl(); return arr; } } static class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; private static PrintWriter pw; public FastReader() { reader = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); 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 ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public double nd() { return Double.parseDouble(next()); } public String rl() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void print(String str) { pw.print(str); pw.flush(); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
07327962201527a88662d049b20abfd7
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { private static FastReader fr = new FastReader(); private static Helper hp = new Helper(); private static StringBuilder result = new StringBuilder(); public static void main(String[] args) { Task solver = new Task(); solver.solve(); } static class Task { private long helper(String s, char ch, int n){ if(n == 1 && s.charAt(0) == ch) return 0; if(n == 1 && s.charAt(0) != ch) return 1; StringBuilder sb = new StringBuilder(); for(int i=0; i<n/2; i++) sb.append(ch); String newStr = sb.toString(); long op1 = 0, op2 = 0; long ans1 = helper(s.substring(n/2, n), (char)(ch+1), n/2); long ans2 = helper(s.substring(0, n/2), (char)(ch+1), n/2); if(s.substring(0, n/2).equals(newStr)){ op1 = ans1; } else{ for(int i=0; i<n/2; i++){ if(s.charAt(i) != newStr.charAt(i)) op1 += 1; } op1 += ans1; } if(s.substring(n/2, n).equals(newStr.toString())){ op2 = ans2; } else{ for(int i=n/2, j=0; i<n; ++i, ++j){ if(s.charAt(i) != newStr.charAt(j)) op2 += 1; } op2 += ans2; } return Math.min(op1, op2); } public void solve() { int nt = fr.ni(); while(nt-- > 0){ int n = fr.ni(); String s = fr.next(); long ans = helper(s, 'a', n); result.append(ans).append("\n"); } System.out.println(result); } } static class Helper { public int[] ipArrInt(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fr.ni(); return arr; } public long[] ipArrLong(int n, int si) { long[] arr = new long[n]; for (int i = si; i < n; i++) arr[i] = fr.nl(); return arr; } } static class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; private static PrintWriter pw; public FastReader() { reader = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); 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 ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public double nd() { return Double.parseDouble(next()); } public String rl() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void print(String str) { pw.print(str); pw.flush(); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
38c1bede7976eff5a97ef0e110e34ec3
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
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 String s=""; public static void main (String[] args) throws java.lang.Exception { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t--!=0) { int n=in.nextInt(); s=in.next(); Codechef obj=new Codechef(); int q=obj.f(0,n,'a'); System.out.println(q); } } int f(int l,int r,char c) { if(r-l==1) { if(s.charAt(l)==c) return 0; else return 1; } int p1=0; int p=0; for(int i=l;i<r;i++) { if(s.charAt(i)==c && i<(l+r)/2) p++; else if(s.charAt(i)==c && i>=(l+r)/2) p1++; } return Math.min(f(l,(l+r)/2,(char)((int)c+1))+(r-l)/2-p1,f((l+r)/2,r,(char)((int)c+1))+(r-l)/2-p); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
e1c885579d2ca30f3528f96dda277e80
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)998244353; static int res=998244353; static String ss="abcdefghijklmnopqrstuvwxyz"; static void rec(char[] c, int c1,int i,int j,int tmp){ char cc=ss.charAt(c1); if(i==j){ if(c[i]!=cc) tmp++; res=Math.min(res,tmp); return; } int k=(i+j)/2,tc=0,tc1=0; for(int x=i;x<=k;x++) if(c[x]!=cc) tc++; for(int x=k+1;x<=j;x++) if(c[x]!=cc) tc1++; rec(c,c1+1,i,k,tc1+tmp);rec(c,c1+1,k+1,j,tmp+tc); } static void solve() throws IOException { int n=int_v(read()); res=998244353; char[] c=read().toCharArray(); rec(c,0,0,n-1,0); out.write(res+"\n"); } public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()); while(t--!=0) solve(); out.flush(); } // taking inputs static long pow1(long a,int p){long res=1;while(p>0){if((p&1)!=0){res=(res*a);}p >>=1;a=(a*a);}return res;} static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int gcd(int a,int b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
29de9289195860eb57dec0edeab07367
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; public class CF1385D { static FastReader in = new FastReader(); public static void main(String[] args) { int t = in.nextInt(); while(t-- > 0) solve(); } static void solve() { String[] alph = "abcdefghijklmnopqrstuvwxyz".split(""); int n = in.nextInt(); String s = in.nextLine(); if(n == 1) { if(s.equals("a")) System.out.println(0); else System.out.println(1); return; } System.out.println(find(s, 'a')); } static long find(String s, char c) { if(s.length() == 1) { return s.charAt(0) == c ? 0 : 1; } String left = s.substring(0, s.length() / 2); String right = s.substring(s.length() / 2); long n_left = numbetween(left.split(""), String.valueOf(c)); long n_right = numbetween(right.split(""), String.valueOf(c)); return Math.min(n_right + find(left, (char)(c + 1)), n_left + find(right, (char)(c + 1))); } static int numbetween(String[] arr, String a) { int count = 0; for(int i = 0; i < arr.length; i++) { if(arr[i].equals(a)) count++; } return arr.length - count; } 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
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
6ba98d717d5da1fb3451e465f0064b84
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; public class CF1385D { static FastReader in = new FastReader(); public static void main(String[] args) { int t = in.nextInt(); while(t-- > 0) solve(); } static void solve() { String[] alph = "abcdefghijklmnopqrstuvwxyz".split(""); int n = in.nextInt(); String s = in.nextLine(); if(n == 1) { if(s.equals("a")) System.out.println(0); else System.out.println(1); return; } System.out.println(find(s, 'a')); } static long find(String s, char c) { if(s.length() == 1) { return s.charAt(0) == c ? 0 : 1; } String left = s.substring(0, s.length() >> 1); String right = s.substring(s.length() >> 1); long n_left = Arrays.stream(left.split("")).filter(v -> v.charAt(0) != c).count(); long n_right = Arrays.stream(right.split("")).filter(v -> v.charAt(0) != c).count(); return Math.min(n_right + find(left, (char)((int)c + 1)), n_left + find(right, (char)((int)c + 1))); } static int numbetween(int start, int end, String[] arr, String a) { int count = 0; if(start == end) if(arr[start].equals(a)) count++; for(int i = start; i < end; i++) { if(arr[i].equals(a)) count++; } return count; } 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
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
5726dabba4de90ddbd3baecb22ef6f2c
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while ( t-- > 0 ) { int n = scanner.nextInt(); String s = scanner.next(); System.out.println( calculateAnswer(n, s, 0) ); } } private static int calculateAnswer(int n, String s, int iterationNo) { if (n==1) { if (s.charAt(0) == 'a' + iterationNo) return 0; else return 1; } int firstHalf = 0; int secondHalf = 0; for (int i=0; i<n/2; i++) { int charAsNumber = s.charAt(i) - 'a' - iterationNo; if (charAsNumber == 0) firstHalf++; } for (int i=n/2; i<n; i++) { int charAsNumber = s.charAt(i) - 'a' - iterationNo; if (charAsNumber == 0) secondHalf++; } int temp1 = (n/2 - firstHalf) + calculateAnswer(n/2, s.substring(n/2), iterationNo+1); int temp2 = (n/2 - secondHalf) + calculateAnswer(n/2, s.substring(0, n/2), iterationNo+1); return Math.min(temp1, temp2); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
97506eaa9dbb29e1df005a8be22994da
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static int dac(char carr[],int c,int l,int r) { if(l==r) { if((carr[l]-'a')==c) return 0; return 1; } int mid=(l+r)/2; int cntr1=0,cntr2=0; for(int i=l;i<=mid;i++) if((carr[i]-'a')!=c) cntr1++; for(int i=mid+1;i<=r;i++) if((carr[i]-'a')!=c) cntr2++; c++; return Math.min(cntr1+dac(carr,c,mid+1,r),cntr2+dac(carr,c,l,mid)); } public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { int n=Integer.parseInt(br.readLine()); char carr[]=br.readLine().toCharArray(); pw.println(dac(carr,0,0,n-1)); } pw.flush(); pw.close(); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
e07cb2b250456997a2474780805324e0
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class D { private static int solve(char[] str, int l, int r, char cur) { if(l==r) return str[l]==cur?0:1; int mid=(l+r)/2; int c1=0,c2=0; for(int i=l;i<=mid;i++) if(str[i]!=cur) c1++; for(int i=mid+1;i<=r;i++) if(str[i]!=cur) c2++; int tmp1=c1+solve(str,mid+1,r,(char)(cur+1)); int tmp2=c2+solve(str,l,mid,(char)(cur+1)); return Math.min(tmp1,tmp2); } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while(T-->0) { N=Integer.parseInt(br.readLine().trim()); char[] str=br.readLine().trim().toCharArray(); sb.append(solve(str,0,N-1,'a')).append("\n"); } System.out.println(sb); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
1a8d02cd2f2e73ef9b17d79b75bfb93f
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.Scanner; public class hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); char checker = 'a'; String s = sc.next(); int ans = getMin(s, 0, n - 1, checker); System.out.println(ans); } } private static int getMin(String s, int l, int r, char checker) { if (l == r) { if (s.charAt(l) == checker) return 0; else return 1; } int mid = (l + r) / 2; return Math.min(getCost(s, mid + 1, r, checker) + getMin(s, l, mid, (char) ((int) checker + 1)), getCost(s, l, mid, checker) + getMin(s, mid + 1, r, (char) ((int) checker + 1))); } private static int getCost(String s, int l, int r, char c) { int cnt = 0; for (int i = l; i <= r; i++) if (s.charAt(i) != c) cnt++; return cnt; } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
08959ac66e8b550bfdb0ae2cd6fbadb6
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class D_Round_656_Div3 { public static long MOD = 1000000007; static int[][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int z = 0; z < T; z++) { int n = in.nextInt(); String line = in.nextLine(); int[][] count = new int[26][n]; for (int i = 0; i < n; i++) { int index = line.charAt(i) - 'a'; count[index][i]++; if (i > 0) { for (int j = 0; j < 26; j++) { count[j][i] += count[j][i - 1]; } } } int l = Integer.numberOfTrailingZeros(n); dp = new int[26][n]; for (int[] a : dp) { Arrays.fill(a, -1); } //System.out.println(l); out.println(cal(0, 0, count)); } out.close(); } static int cal(int index, int need, int[][] count) { int l = Integer.numberOfTrailingZeros(count[0].length) - need; if (l == 0) { int v = count[need][index] - (index > 0 ? count[need][index - 1] : 0); return 1 - v; } if (dp[need][index] != -1) { return dp[need][index]; } int len = 1 << l; //System.out.println(l + " " + len + " " + need + " " + index); int a = count[need][index + (len / 2) - 1] - (index > 0 ? count[need][index - 1] : 0); int b = count[need][index + len - 1] - count[need][index + (len / 2) - 1]; a = len / 2 - a + cal(index + len / 2, need + 1, count); b = len / 2 - b + cal(index, need + 1, count); return dp[need][index] = Integer.min(a, b); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * (val * a); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
b212ddc0bf140358a3d309a411b792f0
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class A_Good_String { InputReader in;PrintWriter pw; char str[]; long pow(long base,long power) { if(power==0) return 1L; long temp = 1L; if(power%2==1) { temp = base; } base = (base*base); return (temp*pow(base,power/2L)); } long getAns(int l,int r ,char ch) { //pn(l+" "+r); int mid = (int)Math.floor((l+r)/(double)2); if(r-l+1 == 1) { if(str[l] == ch) return 0; return 1; } long c1 =0,c2=0; for(int i=l;i<=mid;i++) { if(str[i] != ch) c1++; } for(int i=mid+1;i<=r;i++) { if(str[i] != ch) c2++; } return Math.min(c1+getAns(mid+1,r,(char)(ch+1)),c2+getAns(l,mid,(char)(ch+1))); } void solve(int test) throws Exception { int n = ni(); str = nln().toCharArray(); pn(getAns(0,n-1,'a')); } void run() throws Exception { in = new InputReader(); pw = new PrintWriter(System.out); int test = ni(); while(test--!=0){solve(test);} pw.close(); } public static void main(String[] args) throws Exception { new A_Good_String().run(); } void p(Object o){pw.print(o);} void pn(Object o){pw.println(o);} void pn(){pw.println();} void spn(Object o){System.out.println(o);}; String nln() throws Exception {return in.nextLine();} int ni() throws Exception {return Integer.parseInt(in.next());} double nd() throws Exception {return Double.parseDouble(in.next());} long nl() throws Exception {return Long.parseLong(in.next());} class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public InputReader(String s) throws IOException { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch(IOException e) { throw new Exception(e.toString()); } return str; } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
0123e9939c7540ccffe900a554cfb31c
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
// _________________________RATHOD_____________________________________________________________ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class Main { static ArrayList<ArrayList<Integer>> graph; static int visited[]; 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 String s; public static void main(String[] args) { FastReader sc=new FastReader(); int t=sc.nextInt(); while(t>0) { t--; int n=sc.nextInt(); s=sc.next(); char ch='a'; if(n==1) { if(s.charAt(0)=='a') System.out.println(0); else System.out.println(1); } if(n!=1) System.out.println(countc(1,n,ch,n)); } } public static int countc(int st,int e,char ch,int size) { int mid=((e-st+1)/2)+st-1; int l=countf(ch,st,mid); int r=countf(ch,(mid+1),e); int rl=size/2-l; int rr=size/2-r; if(size==2) { if(s.charAt(st-1)==ch) { if(s.charAt(e-1)==(ch+1)) { return 0; } else return 1; } else { if(s.charAt(st-1)==ch+1) { if(s.charAt(e-1)==(ch)) { return 0; } else return 1; } else { if((s.charAt(e-1)==(ch))||(s.charAt(e-1)==(ch+1))) { return 1; } else return 2; } } } else { int lll=(countc(st,mid,((char) (ch+1)),size/2)+rr); int rrr=(countc(mid+1,e,((char) (ch+1)),size/2)+rl); // System.out.println(lll+" "+rrr); return((int) Math.min(lll,rrr)); } } public static int countf(char ch,int st,int e) { int i; int count=0; for(i=st-1;i<=e-1;i++) { if(s.charAt(i)==ch) count++; } return count; } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
44c9709b6493f3749244de3d735474a5
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; public class temp { public int find(int c,int l,int r,String s,int f[][]) { if(l==r) { if(s.charAt(l)!=(char)(c+97)) return 1; return 0; } int mid = (l+r)/2; int ans = Integer.MAX_VALUE; int left = (mid-l+1) - (f[mid][c] - ((l-1)>=0 ? f[l-1][c] : 0)); int right = (r-mid) - (f[r][c] - f[mid][c]); ans = Math.min(left + find(c+1,mid+1,r,s,f) , right + find(c+1,l,mid,s,f)); return ans; } void solve() throws IOException { FastReader sc=new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); String s = sc.next(); int f[][] = new int[n][26]; for(int i=0;i<n;i++) { if(i!=0) { for(int j=0;j<26;j++) f[i][j]+=f[i-1][j]; } f[i][s.charAt(i)%97]++; } System.out.println(find(0,0,n-1,s,f)); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub new temp().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
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
5990fa7a594b34511e3f449596146777
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; public class temp { HashMap<String,Integer> dp; public int find(int c,int l,int r,String s,int f[][]) { if(l==r) { if(s.charAt(l)!=(char)(c+97)) return 1; return 0; } String tmp = l+"#"+r+"#"+c; if(dp.containsKey(tmp)) return dp.get(tmp); int mid = (l+r)/2; int ans = Integer.MAX_VALUE; int left = (mid-l+1) - (f[mid][c] - ((l-1)>=0 ? f[l-1][c] : 0)); int right = (r-mid) - (f[r][c] - f[mid][c]); ans = Math.min(left + find(c+1,mid+1,r,s,f) , right + find(c+1,l,mid,s,f)); dp.put(tmp , ans); return ans; } void solve() throws IOException { FastReader sc=new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); String s = sc.next(); int f[][] = new int[n][26]; for(int i=0;i<n;i++) { if(i!=0) { for(int j=0;j<26;j++) f[i][j]+=f[i-1][j]; } f[i][s.charAt(i)%97]++; } dp = new HashMap<>(); System.out.println(find(0,0,n-1,s,f)); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub new temp().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
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
84d638eb137d2b023e5dab8b268fc781
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static CustomScanner input; static PrintWriter out; public static void main(String commandLineArgument[]){ input = new CustomScanner(); out = new PrintWriter(System.out); int tc = input.nextInt(); while(tc --> 0) { int n = input.nextInt(); String s = input.next(); int [][] characterCount = new int[n + 1][26]; for(int i = 0; i < n; ++i){ int reqChar = s.charAt(i) - 'a'; for(int j = 0; j < 26; ++j){ characterCount[i + 1][j] = characterCount[i][j] + ((j == reqChar) ? 1 : 0); } } int answer = findGoodArray(1 , n , 0, characterCount); out.println(answer); } out.close(); } private static int findGoodArray(int l, int r , int reqChar , int [][] characterCount) { if(l == r){ int reqCount = characterCount[r][reqChar] - characterCount[r - 1][reqChar]; return (reqCount == 0) ? 1 : 0; } int mid = l + (r - l)/2; int halfCount = ((r - l) + 1)/2; int firstHalf = characterCount[mid][reqChar] - characterCount[l - 1][reqChar]; int reqFirstHalf = halfCount - firstHalf; int minReq = reqFirstHalf + findGoodArray(mid + 1 , r , reqChar + 1 , characterCount); int secondHalf = characterCount[r][reqChar] - characterCount[mid][reqChar]; int reqSecondHalf = halfCount - secondHalf; minReq = Math.min(minReq , reqSecondHalf + findGoodArray(l , mid , reqChar + 1 , characterCount)); return minReq; } } class CustomScanner{ BufferedReader br; StringTokenizer st; public CustomScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} double nextDouble() { return Double.parseDouble(next());} long nextLong() { return Long.parseLong(next());} }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
35fd0aebf06df47200d8390a06ca3a16
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static CustomScanner input; static PrintWriter out; public static void main(String commandLineArgument[]){ input = new CustomScanner(); out = new PrintWriter(System.out); int tc = input.nextInt(); while(tc --> 0) { int n = input.nextInt(); String s = input.next(); int [][] characterCount = new int[n + 1][26]; for(int i = 0; i < n; ++i){ int reqChar = s.charAt(i) - 'a'; for(int j = 0; j < 26; ++j){ characterCount[i + 1][j] = characterCount[i][j] + ((j == reqChar) ? 1 : 0); } } int answer = findGoodArray(1 , n , 0, characterCount); out.println(answer); } out.close(); } private static int findGoodArray(int l, int r , int reqChar , int [][] characterCount) { if(l == r){ int reqCount = characterCount[r][reqChar] - characterCount[r - 1][reqChar]; return (reqCount == 0) ? 1 : 0; } int mid = l + (r - l)/2; int halfCount = ((r - l) + 1)/2; int firstHalf = characterCount[mid][reqChar] - characterCount[l - 1][reqChar]; int reqFirstHalf = halfCount - firstHalf; int minReq = reqFirstHalf + findGoodArray(mid + 1 , r , reqChar + 1 , characterCount); int secondHalf = characterCount[r][reqChar] - characterCount[mid][reqChar]; int reqSecondHalf = halfCount - secondHalf; minReq = Math.min(minReq , reqSecondHalf + findGoodArray(l , mid , reqChar + 1 , characterCount)); return minReq; } } class CustomScanner{ BufferedReader br; StringTokenizer st; public CustomScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} double nextDouble() { return Double.parseDouble(next());} long nextLong() { return Long.parseLong(next());} }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
a2f00eec23f7c040afa6be35d0037c36
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; public class Main { static int c=0; public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); String str=in.next(); int z=good(str, 0, str.length()-1, 'a'); System.out.println(z); } } public static int good(String str, int l ,int r, char ch){ c++; if(l==r){ if(str.charAt(l)==ch){ return 0; } return 1; } if(l>r){ return 1000000; } int mid=(l+r)/2; int c1=0, c2=0; for(int i=l ; i<=mid ; i++){ if(str.charAt(i)!=ch){ c1+=1; } } for(int i=mid+1 ; i<=r ; i++){ if(str.charAt(i)!=ch){ c2+=1; } } c1+=good(str, mid+1, r, (char)(ch+1)); c2+=good(str, l, mid, (char)(ch+1)); return Math.min(c1, c2); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
cd995bcbcde3d1f4572098f555007105
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int T = in.nextInt(); while (T-- > 0) { solve(in, out); } } private void solve(Scanner in, PrintWriter out) { int N = in.nextInt(); String S = in.next(); out.println(recurr(0, N - 1, 'a', S)); } private int recurr(int start, int end, char a, String S) { if (start == end) return S.charAt(start) == a ? 0 : 1; int first = 0, second = 0; int mid = start + ((end - start) / 2); for (int i = start; i <= mid; i++) { if (S.charAt(i) == a) continue; first++; } for (int i = mid + 1; i <= end; i++) { if (S.charAt(i) == a) continue; second++; } /*if (first < second){ return first + recurr(mid + 1, end, (char) (a + 1), S); }else if (first > second) { return second + recurr(start, mid, (char) (a + 1), S); } else { return Math.min(first + recurr(mid + 1, end, (char) (a + 1), S), second + recurr(start, mid, (char) (a + 1), S)); }*/ return Math.min(first + recurr(mid + 1, end, (char) (a + 1), S), second + recurr(start, mid, (char) (a + 1), S)); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
179c4f8f2fd0f2722fa605d6daa036cb
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
// coded by Krishna Sundar // import java.lang.*; import java.io.*; import java.util.*; public class Main { private int calc(int[][] count, int start, int end, int C) { return count[end][C]-(start-1<0?0:count[start-1][C]); } private int GO(String str, int[][] count, int start, int end, int C) { if (start==end) { if ((str.charAt(start)-'a')!=C) { return 1; } return 0; } int mid = (start+end)/2; int left = calc(count, start, mid, C); int right = calc(count, mid+1, end, C); int len = mid-start+1; int res1 = 0; res1 += (len-left) + GO(str, count, mid+1, end, C+1); int res2 = 0; len = (end-(mid+1))+1; res2 += (len-right) + GO(str, count, start, mid, C+1); return Math.min(res1, res2); } public void solve(Read input, Write output) throws Exception { int cases = input.readInt(); while (cases-->0) { int N = input.readInt(); int[][] count = new int[N+1][26]; String str = input.readString(); for (int i=0;i<N;i++) { int pos = str.charAt(i)-'a'; for (int j=0;j<26;j++) { count[i][j] = ((pos==j)?1:0)+((i-1)<0?0:count[i-1][j]); } } output.printLine(GO(str, count, 0, N-1, 0)); } } public static void main(String[] args) throws Exception { Read input = new Read(); Write output = new Write(); Main D = new Main(); D.solve(input, output); output.flush(); output.close(); } // java fast io reader and writer // taken from various sources and customized static class Read { private byte[] buffer =new byte[10*1024]; private int index; private InputStream input_stream; private int total; public Read() { input_stream = System.in; } public int read()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total= input_stream.read(buffer); if(total<=0) return -1; } return buffer[index++]; } public long readLong() throws IOException { long number=0; int n= read(); while(isWhiteSpace(n)) n= read(); long neg=1l; if(n=='-') { neg=-1l; n= read(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { number*=10l; number+=(long)(n-'0'); n= read(); } else throw new InputMismatchException(); } return neg*number; } public int readInt() throws IOException { int integer=0; int n= read(); while(isWhiteSpace(n)) n= read(); int neg=1; if(n=='-') { neg=-1; n= read(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n= read(); } else throw new InputMismatchException(); } return neg*integer; } public double readDouble()throws IOException { double doub=0; int n= read(); while(isWhiteSpace(n)) n= read(); int neg=1; if(n=='-') { neg=-1; n= read(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n= read(); } else throw new InputMismatchException(); } if(n=='.') { n= read(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n= read(); } else throw new InputMismatchException(); } } return doub*neg; } public String readString()throws IOException { StringBuilder sb = new StringBuilder(); int n = read(); while (isWhiteSpace(n)) n = read(); while (!isWhiteSpace(n)) { sb.append((char)n); n = read(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '|| n=='\n'|| n=='\r'|| n=='\t'|| n==-1) return true; return false; } } static class Write { private final BufferedWriter bw; public Write() { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object str) throws IOException { bw.append(str+""); } public void printLine(Object str) throws IOException { print(str); bw.append("\n"); } public void close()throws IOException { bw.close(); } public void flush()throws IOException { bw.flush(); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
f493edba6d1015957c44f2dd70eb2180
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Code { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); StringBuilder res = new StringBuilder(); int t = sc.nextInt(); while (t-- > 0) { int len = sc.nextInt(); String s = sc.next(); int result = halve(s, 'a'); pw.println(result); } pw.close(); } public static int halve(String str, char c) { int count1 = 0; int count2 = 0; if (str.length() == 1) { if (str.charAt(0) == c) { return 0; } else { return 1; } } int half1 = 0; int len = str.length()/2; for (int i = 0; i < len; i++) { if (str.charAt(i) == c) { half1++; } } int half2 = 0; for (int i = len; i < str.length(); i++) { if (str.charAt(i) == c) { half2++; } } count1 += (len - half1); count1 += halve(str.substring(len), (char)(c +1)); count2 += (len - half2); count2 += halve(str.substring(0, len), (char)(c +1 )); return Math.min(count1, count2); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
28702d95da34480a896468c7bf9a03fd
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
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 Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while(t-->0) { sum=0; int n=Integer.parseInt(bf.readLine()); String s=bf.readLine(); check(97,s); System.out.println(solve(s,0)); // System.out.println("testcase khtm"); } } static int sum=0; public static void check(int z,String s) { int n=s.length(); if(n==0) return; if(n==1) { if(s.charAt(0)==(char)z) { return; } else{ sum=sum+1; return; } } if(n==2) { if(s.charAt(0)==(char)z || s.charAt(1)==(char)z) { if(s.charAt(0)==(char)z+1 || s.charAt(1)==(char)z+1) { return; } else { sum=sum+1; return; } } else { if(s.charAt(0)==(char)z+1 || s.charAt(1)==(char)z+1) { sum=sum+1; return; } else { sum=sum+2; return; } } } // char c=(char)z; int a[]=new int[26]; int b[]=new int[26]; int req[]=new int[26]; int len=n; int zz=z-97; while(len>0) { req[zz]=len/2; zz++; len=len/2; } int index=0; for(index=z-97;index<26;index++) { if(req[index]==0) { break; } } for(int i=0;i<n/2;i++) { int p=s.charAt(i)-97; a[p]++; if(a[p]>req[p]) { a[p]=req[p]; } } for(int i=n/2;i<n;i++) { int p=s.charAt(i)-97; b[p]++; if(b[p]>req[p]) { b[p]=req[p]; } } // System.out.println("a "+Arrays.toString(a)); // System.out.println("b "+Arrays.toString(b)); int sum1=0; int sum2=0; for(int i=(z-97)+1;i<index;i++) { sum1+=a[i]; sum2+=b[i]; } if(sum1>sum2) { sum+=n/2-b[z-97]; String m=s.substring(0,n/2); check(z+1,m); } else if(sum2>sum1) { sum+=a[z-97]; String m=s.substring(n/2,n); check(z+1,m); } // for(int i=z-97;i<26;i++) // { // if(i==z-97 ) // { // if(a[i]!=b[i]) // { // if(a[i]>b[i]) // { // sum=sum+(n/2-a[i]); // // System.out.println("sum1 "+sum); // // z++; // // System.out.println(((end-start+1)/2)+" "+end+" "+n/2+" "+(z+1)+" "+s); // String m=s.substring(n/2,n); // check(z+1,m); // break; // } // else // { // sum=sum+(n/2-b[i]); // // System.out.println("sum2 "+sum); // // System.out.println(((end-start+1)/2)+" "+end+" "+n/2+" "+(z+1)+" "+s); // // z++; // String m=s.substring(0,n/2); // check(z+1,m); // break; // } // } // } // else // { // if(a[i]!=b[i]) // { // if(a[i]<b[i]) // { // sum=sum+(n/2-a[z-97]); // // z++; // // System.out.println("sum3 "+sum); // // System.out.println(((end-start+1)/2)+" "+end+" "+n/2+" "+(z+1)+" "+s); // String m=s.substring(n/2,n); // check(z+1,m); // break; // } // else // { // sum=sum+(n/2-b[z-97]); // // z++; // // System.out.println("sum4 "+sum); // // System.out.println(((end-start+1)/2)+" "+end+" "+n/2+" "+(z+1)+" "+s); // String m=s.substring(0,n/2); // check(z+1,m); // break; // } // } // else // { // if(i==25) // { // sum=sum+(n/2); // String m=s.substring(0,n/2); // check(z+1,m); // } // } // } // } } public static int solve(String str,int ii){ char ch=(char)(ii+'a'); int n=str.length(); if(str.length()==1){ if(str.charAt(0)==ch) { return 0; } else{ return 1; } } int ans1=0; for(int i=0;i<n/2;i++){ if(str.charAt(i)!=ch) { ans1++; } } ans1 = ans1 + solve(str.substring(n/2,n),ii+1); int ans2 = 0; for(int i=0;i<n/2;i++){ if(str.charAt(i+n/2)!=ch) { ans2++; } } ans2 += solve(str.substring(0,n/2),ii+1); return Math.min(ans1,ans2); } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
87baec73aae549bad2c2a2996d07b370
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.util.*; public class cfgs{ static int goods(String s,int strs,int stre,int ctf) { if(strs==stre) { char c=(char)(97+ctf); if(s.charAt(strs)!=c) return 1; else return 0; } int lc=0; int rc=0; char c=(char)(97+ctf); int i=0; int k=(stre-strs+1)/2; while(k>0) { char cl=s.charAt(strs+i); char cr=s.charAt(stre-i); if(cl==c) lc++; if(cr==c) rc++; i++; k--; } int countl=0; int countr=0; int conl=goods(s,((stre+strs)/2)+1,stre,ctf+1); int conr=goods(s,strs,((stre+strs)/2),ctf+1); countl=(stre-strs+1)/2-lc+conl; countr=(stre-strs+1)/2-rc+conr; int count=Math.min(countl,countr); return count; } public static void main(String[]args) { Scanner scn=new Scanner(System.in); int tc=scn.nextInt(); for(int i=0;i<tc;i++) { int n=scn.nextInt(); String s=scn.next(); int res=goods(s,0,s.length()-1,0); System.out.println(res); } } }
Java
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
237622316fb4e28d6ed75ad630346d6f
train_000.jsonl
1594996500
You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.*; public class D { public static int replace(String s,char c) { int ans=0; for(char c1:s.toCharArray()) if(c1!=c) ans++; return ans; } public static int solve(String s,char c) { if(s.length()==1) return s.charAt(0)==c? 0:1; if(s.length()==2) { int diff= Math.abs(s.charAt(0)-s.charAt(1)); //System.out.println(s+" "+diff); if (diff==1&&((s.charAt(0)==c&&s.charAt(1)==c+1)||(s.charAt(0)==c+1&&s.charAt(1)==c))) return 0; if(s.charAt(0)==c||s.charAt(1)==c||s.charAt(0)==c+1||s.charAt(1)==c+1) return 1; else return 2; } int n=s.length(); int ans1= solve(s.substring(0,n/2), (char) (c+1))+ replace(s.substring(n/2), c); int ans2= replace(s.substring(0,n/2), c)+ solve(s.substring(n/2), (char) (c+1)); return Math.min(ans1, ans2); } public static void main(String[] args) { FastScanner scanner=new FastScanner(); int t=scanner.nextInt(); while(t-->0) { int n=scanner.nextInt(); String string=scanner.next(); int res= solve(string, 'a'); System.out.println(res); } } 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
["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"]
2 seconds
["0\n7\n4\n5\n1\n1"]
null
Java 8
standard input
[ "dp", "bitmasks", "implementation", "divide and conquer", "brute force" ]
324b7957b46dfe4948074c781159b7e7
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) β€” the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,500
For each test case, print the answer β€” the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.
standard output
PASSED
48965e532f595240288b631f9d878991
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.math.*; import java.io.*; public class C408C{ public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] num1=br.readLine().split(" "); int A=Integer.parseInt(num1[0]); int B=Integer.parseInt(num1[1]); int fx1=0; int fy1=0; int fx2=0; int fy2=0; for(int x=1;x<A;x++) if((int)Math.sqrt((double)(A*A-x*x))*(int)Math.sqrt((double)(A*A-x*x))+x*x==A*A){ int x1=x; int y1=(int)Math.sqrt((double)(A*A-x*x)); for(int y=1;y<B;y++) if(y*x1%y1==0) if(y*y+(y*x1/y1)*(y*x1/y1)==B*B){ if(y==x1){ if(y*x1/y1!=y1){ fx1=x1; fy1=y1; fx2=-y; fy2=y*x1/y1; } } else{ fx1=x1; fy1=y1; fx2=y; fy2=-y*x1/y1; } } } if(fx1!=0 && fx2!=0){ System.out.println("YES"); System.out.println("0 0"); System.out.println(fx1+" "+fy1); System.out.println(fx2+" "+fy2); } else System.out.println("NO"); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
336f5e550389065b158b9b569d699116
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.Scanner; public class test { public static void main(String args[]) { Scanner input = new Scanner(System.in); double a = input.nextInt(); double b = input.nextInt(); input.close(); double c = a * a + b * b; double xA = 0, yA = 0, xB = 0, yB = 0; for (int i = 1; i < a; i++) { if (Math.sqrt(a * a - i * i) == (int)Math.sqrt(a * a - i * i)) { xA = i; yA = Math.sqrt(a * a - i * i); //System.out.println(xA + " " + yA); for (int j = 1; j < c; j++) { if (Math.sqrt(c - j * j) == (int)Math.sqrt(c - j * j)) { //System.out.println(j + " " + Math.sqrt(c - j * j)); xB = xA - Math.sqrt(c - j * j); yB = yA + j; if (xB * xB + yB * yB != b * b) yB = yA - j; //System.out.println(xB + " " + yB); double lenNorm = Math.sqrt(xA * xA + yA * yA); //System.out.println(lenNorm); if (xB / (-yA / lenNorm) == b && yB / (xA / lenNorm) == b) { System.out.println("YES"); System.out.println(0 + " " + 0); System.out.println((int)xA + " " + (int)yA); System.out.println((int)xB + " " + (int)yB); return; } } } //System.out.println(); } } System.out.print("NO"); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
4ea4226af5fba4d186e36dc29928b1e5
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class solver implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } String readString(String delim) throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } int readInt() throws IOException{ return Integer.parseInt(readString()); } int readInt(String delim) throws IOException{ return Integer.parseInt(readString(delim)); } long readLong() throws IOException{ return Long.parseLong(readString()); } long readLong(String delim) throws IOException{ return Long.parseLong(readString(delim)); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } double readDouble(String delim) throws IOException{ return Double.parseDouble(readString(delim)); } char readChar() throws IOException { char val = 0; do{ val = (char) in.read(); }while(val == '\n' || val == '\r'); return val; } char readChar(String skipChars)throws IOException{ char val = 0; boolean ret; do{ val = (char) in.read(); ret = false; for (int i = skipChars.length()-1; i >= 0; i--){ if (skipChars.charAt(i) == val){ ret = true; break; } } }while(ret); return val; } public class Pair<T1,T2> { public T1 x1; public T2 x2; public Pair(){}; public Pair(T1 x1, T2 x2){ this.x1 = x1; this.x2 = x2; } public String toString(){ return x1.toString() + " " + x2.toString(); } } public class Point implements Comparable<Point>{ public int x1, x2; public Point(){} public Point(int a, int b){x1 = a;x2=b;} public int compareTo(Point o) { return x1-o.x1; } public String toString(){ return x1 + " " + x2; } } //---------------------------------------- Point getPif(int a, int i){ int aa = a*a; int ii; for (;i*i + 1 <= aa ;i++){ ii = i*i; int cc = aa - ii; int c = (int) Math.sqrt(cc); cc=c*c; if (cc + ii == aa){ return new Point(i,c); } } return null; } public void solve() throws IOException { int a = readInt(); int b = readInt(); int mm; if (b < a){ mm = b; b = a; a = mm; } int i = 0; int aa = a*a; int bb = b*b; int ii, kk, zz; while(true){ Point p = getPif(b, i+1); if (p == null){ break; } i = p.x1; ii = i*i; int k = p.x2; kk = k*k; int z = (int) (a*k/Math.sqrt(ii+kk)); zz = z*z; if (aa*kk != zz*(ii+kk)){ continue; } int m = (int) Math.sqrt(aa - zz); mm = m*m; if (mm + zz != aa) continue; if (m == k) continue; out.println("YES"); out.println("0 " + i); out.println(k +" 0"); out.println((m) +" " + (i+z)); return; } out.print("NO"); } //---------------------------------------- public static void main(String[] args){ new Thread(null, new solver(), "", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } public void run(){ try{ timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
ee27e7b44151c825aa5d4e47255daf1f
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; public class C { Scanner sc = new Scanner(System.in); void doIt() { int a = sc.nextInt(); int b = sc.nextInt(); if(a > b) { int tmp = a; a = b; b = tmp; } // swap for(int x = 1; x < a; x++) { for(int y = 1; y < a; y++) { if(x*x + y*y == a*a) { // candidate int m = x * b / a; int n = y * b / a; if(m*m + n*n == b*b) { // OK System.out.println("YES"); System.out.println(0 + " " + 0); System.out.println(-x + " " + y); System.out.println(-n + " " + -m); return; } } } } System.out.println("NO"); } public static void main(String[] args) { new C().doIt(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
1101be5a1e5e446a1330f7143a66e4bd
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; public class a { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a = input.nextInt(), b = input.nextInt(); int g = gcd(a, b); if(a>b) { int temp = a; a = b; b = temp; } int[] first = py(g); if(first.length == 0 || first[0]*(a/g) == (b/g)*first[1]) { System.out.println("NO"); } else { System.out.println("YES"); System.out.println(0+" "+0); System.out.println(first[0]*(a/g)+" "+first[1]*(a/g)); System.out.println((b/g)*first[1]+" "+(-b/g)*first[0]); } } static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a%b); } static int[] py(int c) { for(int i = 1; i<c; i++) { int diff = c*c - i*i; int sqrt = (int)(Math.sqrt(diff) + .5); if(Math.abs(sqrt - Math.sqrt(diff)) < 1e-9) return new int[]{i, sqrt}; } return new int[0]; } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
b4304372312fdb0fa580adfef939f6c8
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.InputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CF239CDev2 { class Triangle implements Comparable<Triangle> { int a, b, c; Triangle(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(Triangle o) { return c - o.c; } } Triangle[] getIntegerTriangle() { int a, a2, b, b2; Set<Triangle> al = new HashSet<Triangle>(); for (a = 1; a <= 1000; a++) { a2 = a * a; for (b = a; b <= 1000; b++) { b2 = b * b; double c = Math.sqrt(a2 + b2); if (Math.floor(c) == c) { al.add(new Triangle(a, b, (int) c)); } } } Triangle ts[] = al.toArray(new Triangle[0]); Arrays.sort(ts); return ts; } String solve(int l1, int l2) { boolean l1IsOk = false, l2IsOk = false; boolean allIsOk = false; Triangle[] ts = getIntegerTriangle(); int ax = 0, ay = 0, bx = 0, by = 0; for (int i = 0; i < ts.length; i++) { if (ts[i].c == l1) { l1IsOk = true; } if (ts[i].c == l2) { l2IsOk = true; } if (l1IsOk && l2IsOk) { for (int j = 0; j < ts.length; j++) { if (l1 % ts[j].c == 0 && l2 % ts[j].c == 0) { allIsOk = true; int k1 = l1 / ts[j].c; int k2 = l2 / ts[j].c; ax = ts[j].a * k1; ay = ts[j].b * k1; bx = -ts[j].b * k2; by = ts[j].a * k2; if (ay == by) { ax = ts[j].b * k1; ay = ts[j].a * k1; bx = -ts[j].a * k2; by = ts[j].b * k2; } break; } } } if (allIsOk) break; } return !allIsOk ? "NO" : "YES\n0 0\n" + ax + " " + ay + "\n" + bx + " " + by; } String solve(InputStream in) { Scanner sc = new Scanner(in); int leg1 = sc.nextInt(); int leg2 = sc.nextInt(); return solve(leg1, leg2); } public static void main(String[] args) { System.out.println(new CF239CDev2().solve(System.in)); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
7341466de7441f565bac53409aaa5814
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * Created by Vadim Semenov on 30-03-2014. */ public class TaskC implements Runnable { private Output solve(Input input) { for (int i = 1; i <= input.b; i++) { for (int j = 1; j < i; j++) { int k = i - j; int aa = input.a * input.a - j * j; int aaa = (int) Math.sqrt(aa); if (aaa * aaa != aa) continue; int bb = input.b * input.b - i * i; int bbb = (int) Math.sqrt(bb); if (bbb * bbb != bb) continue; if (k * k + (aaa + bbb) * (aaa + bbb) != input.a * input.a + input.b * input.b) continue; Output output = new Output(); output.x1 = 0; output.y1 = k; output.x2 = aaa; output.y2 = i; output.x3 = aaa + bbb; output.y3 = 0; return output; } } Output output = new Output(); output.x1 = Integer.MIN_VALUE; return output; } private Input read(InputReader in) { Input input = new Input(); input.a = in.nextInt(); input.b = in.nextInt(); input.check(); return input; } private void write(PrintWriter out, Output output) { if (output.x1 == Integer.MIN_VALUE) { out.println("NO"); } else { out.println("YES"); out.println(output.x1 + " " + output.y1); out.println(output.x2 + " " + output.y2); out.println(output.x3 + " " + output.y3); } } private static class Input { int a, b; void check() { if (a > 1000 || b > 1000) { throw new RuntimeException(); } if (a > b) { int t = a; a = b; b = t; } } } private static class Output { int x1, x2, x3, y1, y2, y3; } @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; File inputFile = new File("taskc.in"); File outputFile = new File("taskc.out"); if (inputFile.exists() && inputFile.canRead()) { try { inputStream = new FileInputStream(inputFile); outputStream = new FileOutputStream(outputFile); } catch (IOException e) { e.printStackTrace(); } } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Input input = read(in); Output output = solve(input); write(out, output); in.close(); out.close(); } public static void main(String[] args) { new TaskC().run(); } public static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line = null; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } public void close() { tokenizer = null; try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
df489870b1f194e987454e621900b0d4
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.List; import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author desc */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class P { int x, y; } public void solve(int testNumber, Scanner in, PrintWriter out) { int ta = in.nextInt(); int tb = in.nextInt(); int a = Math.min(ta, tb); int b = Math.max(ta, tb); int c2 = b * b - a * a; List<P> pa = findPair(a); List<P> pb = findPair(b); List<P> pc = findPair2(c2); for (P a1 : pa) { for (P b1 : pb) { if (a1.x * b1.x == a1.y * b1.y && a1.y != b1.y) { out.println("YES"); out.println("0 0"); out.println((-1 * a1.x) + " " + a1.y); out.println(b1.x + " " + b1.y); return; } } for (P b1 : pc) { if (a1.x * b1.x == a1.y * b1.y && a1.y != b1.y) { out.println("YES"); out.println("0 0"); out.println((-1 * a1.x) + " " + a1.y); out.println(b1.x + " " + b1.y); return; } } } out.print("NO"); } List<P> findPair(int c){ List<P> ps = new ArrayList<>(); for (int i = 1; i < 1001 && i < c; i++) { for (int j = 1; j < 1001 && i * i + j * j <= c * c; j++) { if (i * i + j * j == c * c) { P p = new P(); p.x = i; p.y = j; ps.add(p); } } } return ps; } List<P> findPair2(int c2){ List<P> ps = new ArrayList<>(); for (int i = 1; i < 1001; i++) { for (int j = 1; j < 1001 && i * i + j * j <= c2; j++) { if (i * i + j * j == c2) { P p = new P(); p.x = i; p.y = j; ps.add(p); } } } return ps; } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
9a912d2547236b5b6f8caf0fc51ecbef
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; import java.awt.Point; import java.io.*; import java.math.BigInteger; public class C1 { FastScanner in; PrintWriter out; public int gcd(int a, int b) { while (b !=0) { int tmp = a % b; a = b; b = tmp; } return a; } public void solve() throws IOException { int a = in.nextInt(); int b = in.nextInt(); int a2 = a * a; int bFound = 0; for(int x = 1; x < a; x++) { double y = Math.sqrt(a2 - x * x); int yf = (int)y; if(y == yf) { int g = gcd(x, yf); int bx = (int)(-y / g); int by = (int)(x / g); double bLen = Math.sqrt(bx * bx + by * by); int bLenF = (int)bLen; if(bLen == bLenF && b % bLenF == 0) { int bxFound = (int)(-y / g * b / bLenF); int byFound = (int)(x / g * b / bLenF); int cx = x - bxFound; int cy = yf - byFound; if(cx != 0 && cy != 0) { bFound = 1; out.println("YES"); out.println("" + 0 + " " + 0); out.println("" + x + " " + yf); out.println("" + bxFound + " " + byFound); break; } } } } if(bFound == 0) { out.print("NO"); } } public void run() { try { //in = new FastScanner(new File("sum.in")); //out = new PrintWriter(new File("sum.out")); in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++){ array[i] = nextInt(); } return array; } long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++){ array[i] = nextLong(); } return array; } BigInteger nextBigInteger() { return new BigInteger(next()); } Point nextIntPoint() { int x = nextInt(); int y = nextInt(); return new Point(x, y); } Point[] nextIntPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = nextIntPoint(); } return array; } List<Integer>[] readGraph(int vertexNumber, int edgeNumber, boolean undirected) { List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index) { graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0) { int from = nextInt() - 1; int to = nextInt() - 1; graph[from].add(to); if(undirected) graph[to].add(from); } return graph; } } public static void main(String[] arg) { new C1().run(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
9a5b9b1032017c0998099363ce792103
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Triangle { static class Point { long x, y; Point(long x, long y) { this.x = x; this.y = y; } public long sqDist(Point o) { long xDiff = Math.abs(this.x - o.x); long yDiff = Math.abs(this.y - o.y); return xDiff * xDiff + yDiff * yDiff; } public boolean diff(Point o) { return this.x != o.x && this.y != o.y; } public void change(int type) { this.x = Math.abs(this.x); this.y = Math.abs(this.y); if (type == 1) { this.x *= -1; } else if (type == 2) { this.x *= -1; this.y *= -1; } else if (type == 3) { this.y *= -1; } } } static boolean isPerfect(long x) { long y = (long) Math.sqrt(x); return y * y == x; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new StringTokenizer(""); int a = nxtInt(); int b = nxtInt(); long c2 = a * a + b * b; boolean done = false; for (long x1 = 1; x1 < a && !done; x1++) { long y1 = a * a - x1 * x1; if (isPerfect(y1)) { y1 = (long) Math.sqrt(y1); Point one = new Point(x1, y1); for (long x2 = 1; x2 < b && !done; x2++) { long y2 = b * b - x2 * x2; if (isPerfect(y2)) { y2 = (long) Math.sqrt(y2); Point two = new Point(x2, y2); for (int type = 0; type < 4 && !done; type++) { one.change(type); two.change((type + 1) % 4); if (one.diff(two) && one.sqDist(two) == c2) { done = true; out.println("YES"); out.println("0 0"); out.println(one.x + " " + one.y); out.println(two.x + " " + two.y); } } } } } } if (!done) out.println("NO"); br.close(); out.close(); } static BufferedReader br; static StringTokenizer sc; static PrintWriter out; static String nxtTok() throws IOException { while (!sc.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; sc = new StringTokenizer(s.trim()); } return sc.nextToken(); } static int nxtInt() throws IOException { return Integer.parseInt(nxtTok()); } static long nxtLng() throws IOException { return Long.parseLong(nxtTok()); } static double nxtDbl() throws IOException { return Double.parseDouble(nxtTok()); } static int[] nxtIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nxtInt(); return a; } static long[] nxtLngArr(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nxtLng(); return a; } static char[] nxtCharArr() throws IOException { return nxtTok().toCharArray(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
d7f0c21490686b8b90f3150f66c42ee5
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.*; import java.util.*; public class C { BufferedReader br; StringTokenizer in; PrintWriter out; int b; final double eps = 0.00001; final double pi = 3.141592653; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new C().run(); } long[] check(int x, int y) { double phi = Math.atan2((double)y, (double)x); double newphi1 = phi + pi / 2; double newphi2 = phi - pi / 2; double newmod = (double)b; double x1 = newmod * Math.cos(newphi1); double y1 = newmod * Math.sin(newphi1); if (Math.abs(x1 - Math.round(x1)) < eps && Math.abs(y1 - Math.round(y1)) < eps) { long[] res = new long[2]; res[0] = Math.round(x1); res[1] = Math.round(y1); return res; } else { double x2 = newmod * Math.cos(newphi1); double y2 = newmod * Math.sin(newphi1); if (Math.abs(x2 - Math.round(x2)) < eps && Math.abs(y2 - Math.round(y2)) < eps) { long[] res = new long[2]; res[0] = Math.round(x1); res[1] = Math.round(y1); return res; } else { long[] res = new long[2]; res[0] = Long.MAX_VALUE; return res; } } } public void solve() throws IOException { int a = nextInt(); b = nextInt(); for (int i = -a; i < a + 1; i++) { for (int j = -a; j < a + 1; j++) { if (i != 0 && j != 0 && i * i + j * j == a * a) { long[] res = check(i, j); if (res[0] != Long.MAX_VALUE) { if (i != 0 && res[0] != i && res[0] != 0 && j != 0 && res[1] != j && res[1] != 0) { out.println("YES"); out.println(0 + " " + 0); out.println(i + " " + j); out.println(res[0] + " " + res[1]); out.flush(); System.exit(0); } } } } } out.println("NO"); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
40e8c91f941146b5d47fd93fec1e9bab
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; public class C { Scanner in = new Scanner(System.in); void run() { int a = in.nextInt(); int b = in.nextInt(); int b2 = b * b; for (int x = b - 1; x > 0; x--) { int x2 = x * x; if (x2 >= b2) { break; } int y = (int) (Math.round(Math.sqrt(b2 - x2)) + 0.1); if (y * y + x2 != b2) { continue; } int ys = (int) (Math.round(a * x / (double) b) + 0.1); int xs = (int) (Math.round(a * y / (double) b) + 0.1); if (xs * xs + ys * ys != a * a) { continue; } int dx = x + xs; int dy = y - ys; if (dy == 0 || dx == 0 || x == 0 || y == 0 || xs == 0 || ys == 0) { continue; } if (dx * dx + dy * dy == a * a + b2) { System.out.println("YES"); System.out.println("0 0"); System.out.println(x + " " + y); System.out.println((-xs) + " " + ys); return; } } System.out.println("NO"); } public static void main(String... args) { new C().run(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
26d932c51e70a78acbc51516d4601797
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Scanner; public class C239 { public class solution { int x1; int y1; int x2; int y2; int x3; int y3; public solution() { x1 = x2 = y1 = y2 = x3 = y3 = 0; } } static boolean perfect(int num) { double s = Math.sqrt(num); int ss = (int) s; if (ss * ss == num) return true; else return false; } public void run() { Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); ArrayList<Integer> x = new ArrayList<Integer>(); ArrayList<Integer> y = new ArrayList<Integer>(); for (int xx = 0 - a-a; xx <= a+a; xx++) { int inter = a * a - xx * xx; if (!perfect(inter) || xx == 0) continue; int sq = (int) Math.sqrt(inter); int y1 = sq; int y2 = -sq; if (y1 != 0) { x.add(xx); y.add(y1); } if (y2 != 0) { x.add(xx); y.add(y2); } } ArrayList<solution> all = new ArrayList<solution>(); for (int i = 0; i < x.size(); i++) { int xnow = x.get(i); int ynow = y.get(i); for (int xx = xnow - b-b; xx <= xnow + b+b; xx++) { int inter = b * b - (xnow - xx) * (xnow - xx); if (!perfect(inter)) continue; int sq = (int) Math.sqrt(inter); int yy1 = ynow - sq; if ((yy1 - ynow) * ynow == -xnow * (xx - xnow) && yy1 != 0) { solution newsol = new solution(); newsol.x1 = 0; newsol.y1 = 0; newsol.x2 = xnow; newsol.y2 = ynow; newsol.x3 = xx; newsol.y3 = yy1; all.add(newsol); } int yy2 = sq + ynow; if ((yy2 - ynow) * ynow == -xnow * (xx - xnow) && yy2 !=0) { solution newsol = new solution(); newsol.x1 = 0; newsol.y1 = 0; newsol.x2 = xnow; newsol.y2 = ynow; newsol.x3 = xx; newsol.y3 = yy2; all.add(newsol); } } } if (all.size() == 0) System.out.println("NO"); else { System.out.println("YES"); solution here = all.get(0); System.out.println(here.x1 + " " + here.y1); System.out.println(here.x2 + " " + here.y2); System.out.println(here.x3 + " " + here.y3); } } public static void main(String[] args) { // TODO Auto-generated method stub new C239().run(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
6f27df35ae13c4980108f619f33d7f25
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Scanner; public class C239 { public class solution { int x1; int y1; int x2; int y2; int x3; int y3; public solution() { x1 = x2 = y1 = y2 = x3 = y3 = 0; } } static boolean perfect(int num) { double s = Math.sqrt(num); int ss = (int) s; if (ss * ss == num) return true; else return false; } public void run() { Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); ArrayList<Integer> x = new ArrayList<Integer>(); ArrayList<Integer> y = new ArrayList<Integer>(); for (int xx = 0 - a-a; xx <= a+a; xx++) { int inter = a * a - xx * xx; if (!perfect(inter) || xx == 0) continue; int sq = (int) Math.sqrt(inter); int y1 = sq; int y2 = -sq; if (y1 != 0) { x.add(xx); y.add(y1); } if (y2 != 0) { x.add(xx); y.add(y2); } } ArrayList<solution> all = new ArrayList<solution>(); for (int i = 0; i < x.size(); i++) { int xnow = x.get(i); int ynow = y.get(i); for (int xx = xnow - b-b; xx <= xnow + b+b; xx++) { int inter = b * b - (xnow - xx) * (xnow - xx); if (!perfect(inter) || xx == 0) continue; int sq = (int) Math.sqrt(inter); int yy1 = ynow - sq; if ((yy1 - ynow) * ynow == -xnow * (xx - xnow) && yy1 != 0) { solution newsol = new solution(); newsol.x1 = 0; newsol.y1 = 0; newsol.x2 = xnow; newsol.y2 = ynow; newsol.x3 = xx; newsol.y3 = yy1; all.add(newsol); } int yy2 = sq + ynow; if ((yy2 - ynow) * ynow == -xnow * (xx - xnow) && yy2 !=0) { solution newsol = new solution(); newsol.x1 = 0; newsol.y1 = 0; newsol.x2 = xnow; newsol.y2 = ynow; newsol.x3 = xx; newsol.y3 = yy2; all.add(newsol); } } } if (all.size() == 0) System.out.println("NO"); else { System.out.println("YES"); solution here = all.get(0); System.out.println(here.x1 + " " + here.y1); System.out.println(here.x2 + " " + here.y2); System.out.println(here.x3 + " " + here.y3); } } public static void main(String[] args) { // TODO Auto-generated method stub new C239().run(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
76acd072883d57c4d3997116916c72f6
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { final boolean isFileIO = false; BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String delim = " "; public static void main(String[] args) { new Thread(null, new Main(), "", 268435456).start(); } public void run() { try { initIO(); solve(); out.close(); } catch(Exception e) { e.printStackTrace(System.err); System.exit(-1); } } public void initIO() throws IOException { if(!isFileIO) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String nextToken() throws IOException { if(!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(delim); } String readLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void solve() throws IOException { int a, b; a = nextInt(); b = nextInt(); int[] sqrt = new int[1000001]; Arrays.fill(sqrt, -1); for(int i = 1; i <= 1000; i++) { sqrt[i * i] = i; } for(int x_1 = -a; x_1 <= a; x_1++) { int y_1 = a * a - x_1 * x_1; if(sqrt[y_1] == -1) continue; for(int x_2 = -b; x_2 <= b; x_2++) { int y_2 = b * b - x_2 * x_2; if(sqrt[y_2] == -1) continue; if(b * b + a * a == (x_1 - x_2) * (x_1 - x_2) + (sqrt[y_1] - sqrt[y_2]) * (sqrt[y_1] - sqrt[y_2])) { if(sqrt[y_1] != sqrt[y_2]) { out.println("YES"); out.println("0 0"); out.println(x_1 + " " + sqrt[y_1]); out.println(x_2 + " " + sqrt[y_2]); return; } } } } out.println("NO"); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
b6d3e0f3478aae63a2d6f4c7d2e0a9b4
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.awt.geom.Point2D; import java.util.*; public class Main { Scanner in = new Scanner(System.in); public static void main(String[] args) { new Main(); } public Main(){ new C().doIt(); } class C{ double EPS = 1.0e-8; Point2D normalVector1(Point2D p){ return new Point2D.Double(-p.getY(), p.getX()); } Point2D normalVector2(Point2D p){ return new Point2D.Double(p.getY(), -p.getX()); } // boolean void doIt(){ int sss = in.nextInt(); int ss = in.nextInt(); int a = Math.max(sss, ss),b = Math.min(sss, ss); double ritu = 1.0*a/b; // System.out.println(ritu); for(int i=0;i<=b;i++)for(int s=0;s<=b;s++){ if(i==a||s==b)continue; if(i==b||s==a)continue; Point2D p = new Point2D.Double(i,s); if(p.distance(new Point2D.Double())!=b)continue; Point2D p2 = normalVector1(p); Point2D p4 = new Point2D.Double((int)(p2.getX()*ritu),(int)(p2.getY()*ritu)); Point2D p3 = normalVector2(p); Point2D p5 = new Point2D.Double((int)(p3.getX()*ritu),(int)(p3.getY()*ritu)); // System.out.println(p); // System.out.println(i+" "+s); // System.out.println(p4); // System.out.println(p5); // System.out.println(); if(Math.abs(p4.distance(new Point2D.Double())-a)<EPS){ if(p.getX()==p4.getX())continue; if(p.getY()==p4.getY())continue; System.out.println("YES"); System.out.println("0 0"); System.out.println((int)p.getX()+" "+(int)p.getY()); System.out.println((int)p4.getX()+" "+(int)p4.getY()); return; }else if(Math.abs(p5.distance(new Point2D.Double())-a)<EPS){ if(p.getX()==p5.getX())continue; if(p.getY()==p5.getY())continue; System.out.println("YES"); System.out.println("0 0"); System.out.println((int)p.getX()+" "+(int)p.getY()); System.out.println((int)p5.getX()+" "+(int)p5.getY()); return; } } System.out.println("NO"); } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
263e49ccf1aac085aceed23964cc7111
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.io.*; import java.util.StringTokenizer; import java.util.Vector; /** * Created by Praveen on 3/30/14. */ public class B { public static void main(String[]args) { InputReader in=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int a=in.nextInt(); int b=in.nextInt(); Vector<Integer> x1=new Vector<Integer>(); Vector<Integer> y1=new Vector<Integer>(); Vector<Integer> x2=new Vector<Integer>(); Vector<Integer> y2=new Vector<Integer>(); for(int x=-a;x<=a;x++) for(int y=-a;y<=a;y++) { if((long)x*x+(long)y*y==a*a) { x1.add(x); y1.add(y); } } for(int x=-b;x<=b;x++) for(int y=-b;y<=b;y++) { if((long)x*x+(long)y*y==b*b) { x2.add(x); y2.add(y); } } boolean ok=false; int ans1x=0,ans1y = 0,ans2x=0,ans2y=0; for(int i=0;i<x1.size();i++) { if(ok)break; for(int j=0;j<x2.size();j++) { if(x1.get(i).equals(x2.get(j))&&y1.get(i).equals(y2.get(j))) continue; if(x1.get(i)==0||y1.get(i)==0||x2.get(j)==0||y2.get(j)==0) continue; if((x1.get(i).equals(x2.get(j))||(y1.get(i).equals(y2.get(j))))) continue; if(perpendicular(x1.get(i),y1.get(i),x2.get(j),y2.get(j))) { ok=true; ans1x=x1.get(i); ans1y=y1.get(i); ans2x=x2.get(j); ans2y=y2.get(j); break; } } } if(ok) { out.println("YES"); out.println(ans1x + " " + ans1y); out.println("0 " + "0"); out.println(ans2x+" "+ans2y); } else out.println("NO"); out.close(); } private static boolean perpendicular(long x1,long y1, long x2, long y2) { if(y1*y2==-x1*x2)return true; return false; } private static long solve(long a, long b) { long res=1; while(b>0) { if((b&1)>0) { res=(res*a); res%=10; } a=(a*a); a%=10; b>>=1; } return res; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
749abaa8b3e8bbcf9a7f9bd425ffa8c0
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.awt.geom.Point2D; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int y1,x1,y2,x2; int cnt = 0; for(int i = 1;i < n;i++){ if(cnt == 1)break; double k = n*n - i*i; k=Math.sqrt(k); if(k == (int)k){ y1 = (int)k; x1 = i; for(int j = -1;j > -m;j--){ k = m*m - j*j; k=Math.sqrt(k); if(k == (int)k){ y2 = (int)k; x2 = j; if(n*n+m*m == (int)(Point2D.distanceSq(x1, y1, x2, y2))){ if(x1 != x2 && y1 != y2){ System.out.println("YES"); System.out.println(x1 + " " + y1); System.out.println(x2 + " " + y2); System.out.println(0 + " " + 0); cnt = 1; break; } } } } if(cnt == 1)break; } } if(cnt == 0){ System.out.println("NO"); } } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
a9f896c930dae030d46f9977f6a2c45f
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class C_Triangle_r239d2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r1 = sc.nextInt(); int r2 = sc.nextInt(); HashMap<Integer, Integer> sqrt = new HashMap<Integer, Integer>(); for(int i = 1; i <= 1011; i++) { sqrt.put(i*i, i); } ArrayList<int[]> p1 = new ArrayList<int[]>(); for(int x = -r1; x <= r1; x++) { int y2 = r1*r1 - x*x; Integer y = sqrt.get(y2); if(y != null) { if(x == 0 || y == 0) continue; p1.add(new int[]{x, y}); p1.add(new int[]{x, -y}); } } ArrayList<int[]> p2 = new ArrayList<int[]>(); for(int x = -r2; x <= r2; x++) { int y2 = r2*r2 - x*x; Integer y = sqrt.get(y2); if(y != null) { if(x == 0 || y == 0) continue; p2.add(new int[]{x, y}); p2.add(new int[]{x, -y}); } } for(int c1[] : p1) { for(int c2[]: p2) { int x1 = c1[0], y1 = c1[1], x2 = c2[0], y2 = c2[1]; if(Math.abs(y1)*Math.abs(x2) == Math.abs(y2)*Math.abs(x1)) { continue; } if(x1*x2 + y1*y2 != 0) continue; if(y1 == y2 || x1 == x2) continue; System.out.println("YES"); System.out.println(0+" "+0); System.out.println(x1+" "+y1); System.out.println(x2+" "+y2); return; } } System.out.println("NO"); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
2b1af829471f6757760400797be34ff8
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.math.*; import static java.util.Arrays.*; import static java.lang.Math.*; import static java.util.Collections.*; import static java.lang.System.out; public class Main { static boolean LOCAL = System.getSecurityManager() == null; Scanner in = new Scanner(System.in); void run() { int a = in.nextInt(), b = in.nextInt(); int[][] A = work(a); if (!fit(A, a, b)) { out.println("NO"); } } private boolean fit(int[][] as, int a, int b) { for (int[] A : as) { int g = gcd(A[0], A[1]); int r = a / g; if (b % r == 0) { int bt = b / r; if (A[0] / g * bt == A[1]) continue; out.println("YES"); out.println("0 0"); out.println(A[0] + " " + A[1]); out.println(-A[1] / g * bt + " " + A[0] / g * bt); return true; } } return false; } private int gcd(int i, int j) { while (j != 0) { int t = i; i = j; j = t % j; } if (i < 0) i = -i; return i; } private int[][] work(int a) { ArrayList<int[]> res = new ArrayList<int[]>(); for (int i = 1; i < a; i++) { for (int j = 1; j < a; j++) { if (i * i + j * j == a * a) res.add(new int[] {i, j}); } } return res.toArray(new int[0][]); } void debug(Object... os) { System.err.println(deepToString(os)); } public static void main(String[] args) { if (LOCAL) { try { System.setIn(new FileInputStream("./../in")); } catch (IOException e) { LOCAL = false; } } new Main().run(); } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String string) { st = new StringTokenizer(string); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } String next() { hasNext(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
527931542f18a7cf1aa3398f4bfd85db
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.math.*; import static java.util.Arrays.*; import static java.lang.Math.*; import static java.util.Collections.*; import static java.lang.System.out; public class Main { static boolean LOCAL = System.getSecurityManager() == null; Scanner in = new Scanner(System.in); void run() { int a = in.nextInt(), b = in.nextInt(); int[][] A = work(a); if (!fit(A, a, b)) { out.println("NO"); } } private boolean fit(int[][] as, int a, int b) { for (int[] A : as) { int g = gcd(A[0], A[1]); int r = a / g; if (b % r == 0) { int bt = b / r; if (A[0] / g * bt == A[1]) continue; out.println("YES"); out.println("0 0"); out.println(A[0] + " " + A[1]); out.println(-A[1] / g * bt + " " + A[0] / g * bt); return true; } } return false; } private int gcd(int i, int j) { while (j != 0) { int t = i; i = j; j = t % j; } if (i < 0) i = -i; return i; } private int[][] work(int a) { ArrayList<int[]> res = new ArrayList<int[]>(); for (int i = 1; i < a; i++) { int j2 = a * a - i * i; int j = (int) (sqrt(j2)); while (j * j < j2) j++; while (j * j > j2) j--; if (j * j == j2) res.add(new int[] {i, j}); } return res.toArray(new int[0][]); } void debug(Object... os) { System.err.println(deepToString(os)); } public static void main(String[] args) { if (LOCAL) { try { System.setIn(new FileInputStream("./../in")); } catch (IOException e) { LOCAL = false; } } new Main().run(); } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String string) { st = new StringTokenizer(string); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } String next() { hasNext(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
d6dd05df6873f03e0a0d575790dc71c2
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); for (int x_a = 1; x_a <= a; x_a++) { double yy_a = a*a - x_a*x_a; double y_a = Math.sqrt(yy_a); if (y_a == (int) y_a) { for (int x_b = 1; x_b <= b; x_b++) { double yy_b = b*b - x_b*x_b; double y_b = Math.sqrt(yy_b); if (y_b == (int) y_b) { if (x_a * x_b == y_a * y_b && x_a != -x_b && y_a != y_b) { System.out.println("YES"); System.out.println(0 + " " + 0); System.out.println(-x_a + " " + (int)y_a); System.out.println(x_b + " " + (int)y_b); return; } } } } } System.out.println("NO"); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
b4af96542be1ac4db143a0337b644d93
train_000.jsonl
1396162800
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { new C(); } public C() { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); boolean found = false; int solx1 = 0; int solx2 = 0; int soly1 = 0; int soly2 = 0; for (int i = 1; i < a && !found; i++) { int j = (int) Math.sqrt(a * a - i * i); if ((Math.sqrt(a * a - i * i) - (double) j) > 0.999999) j++; if (a * a == (i * i + j * j)) { int x = b * i / a; int y = b * j / a; if (x * a == b * i && y * a == b * j) { if (j != x) { found = true; solx1 = i; soly1 = j; solx2 = -1 * y; soly2 = x; } } } } if (found) { System.out.println("YES"); System.out.println("0 0"); System.out.println(solx1 + " " + soly1); System.out.println(solx2 + " " + soly2); } else System.out.println("NO"); sc.close(); } }
Java
["1 1", "5 5", "5 10"]
1 second
["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"]
null
Java 7
standard input
[ "geometry", "math" ]
a949ccae523731f601108d4fa919c112
The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space.
1,600
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
standard output
PASSED
1b018d96fb6f971029ca0250ffe2c3d2
train_000.jsonl
1593873900
This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing $$$a$$$, $$$b$$$, and $$$c$$$ stones, where $$$a$$$, $$$b$$$, and $$$c$$$ are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer $$$y$$$ and provides it to the second player. The second player adds $$$y$$$ stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $$$1000$$$ turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // +8 public class cf1375f { public static void main(String[] args) throws IOException { long a[][] = new long[3][2]; r(); for (int i = 0; i < 3; ++i) { a[i][0] = nl(); a[i][1] = i; } sort(a, (aa, bb) -> Long.compare(aa[0], bb[0])); prln("First"); flush(); long delta = a[2][0] - a[0][0]; prln(delta); flush(); int ind = ri() - 1; for (int i = 0; i < 3; ++i) { if (a[i][1] == ind) { a[i][0] += delta; break; } } sort(a, (aa, bb) -> Long.compare(aa[0], bb[0])); delta = 2 * a[2][0] - a[1][0] - a[0][0]; prln(delta); flush(); ind = ri() - 1; for (int i = 0; i < 3; ++i) { if (a[i][1] == ind) { a[i][0] += delta; break; } } sort(a, (aa, bb) -> Long.compare(aa[0], bb[0])); delta = a[1][0] - a[0][0]; prln(delta); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
Java
["5 2 6\n\n\n3\n\n0"]
1 second
["First\n2\n\n3"]
NoteIn the sample input, the piles initially have $$$5$$$, $$$2$$$, and $$$6$$$ stones. Harris decides to go first and provides the number $$$2$$$ to Anton. Anton adds $$$2$$$ stones to the third pile, which results in $$$5$$$, $$$2$$$, and $$$8$$$.In the next turn, Harris chooses $$$3$$$. Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
Java 11
standard input
[ "math", "constructive algorithms", "games", "interactive" ]
351c6fb0a9d1bbb29387c5b7ce8c7f28
The first line of input contains three distinct positive integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) Β β€” the initial number of stones in piles $$$1$$$, $$$2$$$, and $$$3$$$ respectively.
2,600
null
standard output
PASSED
563e10e72387c586edfd4e808585260f
train_000.jsonl
1593873900
This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing $$$a$$$, $$$b$$$, and $$$c$$$ stones, where $$$a$$$, $$$b$$$, and $$$c$$$ are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer $$$y$$$ and provides it to the second player. The second player adds $$$y$$$ stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $$$1000$$$ turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1375f { public static void main(String[] args) throws IOException { long a[] = rla(3), op; prln("First"); flush(); prln(op = maxof(a)); flush(); a[ri() - 1] += op; long b[] = {a[0], a[1], a[2]}; sort(b); prln(op = 2 * b[2] - b[1] - b[0]); flush(); a[ri() - 1] += op; sort(a); prln(a[1] - a[0]); flush(); rline(); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["5 2 6\n\n\n3\n\n0"]
1 second
["First\n2\n\n3"]
NoteIn the sample input, the piles initially have $$$5$$$, $$$2$$$, and $$$6$$$ stones. Harris decides to go first and provides the number $$$2$$$ to Anton. Anton adds $$$2$$$ stones to the third pile, which results in $$$5$$$, $$$2$$$, and $$$8$$$.In the next turn, Harris chooses $$$3$$$. Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
Java 11
standard input
[ "math", "constructive algorithms", "games", "interactive" ]
351c6fb0a9d1bbb29387c5b7ce8c7f28
The first line of input contains three distinct positive integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) Β β€” the initial number of stones in piles $$$1$$$, $$$2$$$, and $$$3$$$ respectively.
2,600
null
standard output
PASSED
0e786332ba7f15d094a64b442a0cc8e5
train_000.jsonl
1593873900
This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing $$$a$$$, $$$b$$$, and $$$c$$$ stones, where $$$a$$$, $$$b$$$, and $$$c$$$ are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer $$$y$$$ and provides it to the second player. The second player adds $$$y$$$ stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $$$1000$$$ turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static void solve() throws Exception { long a[] = {scanInt(), scanInt(), scanInt()}; out.println("First"); long min = min(min(a[0], a[1]), a[2]); long max = max(max(a[0], a[1]), a[2]); long y = max - min; out.println(y); out.flush(); int i = scanInt() - 1; if (i < 0) { return; } a[i] += y; long sum = a[0] + a[1] + a[2]; y = 3 * a[i] - sum; out.println(y); out.flush(); i = scanInt() - 1; if (i < 0) { return; } a[i] += y; y = min(a[i] - a[(i + 1) % 3], a[i] - a[(i + 2) % 3]); out.println(y); out.flush(); i = scanInt() - 1; if (i < 0) { return; } throw new AssertionError(); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["5 2 6\n\n\n3\n\n0"]
1 second
["First\n2\n\n3"]
NoteIn the sample input, the piles initially have $$$5$$$, $$$2$$$, and $$$6$$$ stones. Harris decides to go first and provides the number $$$2$$$ to Anton. Anton adds $$$2$$$ stones to the third pile, which results in $$$5$$$, $$$2$$$, and $$$8$$$.In the next turn, Harris chooses $$$3$$$. Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
Java 11
standard input
[ "math", "constructive algorithms", "games", "interactive" ]
351c6fb0a9d1bbb29387c5b7ce8c7f28
The first line of input contains three distinct positive integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) Β β€” the initial number of stones in piles $$$1$$$, $$$2$$$, and $$$3$$$ respectively.
2,600
null
standard output