exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
5485e6782da37da8f22191e6fa7da85a
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws NumberFormatException, IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[]parts = br.readLine().split("\\s+"); int[]res = new int[n]; int max = Integer.MIN_VALUE; int maxIdx = -1; for(int i = 0; i < parts.length; i++){ int tmp = Integer.parseInt(parts[i]); res[i] = tmp; if(tmp>max){ max=tmp; maxIdx = i; } } if(max==1){ res[maxIdx] = 2; } else { res[maxIdx] = 1; } Arrays.sort(res); for(int i : res){ System.out.print(i + " "); } System.out.println(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
0c7d8d987d097208a5ed69be4243325b
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; public class cf135a { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = in.nextInt(); Integer[] v = new Integer[n]; for(int i=0; i<n; i++) v[i] = in.nextInt(); Arrays.sort(v); if(v[n-1] == 1) v[n-1] = 2; else v[n-1] = 1; Arrays.sort(v); for(int x : v) out.print(x + " "); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if(!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if(!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
97ea2668baacc573f8ab7ae6f4db31af
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class solver { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new solver().solve(); } int thr (int first, int second) { int raz = first - second; if(raz < 0) { raz += 3; } return raz; } void solve() { int n = in.nextInt(); int[]tab = new int[n]; for (int i = 0; i < n; i++) { tab[i] = in.nextInt(); } int max = getMax(tab); for (int i = 0; i < tab.length; i++) { if (tab[i] == max) { if (tab[i] == 1) { tab[i] = 2; break; } else { tab[i] = 1; break; } } } Arrays.sort(tab); for (int i = 0; i < tab.length; i++) { System.out.print(tab[i] + " "); } } int getMax(int[]ar) { int n = Integer.MIN_VALUE; for (int i = 0; i < ar.length; i++) { if (ar[i] > n) n = ar[i]; } return n; } long toTen(String s) { long c = 0; int step = 1; for (int i = 0; i < s.length(); i++) { c += step * (s.charAt(i) - 48); step*=3; } return c; } String toThree(int n) { String s = ""; while (n > 0) { s += n%3; n /= 3; } if (s.equals("")) s+= "0"; return s; } public int min (int a, int b) { if (a < b) return a; else return b; } public int max (int a, int b) { if (a > b) return a; else return b; } // public TreeMap<Long, Integer> factorize(long n) { // TreeMap<Long, Integer> factors = new TreeMap<Long, Integer>(); // for (long d = 2; n > 1;) { // int cnt = 0; // while (n % d == 0) { // cnt++; // n /= d; // } // if (cnt > 0) { // factors.put(d, cnt); // } // d += (d == 2) ? 1 : 2; // if (d * d > n) { // d = n; // } // } // return factors; // } public long[] getDivisors(long n) { List<Long> list = new ArrayList<Long>(); for (int i = 1; (long) i * i <= n; i++) { if (n % i == 0) { list.add((long) i); if (i * i != n) { list.add(n / i); } } } long[] res = new long[list.size()]; for (int i = 0; i < res.length; i++) { res[i] = list.get(i); } Arrays.sort(res); return res; } // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } long lcm(long a, long b) { return a / gcd(a, b) * b; } boolean [] getEratothfenSieve(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; ++i) if (prime[i]) if (i * i <= n) for (int j=i*i; j<=n; j+=i) prime[j] = false; return prime; } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
200099c9646effcf765c70f445acc7ed
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Replacemente { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); int[] v = new int[n]; String[] aux = bf.readLine().split("\\s"); for (int i = 0; i < n; ++i) { v[i] = Integer.parseInt(aux[i]); } Arrays.sort(v); if (v[n - 1] == 1) { v[n - 1] = 2; } else { v[n - 1] = 1; } Arrays.sort(v); for (int i = 0; i < n; i++) { System.out.print(v[i]+" "); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
4b665d481c79a50c16ec8ad61f67f4d2
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Replacement { void run() throws Exception { BufferedReader bfd = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(bfd.readLine()); Integer[] arr = new Integer[n]; StringTokenizer tk = new StringTokenizer(bfd.readLine()); Integer mx = -1, mxIdx = -1; for (int i = 0; i < n; ++i) { arr[i] = Integer.parseInt(tk.nextToken()); if (arr[i] > mx) { mxIdx = i; mx = arr[i]; } } if (mx > 1) { arr[mxIdx] = 1; Arrays.sort(arr); } else { arr[n - 1] = 2; } System.out.print(arr[0]); for (int i = 1; i < n; ++i) System.out.print(" " + arr[i]); System.out.println(); } public static void main(String[] args) throws Exception { new Replacement().run(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
394a7190af0d3ecb138b4dd61a931365
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Replacement { void run() throws Exception { BufferedReader bfd = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(bfd.readLine()); StringTokenizer tk = new StringTokenizer(bfd.readLine()); Integer arr[] = new Integer[n]; for(int i = 0; i < n; ++i) arr[i] = Integer.parseInt(tk.nextToken()); int i = 0; for(; i < n; ++i) if(arr[i] != 1) break; if(i==n) { // all 1's arr[n-1] = 2; } else { int mx = 0, mxI = -1; for(i = 0; i < n; ++i) if(arr[i] > mx) { mx = arr[i]; mxI = i; } arr[mxI] = 1; Arrays.sort(arr); } for(i = 0; i < n - 1; ++i) System.out.print(arr[i] + " "); System.out.println(arr[i]); } public static void main(String[] args) throws Exception { new Replacement().run(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
acdd0dba9ef2ea28df771960a344b52b
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); boolean flag = true; List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) { list.add(scanner.nextInt()); if (list.get(i) != 1) flag = false; } if (flag) { if (n == 1) { System.out.println(2); }else { System.out.print(1); for (int i = 1; i < n-1; i ++) { System.out.print(" "); System.out.print(1); } System.out.println(" 2"); } return; } Collections.sort(list); System.out.print(1); for (int i = 1; i < list.size(); i ++) { System.out.print(" "); System.out.print(list.get(i - 1)); } System.out.println(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
19b63b1160a769af620eebf9ad873682
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); boolean check=false; Vector<Long> mas=new Vector<Long>(); for(int i=0; i<n; i++) { Long l=in.nextLong(); mas.add(l); if (l!=1) check=true; } Collections.sort(mas); if (mas.size()>1) { out.print("1 "); for(int i=0; i<mas.size()-2;i++) { out.print(mas.elementAt(i)); out.print(" "); } if (!check) out.print("2"); else out.print(mas.elementAt(mas.size()-2)); } else { if (mas.elementAt(0)==1) out.print("2"); else out.print("1"); } out.close(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
d6c4d4d3119fcfc6805dc28f422f2401
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
//package c; import java.util.*; import java.io.*; public class Main { BufferedReader in; StringTokenizer str = null; private int nextInt() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return Integer.parseInt(str.nextToken()); } private void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = nextInt(); int a[] = new int[n]; int cnt = 0; for(int i=0;i<n;i++) { a[i] = nextInt(); if (a[i] == 1) cnt++; } if (n == 1){ if (a[0] == 1) out.println(2); else out.println(1); out.close(); return; } Arrays.sort(a); out.print(1 + " "); for(int i=0;i<n-2;i++) out.print(a[i] + " "); if (cnt == n) out.println(2); else out.println(a[n-2]); out.close(); } public static void main(String[] args) throws Exception{ new Main().run(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
99c852754a054638475258d90d9403ba
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; public class Replacement { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); int x=Integer.parseInt(reader.readLine()); String st[]=reader.readLine().split(" "); int []f=new int[st.length]; for(int i=0;i<st.length;i++) f[i]=Integer.parseInt(st[i]); Arrays.sort(f); if(f[f.length-1]!=1) { f[f.length-1]=1; } else f[f.length-1]+=1; Arrays.sort(f); StringBuilder ans=new StringBuilder(""); for(int i=0;i<st.length;i++) ans.append(f[i]+" "); System.out.println(ans); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
47c3203f61ad4f98bbfebb39f77ee5e8
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.*; public class C { BufferedReader in; PrintStream out; StringTokenizer tok; public C() throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { int n = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); Arrays.sort(a); int j = 0; boolean allones = true; for(int i = 0; i < a.length; i++) if(a[i]!= 1) { allones = false; break; } if(allones) { for(int i = 0; i < a.length-1; i++) out.println(1); out.println(2); } else { for(;j < a.length && a[j]==1; j++) out.println(1); if(j < a.length) out.println(1); for(int i = j; i < a.length-1; i++) out.println(a[i]); } } public static void main(String[] args) throws NumberFormatException, IOException { new C(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
fac7161224b4426f3e5e5851f6a0cdea
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
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.Arrays; public class ProblemC implements Runnable{ public void solve() throws IOException{ int n=intArr()[0]; int[] x=intArr(); Arrays.sort(x); if(x[x.length-1]!=1){ for(int i=0;i<x.length;i++){ if(i>0){ out.print(" "); out.print(x[i-1]); } else { out.print("1"); } } } else { for(int i=0;i<x.length;i++){ if(i<x.length-1){ out.print(x[i]); out.print(" "); } else { out.print("2"); } } } out.println(); } public static void main(String[] args){ new ProblemC().run(); } @Override public void run(){ // System.out.println("trying to solve"); try{ in=new BufferedReader(new InputStreamReader(stdin)); out=new PrintWriter(stdout); solve(); in.close(); out.close(); } catch (Exception ex){ ex.printStackTrace(); System.exit(1); } } BufferedReader in; PrintWriter out; int[] intArr() throws IOException { String[] arr=nextLine().split("\\s"); int[] res=new int[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Integer.parseInt(arr[i]); return res; } long[] longArr() throws IOException { String[] arr=nextLine().split("\\s"); long[] res=new long[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Long.parseLong(arr[i]); return res; } double[] doubleArr() throws IOException { String[] arr=nextLine().split("\\s"); double[] res=new double[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Double.parseDouble(arr[i]); return res; } String nextLine() throws IOException { return in.readLine(); } InputStream stdin; OutputStream stdout; public ProblemC(){ stdin=System.in; stdout=System.out; } public ProblemC(InputStream stdin, OutputStream stdout){ this.stdin=stdin; this.stdout=stdout; } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
c052a90dfe14809d4fec90e1dd5b592f
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class C { static StreamTokenizer st; public static void main(String[] args) throws IOException{ st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[]a = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } Arrays.sort(a); a[0] = 1; for (int i = 1; i <= n; i++) { if (i==n) { if (a[i]==1) { pw.print(2+" "); } else { pw.print(a[i-1]+""); } } else { pw.print(a[i-1]+" "); } } pw.close(); } private static int nextInt() throws IOException{ st.nextToken(); return (int) st.nval; } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
5ba97a1fb3c32b647f1beb4796130ae2
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedInputStream; import java.util.Arrays; import static java.lang.Math.*; public class C136C { public void solve() throws Exception { int n = nextInt(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = nextInt(); } Arrays.sort(arr); if (arr[arr.length - 1] == 1) { for (int i = 0; i < arr.length - 1; i++) { print(1 + " "); } println(2); } else { print(1 + " "); for (int i = 0; i < arr.length - 1; i++) { print(arr[i] + " "); } } } // ------------------------------------------------------ void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } void print(Object... os) { if (os != null && os.length > 0) System.out.print(os[0].toString()); for (int i = 1; i < os.length; ++i) System.out.print(" " + os[i].toString()); } void println(Object... os) { print(os); System.out.println(); } BufferedInputStream bis = new BufferedInputStream(System.in); String nextWord() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c > ' ') { sb.append(c); c = (char) bis.read(); } return new String(sb); } String nextLine() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c != '\n' && c != '\r') { sb.append(c); c = (char) bis.read(); } return new String(sb); } int nextInt() throws Exception { return Integer.parseInt(nextWord()); } long nextLong() throws Exception { return Long.parseLong(nextWord()); } public static void main(String[] args) throws Exception { new C136C().solve(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
a08695560b246dd6d5cfce042fbcb615
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { new Exchange().solve(); } } class Exchange { public void solve() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] ar = new int[n]; int maxid = -1, max = Integer.MIN_VALUE; for (int i = 0; i < n; ++i) { ar[i] = in.nextInt(); if (ar[i] >= max) { max = ar[i]; maxid = i; } } if (max != 1) { ar[maxid] = 1; } else { ar[maxid] = 2; } Arrays.sort(ar); for (int a : ar) { out.print(a + " "); } out.close(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
e3cd0ae5ba6a5242200f8077a49d4b41
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class C implements Runnable { private void Solution() throws IOException { int n = nextInt(), max = 0, maxi = 0; ArrayList<Integer> mas = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int num = nextInt(); if (num > max) { max = num; maxi = i; } mas.add(num); } mas.remove(maxi); mas.add(max == 1 ? 2 : 1); Collections.shuffle(mas); Collections.sort(mas); for (int i = 0; i < n; i++) System.out.print(mas.get(i) + " "); } public static void main(String[] args) { new C().run(); } BufferedReader in; StringTokenizer tokenizer; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; Solution(); in.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(in.readLine()); return tokenizer.nextToken(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
05c655c30e2f58fa38d0943180893023
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
//package codeforces; /** * * @author Siddharth */ import java.io.*; public class MergeSortArray { private long[] theArray; private int nElems; public MergeSortArray(int max) { theArray = new long[max]; nElems = 0; } public void insert(long value) { theArray[nElems] = value; // insert it nElems++; // increment size } public void display() { for (int j = 0; j < nElems-1; j++) System.out.print(theArray[j] + " "); System.out.println(""); } public void display2() { for (int j = 0; j < nElems-2; j++) System.out.print(theArray[j] + " "); // System.out.println(""); } public void mergeSort() { long[] workSpace = new long[nElems]; recMergeSort(workSpace, 0, nElems - 1); } private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) { if (lowerBound == upperBound) // if range is 1, return; // no use sorting else { // find midpoint int mid = (lowerBound + upperBound) / 2; // sort low half recMergeSort(workSpace, lowerBound, mid); // sort high half recMergeSort(workSpace, mid + 1, upperBound); // merge them merge(workSpace, lowerBound, mid + 1, upperBound); } } private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) { int j = 0; // workspace index int lowerBound = lowPtr; int mid = highPtr - 1; int n = upperBound - lowerBound + 1; // # of items while (lowPtr <= mid && highPtr <= upperBound) if (theArray[lowPtr] < theArray[highPtr]) workSpace[j++] = theArray[lowPtr++]; else workSpace[j++] = theArray[highPtr++]; while (lowPtr <= mid) workSpace[j++] = theArray[lowPtr++]; while (highPtr <= upperBound) workSpace[j++] = theArray[highPtr++]; for (j = 0; j < n; j++) theArray[lowerBound + j] = workSpace[j]; } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); String s[]=br.readLine().split(" "); int maxSize = t; // array size MergeSortArray arr = new MergeSortArray(maxSize); // create the array boolean all=true; for(int i=0;i<t;i++) { if(Integer.parseInt(s[i])!=1)all=false; arr.insert(Integer.parseInt(s[i])); } // arr.display(); arr.mergeSort(); if(t==1&&all==true) System.out.println("2 "); else{ System.out.print("1 "); if(!all) arr.display(); else { arr.display2();System.out.println("2 ");} } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
d4bb2befc24535ba6ba34b276e8107f9
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF136C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] ls = new int[n]; int max = 0; for (int i = 0; i < n; i++) { ls[i] = sc.nextInt(); max = Math.max(max, ls[i]); } if (max == 1 && n == 1) { System.out.println(2); return; } Arrays.sort(ls); StringBuilder sb = new StringBuilder("1"); for (int i = 0; i < n-1; i++) { sb.append(" ").append(max == 1 && i == n-2 ? 2 : ls[i]); } System.out.println(sb); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
6539b83acd38c63fc87de8485c74acc9
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Substitution implements Runnable { private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter pw; void solve() throws IOException { int n = nextInt(); int[] array = new int[n]; for (int i = 0 ; i < n; ++i) { array[i] = nextInt(); } Arrays.sort(array); for (int i = 0; i < n; ++i) { int ans = array[i]; if (ans == 1 && i == n-1) ans = 2; else if (i != 0) ans = array[i-1]; else ans = 1; pw.print(ans + " "); } } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); solve(); pw.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Substitution().run(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } // // long nextLong() throws IOException { // return Long.parseLong(nextToken()); // } // // double nextDouble() throws IOException { // return Double.parseDouble(nextToken()); // } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
a0fc80d678ae608e208080348627900f
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String... args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); int[] x = new int[n]; int max=0, pos=-1; for(int i=0; i<n; i++) { x[i]=sc.nextInt(); if (max<x[i]) { max=x[i]; pos=i; } } if (max==1) { x[pos]=2; } else { x[pos]=1; } Arrays.sort(x); for(int i=0; i<n; i++) System.out.print(x[i]+" "); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
bf210fdab412f14905492167192ff25c
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Rou97_C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long []a = new long[n]; long max = -1; int ind = -1; for(int i =0 ;i < n;i++) { a[i] = in.nextLong(); if(a[i] > max) { max = a[i]; ind = i; } } if(a[ind] == 1)a[ind] = 2; else a[ind] = 1; Arrays.sort(a); System.out.print(a[0]); for(int i =1 ; i < n;i++) { System.out.print(" "+a[i]); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
534098a94ba4b30876e8649aa5f0adbd
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package codeforces; import java.util.Scanner; /** * * @author DELL */ public class Replacement { public static void Merge(int A[], int p, int q, int r) { // System.out.println("\nin merge " + p + " " + q + " " + r); int n1 = (q - p + 1); int n2 = (r - q); int L[] = new int[n1]; int R[] = new int[n2]; int i = 0, j = 0, k = 0; for (i = 1; i <= n1; ++i) { L[i - 1] = A[p + i - 1]; } for (j = 1; j <= n2; ++j) { R[j - 1] = A[q + j]; } i = 0; j = 0; k = p; while (L.length != i && R.length != j) { if (L[i] <= R[j]) { A[k] = L[i]; i++; k++; } else { A[k] = R[j]; j++; k++; } } while (L.length != i) { A[k] = L[i]; i++; k++; } while (R.length != j) { A[k] = R[j]; j++; k++; } } public static void Sort(int A[], int p, int r) { int q = 0; //System.out.println("p= "+p+" r= "+r); if (p < r) { q = (p + r) / 2; // System.out.print("q= "+q); // System.out.println("\nin sort " + p + " " + q + " " + r); Sort(A, p, q); Sort(A, (q + 1), r); Merge(A, p, q, r); } } public static void solve() { Scanner nera = new Scanner(System.in); int n = nera.nextInt(); int k = 1; int A[] = new int[n]; int i = 0; while (i < n) { A[i] = nera.nextInt(); if (A[i] != 1) { k = 0; } ++i; } Sort(A, 0, A.length - 1); if (k == 1) { for (int h = 0; h < n - 1; ++h) { System.out.print("1 "); } System.out.println("2"); } else { System.out.print("1"); i = 1; while (i < n) { System.out.print(" "); System.out.print(A[i - 1]); ++i; } } } public static void main(String[] args) { solve(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
6b481d70d021d40be401d0f58c85cec4
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedInputStream; import java.util.Arrays; import java.util.Scanner; public class Replacement { //Round #97 - Replacement public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int arrayLen = sc.nextInt(); int[] numbers = new int[arrayLen]; for(int i = 0; i < numbers.length; i++) { numbers[i] = sc.nextInt(); } Arrays.sort(numbers); int max = numbers[numbers.length - 1]; if(max == 1) { numbers[numbers.length - 1] = 2; } else { numbers[numbers.length - 1] = 1; } Arrays.sort(numbers); for(int i = 0; i < numbers.length - 1; i++) { System.out.print(numbers[i] + " "); } System.out.println(numbers[numbers.length - 1]); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
4e92e63fb16ded88c0d447f5010a534e
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Test { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int n; n = nextInt(); int mas[] = new int[n]; for(int i=0;i<n;i++) { mas[i]=nextInt(); } Arrays.sort(mas); if(mas[n-1]==1) { mas[n-1]=2; } else { mas[n-1]=1; } Arrays.sort(mas); for(int i=0;i<n;i++) { writer.print(mas[i]+" "); } writer.println(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
0db9cb386c399e45c625f96f19579359
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); Arrays.sort(a); if (a[a.length - 1] == 1) { a[a.length - 1] = 2; } else a[a.length - 1] = 1; Arrays.sort(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
352c9f6298575ecb33d80f6ea47a47f8
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
//package beta97; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static BufferedReader br; public static StringTokenizer inp; public static PrintWriter out; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); inp = new StringTokenizer(br.readLine()); int a[] = new int[n]; for(int i = 0 ; i < n ; i++)a[i] = nextInt(); Arrays.sort(a); boolean ok = true; for(int i = 0 ; i < n ; i++){if(a[i] != 1){ok = false;;break;}} if(ok)a[n-1] = 2; else { for(int i =n-1 ; i >0 ; i--) { a[i] = a[i-1]; }a[0] = 1; } System.out.print(a[0]); for(int i = 1 ; i < n ; i++) System.out.print(" " + a[i]); System.out.println(); br.close(); out.close(); } public static int nextInt(){return Integer.parseInt(inp.nextToken());} public static long nextLong(){return Long.parseLong(inp.nextToken());} public static double nextDouble(){return Double.parseDouble(inp.nextToken());} public static String next(){return inp.nextToken();} }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
6f0231551c66cb1f8f90081ad7eeac6a
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class three { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(buf.readLine()); int[] a = new int[n]; String[] s = buf.readLine().split(" "); int index = 0; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(s[i]); if (max < a[i]) { max = a[i]; index = i; } } if(a[index]!=1) a[index]=1; else a[index]=2; Arrays.sort(a); StringBuilder ss = new StringBuilder(""); for (int i=0;i<n;i++) ss.append(a[i]+" "); System.out.println(ss.substring(0, ss.length()-1)); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
e884e2337be07328bd94e929b65b20e0
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.*; import java.io.*; public class C97C{ static BufferedReader br; public static void main(String args[])throws Exception{ br=new BufferedReader(new InputStreamReader(System.in)); long n=toLong(); long num[]=toLongArray(); if(n==1){ if(num[0]>1) prln("1"); else prln("2"); return; } int min=(int)Math.min(1000, n/2); num=shuf(num,min); Arrays.sort(num); if(num[(int)n-1]==1){ for(int i=0;i<n-1;i++){ pr(num[i]+" "); } prln("2"); return; } pr("1 "); for(int i=0;i<n-2;i++){ pr(num[i]+" "); } prln(num[(int)n-2]); } public static long[] shuf(long a[], int x){ long temp=0; int r1=0; int r2=0; Random rn=new Random(); for(int i=0;i<x;i++ ){ //r1=(int)(Math.random()*a.length); //r2=(int)(Math.random()*a.length); r1=rn.nextInt(a.length); r2=rn.nextInt(a.length); temp=a[r1]; a[r1]=a[r2]; a[r2]=temp; } return a; } /****************************************************************/ public static int[] toIntArray()throws Exception{ String str[]=br.readLine().split(" "); int k[]=new int[str.length]; for(int i=0;i<str.length;i++){ k[i]=Integer.parseInt(str[i]); } return k; } public static int toInt()throws Exception{ return Integer.parseInt(br.readLine()); } public static long[] toLongArray()throws Exception{ String str[]=br.readLine().split(" "); long k[]=new long[str.length]; for(int i=0;i<str.length;i++){ k[i]=Long.parseLong(str[i]); } return k; } public static long toLong()throws Exception{ return Long.parseLong(br.readLine()); } public static double[] toDoubleArray()throws Exception{ String str[]=br.readLine().split(" "); double k[]=new double[str.length]; for(int i=0;i<str.length;i++){ k[i]=Double.parseDouble(str[i]); } return k; } public static double toDouble()throws Exception{ return Double.parseDouble(br.readLine()); } public static String toStr()throws Exception{ return br.readLine(); } public static String[] toStrArray()throws Exception{ String str[]=br.readLine().split(" "); return str; } public static void pr(Object st){ System.out.print(st); } public static void prln(Object st){ System.out.println(st); } /****************************************************************/ }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
e46ffd3809c94850a74da184cb8029a6
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; import java.util.spi.AbstractResourceBundleProvider; public class Main { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static FastReader f = new FastReader(); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb = new StringBuilder(""); private static int m = (int)1e9 + 7; static int MAX = 500005; static int[] inputArray(int n) throws IOException { int[] a = new int[n]; for(int i = 0 ; i < n ; i++) { a[i] = f.nextInt(); } return a; } static int gcd(int a , int b) { if(a % b == 0) { return b; } return gcd(b , a % b); } static long moduloInversePrime(long a) { long ans = modPow(a , m - 2); //System.out.println("modulo inverse of " + a + " -> " + ans); return ans; } static long mult(long a, long b) { return (a * (long)b % m); } static long modPow(long a, int step) { long ans = 1; while(step != 0) { if((step & 1) != 0) ans = mult(ans , a); a = mult(a , a); step >>= 1; } return ans; } static long longModulus(long x , long m) { long d = x / m; return x - d * m; } static boolean isTriangle(int a , int b , int c) { return a + b > c && a + c > b && c + b > a; } private static void swap(int arr[] , int i , int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static class Container { int x , y , noise; Container(int x , int y , int noise) { this.x = x; this.y = y; this.noise = noise; } @Override public String toString() { return "x: " + x + " y: " + y + " noise: " + noise; } } static char reverse(char c) { if(c == '0') { return 1; } return '0'; } public static void main(String[] args) throws IOException { int t = f.nextInt(); while(t-- != 0) { int n = f.nextInt(); String s = f.nextToken(); ArrayList<Integer> segments = new ArrayList<>(); int prev = s.charAt(0); int len = 1 , i; for(i = 1 ; i < n ; i++) { if(s.charAt(i) != prev) { prev = s.charAt(i); segments.add(len); len = 1; } else { len++; } } segments.add(len); int nextNonOne = 0; i = 0; n = segments.size(); while(i < n && segments.get(i) == 1) { i++; } nextNonOne = i; if(nextNonOne == n) { System.out.println((int)Math.ceil(n/2d)); continue; } int res = 0; for(i = 0 ; i < n ; i++) { if(nextNonOne < i || segments.get(nextNonOne) == 1) { int j = nextNonOne + 1; while(j < n && segments.get(j) == 1) { j++; } nextNonOne = j; } if (segments.get(i) == 1) { if (nextNonOne != n) segments.set(nextNonOne, segments.get(nextNonOne) - 1); else { res += (int)Math.ceil((n - i)/2d); break; } } res++; } System.out.println(res); } } } /* 2 3 3 1 1 1 3 2 0 2 1 1 2 2 0 2 1 4 5 5 1 1 5 5 */
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
29f4bf03511c82a602adf70836567193
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class StringDeletion { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); for (int n = 0; n < t; n++ ) { reader.readLine(); String s = reader.readLine(); char current = s.charAt(0); int currentSize = 1; int positionCounter = 0; List<Group> groups = new ArrayList<>(); for (int i = 1; i < s.length(); i++){ if (current == s.charAt(i)){ currentSize++; } else { groups.add(new Group(currentSize, positionCounter)); positionCounter++; currentSize = 1; current = s.charAt(i); } } groups.add(new Group(currentSize, positionCounter)); TreeSet<Group> ordered = new TreeSet<>((a,b) -> Integer.compare(a.position, b.position)); ordered.addAll(groups); TreeSet<Group> largest = new TreeSet<>((a,b) -> { if (a.oSize > 1 && b.oSize > 1 || a.oSize == b.oSize){ return Integer.compare(a.position, b.position); } return Integer.compare(b.oSize,a.oSize); }); largest.addAll(groups); int moves = 0; /* if (n == 105) System.out.println(s);*/ while (!ordered.isEmpty()) { moves++; Group currentL = largest.first(); currentL.size--; if (currentL.size == 0) { largest.remove(currentL); ordered.remove(currentL); } else { largest.remove(currentL); currentL.oSize = currentL.size; largest.add(currentL); } if (!ordered.isEmpty()) { Group currentO = ordered.first(); largest.remove(currentO); ordered.remove(currentO); } } System.out.println(moves); } } public static class Group { int size; int position; int oSize; Group(int size, int position){ this.size = size; this.oSize = size; this.position = position; } @Override public String toString() { return "Group{" + "size=" + size + ", position=" + position + ", oSize=" + oSize + '}'; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
b19a701aeff67c2ca28aef4a46a57c5b
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class StringDeletion { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); for (int n = 0; n < t; n++ ) { reader.readLine(); String s = reader.readLine(); char current = s.charAt(0); int currentSize = 1; int positionCounter = 0; List<Group> groups = new ArrayList<>(); for (int i = 1; i < s.length(); i++){ if (current == s.charAt(i)){ currentSize++; } else { groups.add(new Group(currentSize, positionCounter)); positionCounter++; currentSize = 1; current = s.charAt(i); } } groups.add(new Group(currentSize, positionCounter)); TreeSet<Group> ordered = new TreeSet<>((a,b) -> Integer.compare(a.position, b.position)); ordered.addAll(groups); TreeSet<Group> largest = new TreeSet<>((a,b) -> { if (a.oSize > 1 && b.oSize > 1 || a.oSize == b.oSize){ return Integer.compare(a.position, b.position); } return Integer.compare(b.oSize,a.oSize); }); largest.addAll(groups); int moves = 0; /* if (n == 105) System.out.println(s);*/ while (!ordered.isEmpty()) { moves++; Group currentL = largest.first(); currentL.size--; if (currentL.size == 0) { largest.remove(currentL); ordered.remove(currentL); } if (currentL.size == 1){ largest.remove(currentL); currentL.oSize = currentL.size; largest.add(currentL); } if (!ordered.isEmpty()) { Group currentO = ordered.first(); largest.remove(currentO); ordered.remove(currentO); } } System.out.println(moves); } } public static class Group { int size; int position; int oSize; Group(int size, int position){ this.size = size; this.oSize = size; this.position = position; } @Override public String toString() { return "Group{" + "size=" + size + ", position=" + position + ", oSize=" + oSize + '}'; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
e74020b15152f951989114534b3ddb55
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class StringDeletion { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(reader.readLine()); for (int n = 0; n < t; n++ ) { reader.readLine(); String s = reader.readLine(); char current = s.charAt(0); int currentSize = 1; int positionCounter = 0; List<Group> groups = new ArrayList<>(); for (int i = 1; i < s.length(); i++){ if (current == s.charAt(i)){ currentSize++; } else { groups.add(new Group(currentSize, positionCounter)); positionCounter++; currentSize = 1; current = s.charAt(i); } } groups.add(new Group(currentSize, positionCounter)); TreeSet<Group> ordered = new TreeSet<>(Comparator.comparingInt(Group::getPosition)); ordered.addAll(groups); TreeSet<Group> largest = new TreeSet<>((a,b) -> { if (a.oSize > 1 && b.oSize > 1 || a.oSize == b.oSize){ return Integer.compare(a.position, b.position); } return Integer.compare(b.oSize,a.oSize); }); largest.addAll(groups); int moves = 0; while (!ordered.isEmpty()) { moves++; Group currentL = largest.first(); currentL.size--; if (currentL.size == 0) { largest.remove(currentL); ordered.remove(currentL); } if (currentL.size == 1){ largest.remove(currentL); currentL.oSize = currentL.size; largest.add(currentL); } if (!ordered.isEmpty()) { Group currentO = ordered.first(); largest.remove(currentO); ordered.remove(currentO); } } sb.append(moves).append('\n'); } System.out.println(sb.toString()); } public static class Group { int size; int position; int oSize; public int getPosition() { return this.position; } Group(int size, int position){ this.size = size; this.oSize = size; this.position = position; } @Override public String toString() { return "Group{" + "size=" + size + ", position=" + position + ", oSize=" + oSize + '}'; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
4c50f230138f3081dae057d19295951e
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; public class Main { static void solve() { int t = ni(); for(int i=0;i<t;i++)testCase(); } static void testCase() { int n = ni(); var s = ns(n); var ls = new ArrayList<Integer>(); int cnt = 1; var q = new ArrayDeque<Integer>(); for(int i=0;i<n-1;i++) { if(s[i] != s[i+1]) { ls.add(cnt); if(cnt >= 2)q.add(ls.size()-1); cnt = 1; }else { cnt++; } } ls.add(cnt); if(cnt >= 2)q.add(ls.size()-1); int ans = 0; for(int i=0;i<ls.size();i++) { ans ++; int now = ls.get(i); if(now >= 2) continue; while(!q.isEmpty() && q.peek() <= i) { q.poll(); } while(!q.isEmpty() && ls.get(q.peek()) == 1){ q.poll(); } if(q.isEmpty()) { i++; continue; } int idx = q.peek(); ls.set(idx, ls.get(idx)-1); if(ls.get(idx) == 1)q.poll(); } out.println(ans); } //constants static final int inf = Integer.MAX_VALUE / 2; static final long linf = Long.MAX_VALUE / 3; static final double dinf = Double.MAX_VALUE / 3; static final long mod = (long) 1e9 + 7; static final int[] dx = { -1, 0, 1, 0 }, dy = { 0, -1, 0, 1 }, dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final double eps = 1e-10; //libraries static long[] cum(int a[]) { long[] cum = new long[a.length + 1]; for(int i=0;i<a.length;i++) cum[i+1] = cum[i] + a[i]; return cum; } static long[] cum(long a[]) { long[] cum = new long[a.length + 1]; for(int i=0;i<a.length;i++) cum[i+1] = cum[i] + a[i]; return cum; } static void reverse(int ar[]) { int len = ar.length; for (int i = 0; i < len / 2; i++) { int t = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = t; } } static void reverse(long ar[]) { int len = ar.length; for (int i = 0; i < len / 2; i++) { long t = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = t; } } static void reverse(double ar[]) { int len = ar.length; for (int i = 0; i < len / 2; i++) { double t = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = t; } } static void reverse(char ar[]) { int len = ar.length; for (int i = 0; i < len / 2; i++) { char t = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = t; } } static String getReverse(String s) { StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } static <T> void reverse(T[] ar) { int len = ar.length; for (int i = 0; i < len / 2; i++) { T t = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = t; } } static int[] concat(int x, int arr[]) { int ret[] = new int[arr.length + 1]; System.arraycopy(arr, 0, ret, 1, ret.length - 1); ret[0] = x; return ret; } static int[] concat(int arr[], int x) { int ret[] = new int[arr.length + 1]; System.arraycopy(arr, 0, ret, 0, ret.length - 1); ret[ret.length - 1] = x; return ret; } static long[] concat(long x, long arr[]) { long ret[] = new long[arr.length + 1]; System.arraycopy(arr, 0, ret, 1, ret.length - 1); ret[0] = x; return ret; } static long[] concat(long arr[], long x) { long ret[] = new long[arr.length + 1]; System.arraycopy(arr, 0, ret, 0, ret.length - 1); ret[ret.length - 1] = x; return ret; } static char[] concat(char x, char arr[]) { char ret[] = new char[arr.length + 1]; System.arraycopy(arr, 0, ret, 0, ret.length - 1); ret[ret.length - 1] = x; return ret; } static char[] concat(char arr[], char x) { char ret[] = new char[arr.length + 1]; System.arraycopy(arr, 0, ret, 0, ret.length - 1); ret[ret.length - 1] = x; return ret; } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int max(int x, int y, int z) { x = Math.max(x, y); x = Math.max(x, z); return x; } static int min(int x, int y, int z) { x = Math.min(x, y); x = Math.min(x, z); return x; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } static long max(long x, long y, long z) { x = Math.max(x, y); x = Math.max(x, z); return x; } static long min(long x, long y, long z) { x = Math.min(x, y); x = Math.min(x, z); return x; } static double max(double x, double y) { return Math.max(x, y); } static double min(double x, double y) { return Math.min(x, y); } static double max(double x, double y, double z) { x = Math.max(x, y); x = Math.max(x, z); return x; } static double min(double x, double y, double z) { x = Math.min(x, y); x = Math.min(x, z); return x; } static void sort(int[] ar) { Arrays.sort(ar); } static void sort(long[] ar) { Arrays.sort(ar); } static void sort(double[] ar) { Arrays.sort(ar); } static void sort(char[] ar) { Arrays.sort(ar); } static void rsort(int[] ar) { Arrays.sort(ar); int len = ar.length; for (int i = 0; i < len / 2; i++) { int tmp = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = tmp; } } static void rsort(long[] ar) { Arrays.sort(ar); int len = ar.length; for (int i = 0; i < len / 2; i++) { long tmp = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = tmp; } } static void rsort(double[] ar) { Arrays.sort(ar); int len = ar.length; for (int i = 0; i < len / 2; i++) { double tmp = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = tmp; } } static void rsort(char[] ar) { Arrays.sort(ar); int len = ar.length; for (int i = 0; i < len / 2; i++) { char tmp = ar[i]; ar[i] = ar[len - 1 - i]; ar[len - 1 - i] = tmp; } } static void fill(int arr[], int x) { Arrays.fill(arr, x); } static void fill(long arr[], long x) { Arrays.fill(arr, x); } static void fill(boolean arr[], boolean x) { Arrays.fill(arr, x); } static void fill(double arr[], double x) { Arrays.fill(arr, x); } static void fill(int arr[][], int x) { for (int i = 0; i < arr.length; i++) Arrays.fill(arr[i], x); } static void fill(long arr[][], long x) { for (int i = 0; i < arr.length; i++) Arrays.fill(arr[i], x); } static void fill(double arr[][], double x) { for (int i = 0; i < arr.length; i++) Arrays.fill(arr[i], x); } static void fill(boolean arr[][], boolean x) { for (int i = 0; i < arr.length; i++) Arrays.fill(arr[i], x); } //MOD culc static long plus(long x, long y) { long res = (x + y) % mod; return res < 0 ? res + mod : res; } static long sub(long x, long y) { long res = (x - y) % mod; return res < 0 ? res + mod : res; } static long mul(long x, long y) { long res = (x * y) % mod; return res < 0 ? res + mod : res; } static long div(long x, long y) { long res = x * pow(y, mod - 2) % mod; return res < 0 ? res + mod : res; } static long pow(long x, long y) { if (y < 0) return 0; if (y == 0) return 1; if (y % 2 == 1) return (x * pow(x, y - 1)) % mod; long root = pow(x, y / 2); return root * root % mod; } public static void main(String[] args) throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); } //input static InputStream is; static PrintWriter out; static String INPUT = ""; private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } @SuppressWarnings("unused") private static double nd() { return Double.parseDouble(ns()); } @SuppressWarnings("unused") private static char nc() { return (char) skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static 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); } @SuppressWarnings("unused") private static char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } @SuppressWarnings("unused") private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } @SuppressWarnings("unused") private static long[] nla(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } @SuppressWarnings("unused") private static int[][] na(int n, int m){ int[][] res = new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { res[i][j] = ni(); } } return res; } @SuppressWarnings("unused") private static long[][] nla(int n, int m){ long[][] res = new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { res[i][j] = nl(); } } return res; } private static 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 static 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(); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
a81d8e35f270d3545bbb5a4fb4e13685
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; public class Main { InputStream is; PrintWriter out; String INPUT = ""; void solve(int TC) throws Exception { int n = ni(); char[] s = ns(n); int one=0,zero=0; ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<n;i++){ if(s[i]=='1'){ ++one; if(zero!=0){ al.add(zero); } zero=0; }else{ ++zero; if(one!=0){ al.add(one); } one=0; } } if(one!=0){ al.add(one); }else if(zero!=0){ al.add(zero); } int e=0; int ans = 0; int pt = 1; int N = al.size(); if(N==1) { pn(1); return; } for(int i=0;i<N;i++) { if(pt<i) pt=i; while(pt<N && al.get(pt)==1) { ++pt; } e = al.get(i); if(e>1) { ++ans; }else{ if(pt<N) al.set(pt, al.get(pt)-1); else ++i; ++ans; } } pn(ans); } boolean TestCases = true; public static void main(String[] args) throws Exception { new Main().run(); } void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} int bits(long n){return (n==0)?0:(1+bits(n&(n-1)));} void sort(int[] a) { int n = a.length; ArrayList<Integer> al = new ArrayList<>(); for(int i: a) al.add(i); Collections.sort(al); for(int i=0;i<n;i++) a[i] = al.get(i); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int T = TestCases ? ni() : 1; for(int t=1;t<=T;t++) solve(t); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o);out.flush(); } double PI = 3.141592653589793238462643383279502884197169399; 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(); } } 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(); } } double nd() { return Double.parseDouble(ns()); } char nc() { return (char)skip(); } int BUF_SIZE = 1024 * 8; byte[] inbuf = new byte[BUF_SIZE]; int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } 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); } void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
9deddf412f5e2d0c68b98089a9db513d
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.io.*; public class _1430_D { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); for(int i = 0; i < t; i++) { int n = Integer.parseInt(in.readLine()); String s = in.readLine(); int[] arr = new int[n]; for(int j = 0; j < n; j++) { arr[j] = Character.getNumericValue(s.charAt(j)); } ArrayList<Integer> stretches = new ArrayList<Integer>(); int[] groups = new int[n]; for(int j = 0; j < n; j++) { if(j == 0) { stretches.add(1); groups[j] = 0; }else { if(arr[j] == arr[j - 1]) { int end = stretches.size() - 1; stretches.set(end, stretches.get(end) + 1); groups[j] = groups[j - 1]; }else { stretches.add(1); groups[j] = groups[j - 1] + 1; } } } int[] arrs = new int[stretches.size()]; for(int j = 0; j < stretches.size(); j++) { arrs[j] = stretches.get(j); } int pointer = 0; int count = 0; int group = 0; for(int j = 0; j < n; j++) { while(pointer < arrs.length && arrs[pointer] == 1) { pointer++; } if(pointer >= arrs.length) { break; } arrs[pointer] -= 1; if(groups[pointer] <= group) { pointer = group + 1; } count++; group++; } int total = arrs.length - group; int add = total / 2; if(total % 2 != 0) { add += 1; } out.println(count + add); } in.close(); out.close(); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
ad5a6b154633e2ecd05ed99ef8ab618e
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<27).start(); } static class Pair{ int f; int s; //boolean n; Pair(int f,int s){ this.f=f; this.s=s; //this.n = n; } public static Comparator<Pair> wc = new Comparator<Pair>(){ public int compare(Pair e1,Pair e2){ //reverse order //if(e1.n)return 1; //else if(e2.n) return -1; if(e1.s < e2.s) return -1; // 1 for swaping. else if (e1.s > e2.s) return 1; else { return 0; } } }; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } ////recursive BFS public static int bfsr(int s,ArrayList<Integer>[] a,boolean[] b,int[] pre){ b[s]=true; int p = 1; int n = pre.length -1; int t = a[s].size(); int max = 1; for(int i=0;i<t;i++){ int x = a[s].get(i); if(!b[x]){ //dist[x] = dist[s] + 1; int xz = (bfsr(x,a,b,pre)); p+=xz; max = Math.max(xz,max); } } //max = Math.max(max,(n-p)); pre[s] = max; return p; } //// iterative BFS public static int bfs(int s,ArrayList<Integer>[] a,int dist,boolean[] b,PrintWriter w){ b[s]=true; int siz = 0; dist--; Queue<Integer> q = new LinkedList<>(); q.add(s); while(q.size()!=0 && dist>0 ){ int i=q.poll(); Iterator<Integer> it = a[i].listIterator(); int z=0; while(it.hasNext() && dist>0){ z=it.next(); if(!b[z]){ b[z]=true; dist--; //dist[z] = dist[i] + 1; siz++; q.add(z); } } } return siz; } public static int lower(int key, int[] a){ int l = 0; int r = a.length-1; int res = 0; while(l<=r){ int mid = (l+r)/2; if(a[mid]<=key){ l = mid+1; res = mid+1; } else{ r = mid -1; } } return res; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); long defaultValue=0; int tc = sc.nextInt(); while(tc-->0){ int n = sc.nextInt(); String s = sc.next()+'.'; int c = 1; //int ans = 1; Queue<Pair> sd = new LinkedList<Pair>(); PriorityQueue<Integer> sn = new PriorityQueue<Integer>(); for(int i=1;i<=n;i++){ char x = s.charAt(i); char y = s.charAt(i-1); if(x==y){ c++; } else{ if(c==1){ sn.add(i-1); } else{ sd.add(new Pair(i-c,c)); } c = 1; } } long ans = 0; boolean f = true; boolean z = false; boolean zz = false; Pair x = new Pair(0,0); int y = -1; while(sd.size()!=0 || sn.size()!=0 || zz || z){ if(x.s==0){ if(sd.size()!=0){ x = sd.poll(); zz = true; } else{ int v = sn.size(); if(z)v++; ans+=((v+1)/2); break; } } if(f){ if(sn.size()!=0){ y = sn.poll(); z = true; } else{ int v = sd.size(); if(zz)v++; ans+=v; break; } } if(y<x.f){ ans++; f = true; z = false; x.s--; if(x.s==1){ sn.add(x.f); x = new Pair(0,0); } } else{ ans++; x = new Pair(0,0); f = false; zz = false; } } w.println(ans); } w.flush(); w.close(); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
96a801042cacd3e0c894bc82dbfba1e4
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1430D extends PrintWriter { CF1430D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1430D o = new CF1430D(); o.main(); o.flush(); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); byte[] cc = sc.next().getBytes(); int[] qu = new int[n]; int cnt = 0; for (int k = 1, i = 1; i <= n; i++) { if (i == n || cc[i] != cc[i - 1]) { qu[cnt++] = k; k = 0; } k++; } int ans = cnt; for (int i = 0, j = 0; i < cnt; i++) { if (j < i) j = i; while (j < cnt && qu[j] == 1) j++; if (j == cnt) { ans = i + (cnt - i + 1) / 2; break; } qu[j]--; } println(ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
5b34b474ec761ff78459ee257d9e5d89
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class A4_1 { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for (int o = 0; o < test; o ++) { int a = scan.nextInt(); String t = scan.next(); ArrayList<Character> list = new ArrayList<>(); ArrayList<Integer> tle = new ArrayList<>(); for (int i = 0; i < a; i++) { list.add(t.charAt(i)); } int hp1 = 0; int hp2 = 1; if (list.size() == 1){tle.add(1);} while (hp2 < list.size()) { if (list.get(hp2) == list.get(hp1)) { hp2 += 1; } else { tle.add(hp2 - hp1); hp1 = hp2; hp2 += 1; } if (hp2 == list.size()) { tle.add(hp2 - hp1); } } //System.out.println(tle.toString()); int ans = 0; int start = 0; int ref = 0; while (start < tle.size()){ boolean flag = false; for (int i = Math.max(ref, start); i < tle.size(); i++){ if (tle.get(i) > 1){tle.set(i, tle.get(i) - 1) ; ref = i;flag = true; break;} } if (!flag){ref = tle.size() - 1;tle.set(tle.size() - 1, tle.get(tle.size() - 1) - 1);} if (tle.get(tle.size() - 1) == 0){tle.remove(tle.size() - 1);} start += 1; ans += 1; // System.out.println(tle.toString() + " " + start + " " + ans); } System.out.println(ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
11fe2bc15adf695c3fcc6f43a2a828b9
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; public class ques5 { public static void main(String[] args)throws Exception{ new ques5().run();} long mod=1000000000+7; void solve() throws Exception { for(int ii=ni();ii>0;ii--) { int n=ni(); String s=ns(); s=s+"x"; ArrayList<Integer> al = new ArrayList<>(); int c=1; for(int i=1;i<n+1;i++) { if(s.charAt(i)!=s.charAt(i-1)) { al.add(c); c=1; } else c++; } int in=0; int ans=0; int len=al.size(); for(int i=0;i<len;i++) { int flag=0; for(int j=in;j<len;j++) { if(al.get(j)>1) { flag=1; al.set(j,al.get(j)-1); in=j; break; } } ans++; if(flag==0) {len--;in=len+1;} if(in==i) in++; } out.println(ans); } } /*IMPLEMENTATION BY AMAN KOTIYAL, FAST INPUT OUTPUT & METHODS BELOW*/ private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; private SpaceCharFilter filter; PrintWriter out; int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } /* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */ long expo(long p,long q) /* (p^q)%mod */ { long z = 1; while (q>0) { if (q%2 == 1) { z = (z * p)%mod; } p = (p*p)%mod; q >>= 1; } return z; } void run()throws Exception { in=System.in; out = new PrintWriter(System.out); solve(); out.flush(); } private int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } private int ni() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); int sgn = 1; if (c == '-') { sgn = -1; c = scan(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = scan(); } while (!isSpaceChar(c)); return res * sgn; } private long nl() throws IOException { long num = 0; int b; boolean minus = false; while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = scan(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = scan(); } } private double nd() throws IOException{ return Double.parseDouble(ns()); } private String ns() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = scan(); } while (!isSpaceChar(c)); return res.toString(); } private String nss() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); return br.readLine(); } private char nc() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); return (char) c; } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhiteSpace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
eb565ca2e51432dcf7f8471a964eb64b
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class CP{ public static OutputStream out=new BufferedOutputStream(System.out); static Scanner sc=new Scanner(System.in); static long MOD=998244353l; static int INF=10000000; static long[] fact; static long[] inv_fact; static int[] rr=new int[]{1, 0, -1, 0}; //rook row move static int[] rc=new int[]{0, 1, 0, -1}; //rook col move //nl-->neew line; //l-->line; //arp-->array print; //arpnl-->array print new line public static void nl(Object o) throws IOException{out.write((o+"\n").getBytes()); } public static void l(Object o) throws IOException{out.write((o+"").getBytes());} public static void arp(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+" ").getBytes()); out.write(("\n").getBytes());} public static void arpnl(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+"\n").getBytes());} public static void scanl(long[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextLong();} public static void scani(int[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextInt();} public static void scan2D(int[][] a,int n,int m) {for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt();} //static variables // public static void main(String[] args) throws IOException{ long sttm=System.currentTimeMillis(); int t=sc.nextInt(); // int t=1; while(t-->0) solve(); out.flush(); } public static void solve() throws IOException{ int n=sc.nextInt(); char[] a=sc.next().toCharArray(); ArrayList<Integer> arrl=new ArrayList<Integer>(); int cnt=0; int flag=a[0]=='0'?0:1; for(int i=0;i<n;i++){ if(flag==0){ if(a[i]=='0'){ cnt++; } else{ arrl.add(cnt); flag=1; cnt=1; } } else{ if(a[i]=='1'){ cnt++; } else{ arrl.add(cnt); flag=0; cnt=1; } } } arrl.add(cnt); int ocnt=0; cnt=0; for(int aa:arrl){ if(aa==1)ocnt++; else{ cnt++; int rem=aa-2; int min=Math.min(rem, ocnt); cnt+=min; ocnt-=min; } } cnt+=(ocnt+1)/2; nl(cnt); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } } class Pair{ int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
ebc310146fdfa60856c8a56e7bdc4e9c
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.io.*; public class D{ 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 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 class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int mod = (int)(1e9+7); public static long pow(long a,long b) { long ans = 1; while(b> 0) { if((b & 1)==1){ ans = (ans*a) % mod; } a = (a*a) % mod; b = b>>1; } return ans; } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int t = in.nextInt(); while(t-- >0) { int n = in.nextInt(); long res = 0; char[] arr = in.nextLine().toCharArray(); int bonus = 0; int i = n-1; while(i>=0) { int size = 0; char cur = arr[i]; while(i>=0 && arr[i]==cur) { size++; i--; } bonus+=(size-1); res++; if(bonus==0 && i==-1) break; if(bonus==0) i--; else bonus--; } out.printLine(res); } out.flush(); out.close(); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
d0b4d27f4182aa187466dd7f9e7c25d6
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; // 111111 public class Main{ static Scanner sc = new Scanner(System.in); static int mod = 1_000_000_007; public static void main(String[] args){ int i = sc.nextInt(); for (int i1 = 0; i1 < i; i1++) solve(); } private static void solve() { int n = sc.nextInt(); char[]chars = sc.next().toCharArray(); int cnt = 0; int last = chars[0]; LinkedList<Cell>con = new LinkedList<>(); LinkedList<Cell>stack = new LinkedList<>(); for(char c : chars){ if(c == last){ cnt++; }else{ Cell e = new Cell(cnt); con.addLast(e); if(cnt > 1) stack.addLast(e); cnt = 1; last = c; } } Cell e = new Cell(cnt); con.addLast(e); if(cnt > 1) stack.addLast(e); int ans = 0; while (!con.isEmpty()){ Cell cell = con.pollFirst(); if(cell.cnt > 1){ stack.pollFirst(); }else if(cell.cnt == 1){ if(!stack.isEmpty()){ stack.peek().cnt--; if(stack.peek().cnt == 1) stack.pollFirst(); }else if(!con.isEmpty()){ con.pollFirst(); } } ans++; } System.out.println(ans); } static class Cell{ int cnt; public Cell(int cnt) { this.cnt = cnt; } } private static int gcb(int a,int b){ if(a == b) return a; if(a < b) return gcb(b,a); if(a % b == 0) return b; return gcb(b,a % b); } private static void printList(List<Long> arr){ for(long i : arr){ System.out.print(i + " "); } System.out.println(); } private static void printArr(int[]arr){ for(int i : arr){ System.out.print(i + " "); } System.out.println(); } private static int[]readArr(int len){ int[]ans = new int[len]; for(int i = 0;i < len;i++){ ans[i] = sc.nextInt(); } return ans; } private static long powmod(long a,long b){ long res=1; for(long i=0;i<b;i++){ res=res*a%mod; } return res; } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
1bdfd8585d73e75fe701f0f33f82ac46
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ while(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private String readString()throws IOException{ next(); return tk.nextToken(); } } public static void main(String args[])throws IOException{ int t = sc.nextInt(); while(t-->0) solve(); pw.flush(); pw.close(); } private static TreeMap<Integer, TreeSet<Integer>> map; private static void increment(int index, int weight){ map.putIfAbsent(weight, new TreeSet<>()); map.get(weight).add(index); } private static void decrement(int index, int weight){ if(map.get(weight).size() == 1) map.remove(weight); else map.get(weight).remove(index); } private static void solve()throws IOException{ int n = sc.nextInt(); char s[] = sc.readString().toCharArray(); List<Integer> tmp = new ArrayList<>(); int cnt = 0; for(int i = 0; i < n; i++){ if(i > 0 && s[i] == s[i-1]) cnt++; else{ if(cnt > 0) tmp.add(cnt); cnt = 1; } } if(cnt > 0) tmp.add(cnt); int[] weight = tmp.stream().mapToInt((x) -> x).toArray(); TreeSet<Integer> set = new TreeSet<>(), two = new TreeSet<>(); for(int i = 0; i < weight.length; i++){ if(weight[i] > 2) set.add(i); else if(weight[i] == 2) two.add(i); // increment(i, weight[i]); } int ans = 0; for(int i = 0; i < weight.length; i++){ ans++; if(weight[i] > 1){ set.remove(i); two.remove(i); } else{ if(set.isEmpty()){ if(two.isEmpty()) i++; else{ int next = two.first(); weight[next]--; two.remove(next); } }else{ int next = set.first(); weight[next]--; if(weight[next] == 2){ set.remove(next); two.add(next); } } } } pw.println(+ans); } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
1a94848962b39f93a014d2d3ed3d6260
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
/** * @author vivek * programming is thinking, not typing */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class D { private static void solveTC(int __) { /* For Google */ // ans.append("Case #").append(__).append(": "); //code start int n = scn.nextInt(); char[] arr = scn.next().toCharArray(); Queue<Integer> queue = new ArrayDeque<>(); for (int i = 1; i < n ; i++) { if (arr[i-1] == arr[i]) { queue.offer(i); } } ArrayList<Integer> ind = new ArrayList<>(); int in = 0; for (int i = 1; i < n; i++) { if (arr[i - 1] != arr[i]) { ind.add(in); in = i; } } ind.add(in); int c = 0; for (int i = 0; i < ind.size(); i++) { int ele = ind.get(i); boolean isFound = false; while (!queue.isEmpty()) { int indd = queue.poll(); if (indd >= ele) { isFound = true; break; } } c++; if (!isFound) { i++; } } print(c); //code end print("\n"); } static class Pair { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } } /** * Don't copy other's templates, make your own <br> * It would be much more beneficial */ public static void main(String[] args) { scn = new Scanner(); ans = new StringBuilder(); int t = scn.nextInt(); // int t = 1; // int limit= ; // sieve(limit); /* try { System.setOut(new PrintStream(new File("file_i_o\\output.txt"))); } catch (FileNotFoundException e) { e.printStackTrace(); } */ for (int i = 1; i <= t; i++) { solveTC(i); } System.out.print(ans); } //Stuff for prime start /** * List containing prime numbers <br> * <b>i<sup>th</sup></b> position contains <b>i<sup>th</sup></b> prime number <br> * 0th index is <b>null</b> */ private static ArrayList<Integer> listOfPrimes; /** * query <b>i<sup>th</sup></b> element to get if its prime of not */ private static boolean[] isPrime; /** * Performs Sieve of Erathosnesis and initialise isPrime array and listOfPrimes list * * @param limit the number till which sieve is to be performed */ private static void sieve(int limit) { listOfPrimes = new ArrayList<>(); listOfPrimes.add(null); boolean[] array = new boolean[limit + 1]; Arrays.fill(array, true); array[0] = false; array[1] = false; for (int i = 2; i <= limit; i++) { if (array[i]) { for (int j = i * i; j <= limit; j += i) { array[j] = false; } } } isPrime = array; for (int i = 0; i <= limit; i++) { if (array[i]) { listOfPrimes.add(i); } } } //stuff for prime end /** * Calculates the Least Common Multiple of two numbers * * @param a First number * @param b Second Number * @return Least Common Multiple of <b>a</b> and <b>b</b> */ private static long lcm(long a, long b) { return a * b / gcd(a, b); } /** * Calculates the Greatest Common Divisor of two numbers * * @param a First number * @param b Second Number * @return Greatest Common Divisor of <b>a</b> and <b>b</b> */ private static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static void print(Object obj) { ans.append(obj.toString()); } static Scanner scn; static StringBuilder ans; //Fast Scanner static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); /* try { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt")))); } catch (FileNotFoundException e) { e.printStackTrace(); } */ } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } Integer[] nextIntegerArray(int n) { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } String[] nextStringArray() { return nextLine().split(" "); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
7a56c0660b59df339505d87335d50b87
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1430d { public static void main(String[] args) throws IOException { int t = ri(); while (t --> 0) { int n = ri(), del_ind = 0, cur = 0, ans = 0; char[] s = rcha(); while (cur < n) { if (del_ind < n - 1) { while (del_ind < n - 1 && s[del_ind] != s[del_ind + 1]) { ++del_ind; } if (del_ind < n - 1) { ++del_ind; } else { while (cur < n - 1 && s[cur + 1] == s[cur]) { ++cur; } ++cur; } } else { while (cur < n - 1 && s[cur + 1] == s[cur]) { ++cur; } ++cur; } while (cur < n - 1 && s[cur + 1] == s[cur]) { ++cur; } // prln(cur, ans + 1); ++cur; del_ind = max(del_ind, cur); ++ans; } prln(ans); } 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;} // 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());} // 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 boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} 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\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
0897c616252006fd82844f54175c9785
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.math.*; public class Solution { final static int MOD = 1000000007; public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = Integer.parseInt(in.next()); for(int tt = 0; tt < t; tt++) { int n = Integer.parseInt(in.next()); String ss = in.next(); char[] s = new char[n + 1]; for(int i = 0; i < n; i++) s[i] = ss.charAt(i); s[n] = '*'; int one = 0; int two = 0; int extra = 0; int cnt = 1; for(int i = 0; i < n; i++) { if(s[i] == s[i + 1]) cnt += 1; else { one += 1; if(cnt >= 2) { two += 1; extra += (cnt - 2); } cnt = 1; } } int ans = 0; cnt = 1; int assume = 0; for(int i = 0; i < n; i++) { if(s[i] == s[i + 1]) { cnt += 1; }else { if(one > 0) { ans += 1; one -= 1; if(cnt == 1) { if(extra > 0) { extra -= 1; assume += 1; } else if(two > 0) two -= 1; else one -= 1; }else { if(two < 1) one -= 1; else { assume -= (cnt - 2); if(assume < 0) { extra -= Math.abs(assume); assume = 0; } two -= 1; } } }else { break; } cnt = 1; } } System.out.println(ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
d68242b477d927a156b4158ff0026d9b
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { // Scanner sc=new Scanner(System.in); FastReader sc=new FastReader(); Writer w=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(),z=0,o=0; String s=sc.next(); ArrayList<Integer> al=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='0'){ if(o!=0)al.add(o); z++; o=0; } else{ if(z!=0)al.add(z); o++; z=0; } } if(o!=0)al.add(o);if(z!=0)al.add(z); int x=0,ans=0,f=0; for(int i=0;i<al.size();i++){ if(al.get(i)!=1){ ans++; } else{ if(i!=al.size()-1){ if(x<=i)x=i+1; f=0; for(;x<al.size();x++){ if(al.get(x)>1){ int y=al.get(x); al.set(x,y-1); f=1; break; } } if(f==0)i++; } ans++; } } System.out.println(ans); } w.flush(); w.close(); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
d7ce3e06aed04ea4f8f48cfd35678333
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class D { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class Solver { public void solve(InputReader in, PrintWriter out) { var t = in.nextInt(); for (var i = 0; i < t; i++) { solveT(in, out); } } public void solveT(InputReader in, PrintWriter out) { var n = in.nextInt(); var s = in.next(); var lst = new ArrayList<Integer>(); var currC = s.charAt(n - 1); var currCnt = 1; for (var i = n - 2; i >= 0; i--) { if (s.charAt(i) != currC) { lst.add(currCnt); currCnt = 0; } currCnt++; currC = s.charAt(i); } lst.add(currCnt); var ops = 0; var cursor = lst.size() - 1; while (cursor >= 0) { while (cursor >= 0 && (cursor >= lst.size() || lst.get(cursor) == 1)) cursor--; if (cursor < 0) break; lst.set(cursor, lst.get(cursor) - 1); DecLast(lst); ops++; } ops += (lst.size() + 1) / 2; out.println(ops); } void DecLast(ArrayList<Integer> lst) { var pos = lst.size() - 1; lst.remove(pos); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
736698ef4c088f078e1dae834898903f
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; public class Main { public static void main(final String[] args) { // FastScanner sc = new FastScanner("in.txt"); // PrintWriter out; // try { // out = new PrintWriter("out.txt"); // } catch (FileNotFoundException e) { // e.printStackTrace(); // return; // } FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); solve(sc, out); out.flush(); sc.close(); out.close(); } static void solve(FastScanner sc, PrintWriter out) { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); String s = sc.nextToken(); List<Integer> chunks = new ArrayList<>(); for (int i = 0; i < n;) { char newSeqStartChar = s.charAt(i); int newSeqStartIndex = i; do { ++i; } while (i < n && s.charAt(i) == newSeqStartChar); chunks.add(i - newSeqStartIndex); } int ans = 0; int i = 0; int j = 0; while (i < chunks.size()) { ++ans; if (chunks.get(i) == 1) { while (j < chunks.size() && (j <= i || chunks.get(j) == 1)) { ++j; } if (j < chunks.size()) { // Select index in chunk[j] and delete the i-th chunk as prefix. chunks.set(j, chunks.get(j) - 1); ++i; } else { // Select index in chunk[i] and delete the (i+1)-th chunk as prefix. // Each of these chunks contains 1 character. i += 2; } } else { // Select index in i-th chunk and delete the rest of the chunk as prefix. ++i; } } out.println(ans); } } } class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String readLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String nextToken() { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(readLine()); } return st.nextToken(); } public String nextLine() { String str = ""; if (st != null && st.hasMoreElements()) { str = st.nextToken("\n\r\f"); } else { str = readLine(); } return str; } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
7d71ba4494c3b8f674ba25001b8748d3
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.*; import java.util.*; public class TEST { static class Reader { final private int BUFFER_SIZE = 1 << 16; Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in))); private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws IOException { String str00 = scan.next(); return str00; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() throws IOException { int c; for (c = read(); c <= 32; c = read()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = read()) { sb.append((char) c); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] nextArray(int n) throws IOException { int[] a=new int[n]; for (int i=0;i<n;i++) { a[i]=nextInt(); } return a; } public long[] nextArrayl(int n) throws IOException { long[] a = new long[n]; for (int i=0;i<n;i++) { a[i]=nextLong(); } return a; } } public static void main(String args[])throws IOException { Reader r=new Reader(); int t=r.nextInt(); while(t-->0) { int n=r.nextInt(); String s=r.next(); char ch[]=s.toCharArray(); int sum=1; long ex=0; List<Integer> list=new ArrayList<>(); for(int i=1;i<n;i++) { if(ch[i-1]==ch[i]) { sum++; } else { list.add(sum); ex+=Math.max(0,sum-2); sum=1; } } list.add(sum); ex+=Math.max(0,sum-2); long d=ex; double ans=0; for(int i=0;i<list.size();i++) { if(list.get(i)>1) { ans=ans+1; ex=Math.min(d-(list.get(i)-2),ex); d=d-Math.max(0,list.get(i)-2); } else { if(ex>0) { ex--; ans=ans+1; } else { ans=ans+0.5; } } } ans=Math.ceil(ans); System.out.println((long)ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
cc0a253b7932655f88852786f39a3943
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0) { int n=s.nextInt(); String str=s.next(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<n;){ char c=str.charAt(i); int count=0; while(i<n && str.charAt(i)==c) { count++; i++; } list.add(count); } int ans=0; int j=0; int size=list.size(); for(int i=0;i<size;i++) { ans++; if(list.get(i)>1) { //We can remove two numbers from same index. continue; } else{ //j-> pointer to check element with count>=2 j=Integer.max(j,i+1); while(j<size && list.get(j)==1) { j++; } if(j<size) { list.set(j,list.get(j)-1); } else { //Special case when list do not contains element with count>=2 //It means that list have only elements with count=1 and we remove last element from the list //Hence we reduce size by 1. size--; } } } System.out.println(ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
11d45c35ad4c673e831b73e995d61fc6
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
//package edu96; import java.io.*; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; // What's the smallest input? // Check * for int/long overflow. // Check / for accidental rounding. // Are you using doubles? Can you avoid it? // Never compare after taking mod. // Mod the final result. // Initialize globals in solve() unless they are independent of the problem input. // Check for local/global name conflicts (n?). // Check initial values for max/min (not Integer.MIN_VALUE for long). public class D { static Random rand; static boolean MULTIPLE_CASES = true; static boolean CONSTRUCTIVE = false; static long MOD = (long) 1e9 + 7; static long BIG = (long) 2e9 + 10; public static void solve(Reader in, PrintWriter out) { int n = in.nextInt(); char[] s = in.next().toCharArray(); List<Integer> groups = new ArrayList<>(); int start = 0; for (int i = 1; i < n; i++) { if (s[i] != s[i-1]) { groups.add(i - start); start = i; } } groups.add(n-start); // System.err.println(groups); Stack<Integer> nonOneIndices = new Stack<>(); for (int i = groups.size() - 1; i >= 0; i--) { if (groups.get(i) != 1) nonOneIndices.add(i); } // System.err.println(nonOneIndices); int ptr = 0; int ops = 0; while (ptr < groups.size()) { // update stack while (!nonOneIndices.isEmpty() && nonOneIndices.peek() < ptr) { nonOneIndices.pop(); } // delete if (!nonOneIndices.isEmpty()) { int index = nonOneIndices.peek(); groups.set(index, groups.get(index)-1); if (groups.get(index) == 1) nonOneIndices.pop(); } else { // everything is a 1 - want to delete from the beginning (or end) ptr++; } // advance ptr ptr++; ops++; } // if prefix length > 1, delete from prefix (has no effect) // if prefix length = 1, delete from a later group of > 1 (the next one) out.println(ops); } public static void main(String[] args) throws IOException { Reader in = null; PrintWriter out = null; for (String arg : args) { if (arg.startsWith("input")) { in = new Reader(arg); } else if (arg.startsWith("output")) { out = new PrintWriter(new FileWriter(arg)); } } if (in == null) in = new Reader(); if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out)); if (MULTIPLE_CASES) { int tests = in.nextInt(); for (int t = 0; t < tests; t++) { solve(in, out); } } else { solve(in, out); } out.flush(); } static class Tester { public static void main(String[] args) throws IOException { Validator validator = new Validator(); File currentDir = new File("."); long before; long after; for (File inputFile : Arrays.stream(currentDir.listFiles()) .sorted(Comparator.comparing(File::getName)) .collect(Collectors.toList())) { if (!inputFile.getName().startsWith("input") || inputFile.getName().contains("sight") || inputFile.getName().contains("big")) continue; System.out.println("Test file: " + inputFile.getName()); before = System.nanoTime(); String outputFileName = "output" + inputFile.getName().substring(5); D.main(new String[]{inputFile.getName(), outputFileName}); after = System.nanoTime(); File outputFile = new File(outputFileName); if (!outputFile.exists()) { throw new IllegalStateException("Missing output file " + outputFile); } // TODO if verifier is implemented, remove this if (CONSTRUCTIVE) { System.out.println("INPUT:"); printFile(inputFile); System.out.printf("\nOUTPUT: (%d milliseconds)\n", (after - before) / 1000000L); printFile(outputFile); continue; } if (validator.validate(inputFile, outputFile)) { System.out.printf("OK (%d milliseconds)\n", (after - before) / 1000000L); } else { System.out.println("FAILED"); System.out.println("\nInput: "); printFile(inputFile); System.out.println("\nIncorrect Output: "); printFile(outputFile); return; } } System.out.println("\n-----------------\n"); File sightTestInput = new File("input-sight"); if (sightTestInput.exists()) { System.out.println("Running sight test... Input:"); printFile(sightTestInput); before = System.nanoTime(); System.out.println("\nOutput: "); D.main(new String[]{"input-sight"}); after = System.nanoTime(); System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L); System.out.println("\n-----------------\n"); } File bigTestInput = new File("input-big"); if (bigTestInput.exists()) { System.out.println("Running big test..."); before = System.nanoTime(); D.main(new String[]{"input-big"}); after = System.nanoTime(); System.out.printf("(%d milliseconds)\n", (after - before) / 1000000L); } } static void printFile(File file) throws FileNotFoundException { BufferedReader reader = new BufferedReader(new FileReader(file)); reader.lines().forEach(System.out::println); } } static class Validator { boolean validate(File inputFile, File outputFile) throws IOException { File expectedOutputFile = new File("expected-output" + inputFile.getName().substring(5)); if (CONSTRUCTIVE || !expectedOutputFile.exists()) { return validateManual(inputFile, outputFile); } return areSame(outputFile, expectedOutputFile); } private boolean validateManual(File inputFile, File outputFile) throws IOException { if (CONSTRUCTIVE) { // Validate output against input Reader inputReader = new Reader(inputFile.getName()); Reader outputReader = new Reader(outputFile.getName()); // TODO implement manual validation throw new IllegalStateException("Missing expected output file"); } else { File naiveOutput = new File("naive-" + outputFile.getName()); Naive.main(new String[]{inputFile.getName(), naiveOutput.getName()}); return areSame(outputFile, naiveOutput); } } private boolean areSame(File file1, File file2) throws IOException { BufferedReader reader1 = new BufferedReader(new FileReader(file1)); BufferedReader reader2 = new BufferedReader(new FileReader(file2)); String line1; while ((line1 = reader1.readLine()) != null) { String line2 = reader2.readLine(); if (line2 == null) line2 = ""; // ok if one has an extra newline if (!line1.trim().equals(line2.trim())) { return false; } } String line2; while ((line2 = reader2.readLine()) != null) { if (!line2.trim().isEmpty()) { return false; } } return true; } } static class Naive { public static void solveNaive(Reader in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); Map<String, Integer> m = new HashMap<>(); int ans = solve(s, m); out.println(ans); } static int solve(String s, Map<String, Integer> m) { if (m.containsKey(s)) return m.get(s); if (s.length() == 0) return 0; int mx = Integer.MIN_VALUE; for (int i = 0; i < s.length(); i++) { String newS = s.substring(0, i) + s.substring(i+1); if (!newS.isEmpty()) { int start = 1; while (start < newS.length() && newS.charAt(start) == newS.charAt(start-1)) { start++; } newS = newS.substring(start); } mx = Math.max(mx, 1 + solve(newS, m)); } m.put(s, mx); return mx; } public static void main(String[] args) throws IOException { Reader in = null; PrintWriter out = null; for (String arg : args) { if (arg.startsWith("input")) { in = new Reader(arg); } else if (arg.startsWith("naive-output")) { out = new PrintWriter(new FileWriter(arg)); } } if (in == null) in = new Reader(); if (out == null) out = new PrintWriter(new OutputStreamWriter(System.out)); int tests = in.nextInt(); for (int t = 0; t < tests; t++) { solveNaive(in, out); } out.flush(); out.close(); } } static boolean isPowerOfTwo(int x) { return x > 0 & (x & (x - 1)) == 0; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static void ruffleSort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int oi = rand.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n = a.length; for (int i = 0; i < n; i++) { int oi = rand.nextInt(n); long temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } /////////////////////////////////// ////////// FAST PAIR ////////// /////////////////////////////////// // Works on -1e9 <= x, y <= 1e9 static long pair(int x, int y) { x = (int) BIG / 2 - x; y = (int) BIG / 2 - y; return x * BIG + y; } static int x(long pair) { return (int) BIG / 2 - (int) (pair / BIG); } static int y(long pair) { return (int) BIG / 2 - (int) (pair % BIG); } static String str(long pair) { return String.format("(%d, %d)", x(pair), y(pair)); } /////////////////////////////////// ////////// BINARY SEARCH ////////// /////////////////////////////////// // return highest in range that still returns true // T T T F F F F // invariant: // - indicator(min) = true // - indicator(max+1) = false static int binarySearchHighest(int min, int max, Function<Integer, Boolean> indicator) { int a = min; int b = max; while (a != b) { int mid = (a % 2 != b % 2) ? 1 + (a + b) / 2 : (a + b) / 2; if (indicator.apply(mid)) { a = mid; } else { b = mid - 1; } } return a; } // return lowest in range that still returns true // F F F F T T T // invariant: // - indicator(min-1) = false // - indicator(max) = true static int binarySearchLowest(int min, int max, Function<Integer, Boolean> indicator) { int a = min; int b = max; while (a != b) { int mid = (a + b) / 2; if (indicator.apply(mid)) { b = mid; } else { a = mid + 1; } } return a; } static void insist(boolean bool) { if (!bool) throw new IllegalStateException(); } static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public Reader(String fileName) throws FileNotFoundException { reader = new BufferedReader(new FileReader(fileName)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextInts(int n) { int[] out = new int[n]; for (int i = 0; i < n; i++) { out[i] = nextInt(); } return out; } public long[] nextLongs(int n) { long[] out = new long[n]; for (int i = 0; i < n; i++) { out[i] = nextLong(); } return out; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
92a8c881f8cdb2b4a78e21e4b10cf3ca
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.TreeSet; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); DStringDeletion solver = new DStringDeletion(); int testCount = in.nextInt(); for(int i = 1; i<=testCount; i++) solver.solve(i, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class DStringDeletion { public DStringDeletion() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(); char[] arr = in.next(n).toCharArray(); TreeSet<Integer> next = new TreeSet<>(); for(int i = 0; i<=n; i++) { next.add(i); } int start = 0, j = 0, ans = 0; while(j<n-1) { for(; j<n-1&&arr[j]!=arr[j+1]; j++) ; if(j!=n-1) { next.remove(j); start = next.ceiling(start); int x = arr[start]; next.remove(start); for(; start<n&&arr[start]==x; start = next.higher(start)) { next.remove(start); } ans++; } j = Math.max(start, j+1); // Utilities.Debug.dbg(start, j); } ans += next.size() >> 1; pw.println(ans); } } static class Utilities { public static class Debug { public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } static interface InputReader { String next(); int nextInt(); default String next(int maxLength) { return next(); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { StringBuilder ret = new StringBuilder(64); byte c = skip(); while(c!=-1&&!isSpaceChar(c)) { ret.appendCodePoint(c); c = read(); } return ret.toString(); } public String next(int maxLength) { byte[] ret = new byte[maxLength]; byte c = skip(); int ind = 0; while(c!=-1&&!isSpaceChar(c)) { ret[ind++] = c; c = read(); } return new String(ret, 0, ind); } public int nextInt() { int ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } private boolean isSpaceChar(byte b) { return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f'; } private byte skip() { byte ret; while(isSpaceChar((ret = read()))) ; return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
bace33d0641eb15fd8092e17dc2b9a98
train_001.jsonl
1602407100
You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?
256 megabytes
import java.util.*; import java.util.Scanner; import java.util.Arrays; import java.util.Set; public class Main { public static void main(String args[]) { Scanner cin = new Scanner(System.in); int t; int n; String s; long a[] = new long[200005]; t=cin.nextInt(); while((t--) > 0) { n = cin.nextInt(); s = cin.next(); int id = 0; a[id] = 1; for(int i = 1; i < n; i++) { if(s.charAt(i) == s.charAt(i-1)) a[id]++; else { id++; a[id] = 1; } } // System.out.println("id = " + id); // for(int i = 0; i <= id; i++) { // System.out.println(i + " " + a[i]); // } int head = 0, index = 0x3f3f3f3f; for(int i = 0; i <= id; i++) { if(a[i] > 1) { index = i; break; } } if(index == 0x3f3f3f3f) index = id; int ans = 0; while(head <= id) { if(a[head] > 1) { ans++; head++; } else { if(a[index] > 1) { a[index]--; head++; ans++; } else { head += 2; ans++; } } if(index < head) index = head; while(a[index] == 1 && index < id) index++; } System.out.println(ans); } } }
Java
["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"]
2 seconds
["3\n1\n1\n1\n3"]
NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.
Java 11
standard input
[ "data structures", "two pointers", "binary search", "greedy" ]
d0030996e6b29c8580463fae43bb04d4
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,700
For each test case, print a single integer — the maximum number of operations you can perform.
standard output
PASSED
3cbe0c26f429065747fff60823d0127a
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
//package Test; import java.util.*; public class A { static class Solution { void solve(int[] A, List<Integer> newA, List<Integer> fixPos){ if(fixPos.size() == A.length) { for(int i = 0; i < A.length; i++) { System.out.print(A[i] + " "); } System.out.println(); return; } Collections.sort(newA); int len = A.length, i = 0, j = 0; int[] res = new int[len]; for(; i < newA.size();) { if(j < fixPos.size() && i + j == fixPos.get(j)) { res[i + j] = A[fixPos.get(j)]; j++; } else { res[i + j] = newA.get(newA.size() - 1 - i); i++; } } for(;j < fixPos.size();) { res[i + j] = A[fixPos.get(j)]; j++; } for(i = 0; i < len; i++) { System.out.print(res[i] + " "); } System.out.println(); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for(int i = 0; i < t; i++) { int n = scanner.nextInt(); int[] A = new int[n]; for(int j = 0; j < n; j++) { A[j] = scanner.nextInt(); } List<Integer> newA = new ArrayList<>(); List<Integer> fixPos = new ArrayList<>(); for(int j = 0; j < n; j++) { int flag = scanner.nextInt(); if(flag == 0) newA.add(A[j]); else fixPos.add(j); } Solution solution = new Solution(); solution.solve(A, newA, fixPos); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
cf033ed40a1e25899efbe416e1aa991f
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; ++i) { a[i] = sc.nextInt(); } int[] l = new int[n]; for (int i = 0; i < l.length; ++i) { l[i] = sc.nextInt(); } System.out.println(solve(a, l)); } sc.close(); } static String solve(int[] a, int[] l) { int[] unlockedIndices = IntStream.range(0, l.length).filter(i -> l[i] == 0).toArray(); int[] sortedUnlockedValues = IntStream.range(0, l.length) .filter(i -> l[i] == 0) .map(i -> a[i]) .boxed() .sorted(Collections.reverseOrder()) .mapToInt(x -> x) .toArray(); for (int i = 0; i < unlockedIndices.length; ++i) { a[unlockedIndices[i]] = sortedUnlockedValues[i]; } return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(" ")); } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
1d388e964ba9d016a3dae7edb0fe6a47
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.util.*; public class b { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); int[] tab = new int[n]; int[] l = new int[n]; for(int i = 0; i < n; i++) tab[i] = in.nextInt(); for(int i = 0; i < n; i++) l[i] = in.nextInt(); List<Integer> unlocked = new ArrayList<>(); for(int i = 0; i < n; i++) { if(l[i] == 0) unlocked.add(tab[i]); } Collections.sort(unlocked); Collections.reverse(unlocked); for(int i = 0; i < n; i++) { if(l[i] == 0) { System.out.print(unlocked.get(0) + " "); unlocked.remove(0); } else System.out.print(tab[i] + " "); } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
d16fcad25af4a8bf992eda066ad86111
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int t = ni(); while(t-->0) { int n = ni(); int a[] = new int[n]; int p[] = new int[n]; ArrayList<Integer> ls = new ArrayList<Integer>(); for(int i=0;i<n;i++) a[i] = ni(); for(int i=0;i<n;i++){ p[i] = ni(); if (p[i]==0){ ls.add(a[i]); } } Collections.sort(ls, Collections.reverseOrder()); int j = 0; for(int i=0;i<ls.size();i++) { int v = ls.get(i); if (j>=n) break; if(p[j]==1){ i--; j++; } else { a[j] = v; j++; } } for (int i=0;i<n;i++) { System.out.print(a[i] + " "); } System.out.println(); } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
1525950bf25b8a3d7bcd5f6935718a26
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class c1 { public static FScanner scan; public static PrintWriter out; public static void main(String[] args) { scan=new FScanner(); out=new PrintWriter(new BufferedOutputStream(System.out)); // int t=1; int t=scan.nextInt(); while(t-->0) { int n=scan.nextInt(),point=-1,sum=0,last=-1; int[] a=new int[n],prefix=new int[n],lock=new int[n],fake=a; ArrayList<Integer> flip=new ArrayList<>(); for(int c=0;c<n;c++) a[c]=scan.nextInt(); for(int c=0;c<n;c++) { lock[c]=scan.nextInt(); if(lock[c]==0) flip.add(a[c]); } Collections.sort(flip,Comparator.reverseOrder()); for(int c=0;c<n;c++) { if(lock[c]==0) { point++; fake[c]=flip.get(point); } else fake[c]=a[c]; sum+=fake[c]; prefix[c]=sum; } if(last!=-1&&prefix[last]<0) { for(int c=0;c<n;c++) { if(lock[c]==0) { fake[c]=flip.get(point); point--; } } } for(int c=0;c<n;c++) out.print(fake[c]+" "); out.println(); } out.close(); } //------------------------------------------------------------------------------------------------------------------ //scanner public static class FScanner { BufferedReader br; StringTokenizer st; public FScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
da173a52d48b46ba89a7c7d14944179b
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 998244353; long fac[]= new long[3000]; public void solve() throws IOException { int t = readInt(); for(int f =0;f<t;f++) { int n = readInt(); int arr[]=new int[n]; int l[]=new int[n]; for(int i =0;i<n;i++) { arr[i]= readInt(); } for(int i =0;i<n;i++) { l[i]= readInt(); } ArrayList<Integer> l1=new ArrayList<Integer>(); for(int i =0;i<n;i++) { if(l[i]==0) l1.add(arr[i]); } Collections.sort(l1); int top=l1.size(); for(int i =0;i<n;i++) { if(l[i]==1) out.print(arr[i]+" "); else { top--; out.print(l1.get(top)+" "); } } out.println(); } } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int val ; int color; edge(int u, int v) { this.val=u; this.color=v; } public int compareTo(edge e) { return this.val-e.val; } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
53aedf3b3568a5586539fcf10a8a554b
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Main{ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static String nexts() throws IOException { tokenizer = new StringTokenizer(reader.readLine()); String s=""; while (tokenizer.hasMoreTokens()) { s+=tokenizer.nextElement()+" "; } return s; } //String str=nextToken(); //String[] s = str.split("\\s+"); public static int gcd(int x, int y){ if (y == 0) return x; else return gcd(y, x % y); } public static boolean isPrime(int 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) { //Checking 6i+1 & 6i-1 if (n % i == 0 || n % (i + 2) == 0) { return false; } } //O(sqrt(n)) return true; } public static void shuffle(int[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static long power(int x, long n) { long mod = 1000000007; if (n == 0) { return 1; } long pow = power(x, n / 2); if ((n & 1) == 1) { return (x * pow * pow)%mod; } return (pow * pow)%mod; } static long ncr(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } static int first(int arr[], int low, int high, int x, int n) //Returns first index of x in sorted arr else -1 { if(high >= low) { int mid =low + (high - low)/2; if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x) return mid; else if(x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid -1), x, n); } return -1; } static int last(int arr[], int low, int high, int x, int n) //Returns last index of x in sorted arr else -1 { if(high >= low) { int mid = low + (high - low)/2; if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x ) return mid; else if(x < arr[mid]) return last(arr, low, (mid -1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } static int binarys(int[] arr, int l, int r, int x){ while(l<=r){ int mid = l+(r-l)/2; if(arr[mid]==x){ return x; } if(arr[mid]<x){ l=mid+1; } else{ r=mid-1; } } return -1; } static class R implements Comparable<R>{ int x, y; public R(int x, int y) { this.x = x; this.y = y; } public int compareTo(R o) { return x-o.x; //Increasing order(Which is usually required) } } // int t=a[i]; // a[i]=a[j]; // a[j]=t; //double d=Math.sqrt(Math.pow(Math.abs(x2-x1),2)+Math.pow(Math.abs(y2-y1),2)); public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int t = nextInt(); while(t-->0){ //long n = nextLong(); //String s= nextToken(); //long[] a=new long[n]; ArrayList<Integer> ar=new ArrayList<Integer>(); //HashSet<Integer> set=new HashSet<Integer>(); //HashMap<Integer,String> h=new HashMap<Integer,String>(); //R[] a1=new R[n]; //char[] c=nextToken().toCharArray(); int n = nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=nextInt(); } int[] l=new int[n]; for(int i=0;i<n;i++){ l[i]=nextInt(); } for(int i=0;i<n;i++){ if(l[i]==0){ ar.add(a[i]); } } Collections.sort(ar); int j=ar.size()-1; for(int i=0;i<n;i++){ if(l[i]==0){ int k=ar.get(j); j--; writer.print(k+" "); } else{ writer.print(a[i]+" "); } } writer.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
50c085733317ece4d63ca1f59a48db71
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
/*package whatever //do not write package name here */ import java.util.*; public class a{ public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0){ int n = sc.nextInt(),i=0,j=0; int a[] = new int[n], l[] = new int[n]; List<Integer> list = new ArrayList<>(); while(i<n) a[i++] = sc.nextInt(); i=0; while(i<n) l[i++] = sc.nextInt(); for(i=0; i<n; i++){ if(l[i]==0) list.add(a[i]); } Collections.sort(list,Collections.reverseOrder()); //System.out.println(" * "+list); for(i=0,j=0; i<n&&j<list.size(); i++){ if(l[i]==0){ a[i] = list.get(j); j++; } } for(int x : a) System.out.print(x+" "); System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
f4162e29e2285678e0120f427b5147f1
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Euler { public static void main(String[] args){ FastReader in = new FastReader(); PrintWriter o = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0;i < n; i++) { arr[i] = in.nextInt(); } boolean[] b = new boolean[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); if (x == 1) b[i] = false; if (x == 0) b[i] = true; } List<Integer> ls = new ArrayList<>(); for (int i = 0; i < n; i++) { if (b[i]) { ls.add(arr[i]); } } Collections.sort(ls, Collections.reverseOrder()); int x = 0; for (int i = 0; i < n; i++) { if (b[i]) { arr[i] = ls.get(x); x++; } } for (int i = 0; i < n; i++) { o.print(arr[i] + " "); } o.println(); } o.close(); o.flush(); return; } public static int helper(int pos, int[] arr, int turn, int[][] dp) { int n = arr.length; if (pos >= arr.length) { return 0; } if (dp[pos][turn] != Integer.MAX_VALUE) { return dp[pos][turn]; } int val = Integer.MAX_VALUE; if (turn == 0) { int i = pos; if (pos + 1 < n && arr[i] == 0 && arr[i + 1] == 0) { val = Math.min(val, helper(pos + 2, arr, 1, dp)); } if (pos + 1 < n && arr[i] == 1 && arr[i + 1] == 1) { val = Math.min(val, 2 + helper(pos + 2, arr, 1, dp)); } if (pos + 1 < n && arr[i] == 0 && arr[i + 1] == 1) { val = Math.min(val, 1 + helper(pos + 2, arr, 1, dp)); } if (pos + 1 < n && arr[i] == 1 && arr[i + 1] == 0) { val = Math.min(val, helper(pos + 2, arr, 1, dp)); } if (pos + 1 >= n) val = Math.min(val,arr[i] == 1 ? 1 : 0 + helper(pos + 1, arr, 1, dp)); } if (turn == 1) { if (pos + 1 < n) { val = Math.min(helper(pos + 2, arr, 0, dp), val); } val = Math.min(val, helper(pos + 1, arr, 0, dp)); } dp[pos][turn] = val; return val; } 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()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
e89e2c2d1887b0e83c79fe536a17f71f
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
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.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.util.Collections; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BNegativePrefixes solver = new BNegativePrefixes(); solver.solve(1, in, out); out.close(); } static class BNegativePrefixes { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long[] arr = new long[n]; int[] k = new int[n]; long sum1 = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); sum1 += arr[i]; } ArrayList<Integer> idx = new ArrayList<>(); ArrayList<Long> pos = new ArrayList<>(); ArrayList<Long> neg = new ArrayList<>(); for (int i = 0; i < n; i++) { k[i] = sc.nextInt(); if (k[i] == 0) { idx.add(i); if (arr[i] >= 0) { pos.add(arr[i]); } else neg.add(arr[i]); } } Collections.sort(pos, Collections.reverseOrder()); Collections.sort(neg, Collections.reverseOrder()); Collections.sort(idx); for (int i = 0; i < idx.size(); i++) { if (i < pos.size()) { arr[idx.get(i)] = pos.get(i); } else { arr[idx.get(i)] = neg.get(i - pos.size()); } } for (long x : arr) pw.print(x + " "); pw.println(); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
4a2f69ebed1934a21cd6c286e950a1d3
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
//package com.company; import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while (tc-->0) { int n; n = sc.nextInt(); int[] arr = new int[100005], tp = new int[10005], state = new int[100005]; for (int i=0; i<n; i++) arr[i] = sc.nextInt(); int count = 0; for (int i=0; i<n; i++) { state[i] = sc.nextInt(); if (state[i] == 0) tp[count++] = arr[i]; } if (count>0) Arrays.sort(tp, 0, count); for (int i=0; i<n; i++) { if (state[i]!=0) System.out.print(arr[i]+ " "); else System.out.print(tp[--count]+ " "); } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
185983d26906ae62a6645d13ff8fc9d9
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
//package com.company; import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while (tc-->0) { int n; n = sc.nextInt(); int[] arr = new int[100005], tp = new int[10005], state = new int[100005]; for (int i=0; i<n; i++) arr[i] = sc.nextInt(); int count = 0; for (int i=0; i<n; i++) { state[i] = sc.nextInt(); if (state[i] == 0) tp[count++] = arr[i]; } if (count>0) Arrays.sort(tp, 0, count); for (int i=0; i<n; i++) { if (i>0) System.out.print(" "); if (state[i]!=0) System.out.print(arr[i]); else System.out.print(tp[--count]); } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
ee375262df524b4cb43b6f0e2a0ae887
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { final static long MOD = 1000000007; public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); //out.println(); int t = fs.nextInt(); while(t > 0) { t-=1; int n = fs.nextInt(); int [] a = fs.nextIntArray(n); int [] b = fs.nextIntArray(n); ArrayList<Integer> changable_Positions = new ArrayList<>(); for(int i = 0; i < n; i++) { if(b[i] == 0) changable_Positions.add(a[i]); } Collections.sort(changable_Positions, Collections.reverseOrder()); int next = 0; for(int i = 0; i < n; i++) { if(b[i] == 0) { a[i] = changable_Positions.get(next++); } } for(int i = 0; i < n; i++) { /* if(b[i] == 0) { out.print(" |"+a[i] +"| "); }else*/ out.print(a[i]+" "); } out.println(); } out.flush(); out.close(); } class Pair{ int index; int val; Pair(int index, int val) { this.val = val; this.index = index; } } public static String rString(String s) { return new StringBuilder(s).reverse().toString(); } public static long modpow(long exp, long pow) { BigInteger exp_b = BigInteger.valueOf(exp); BigInteger pow_b = BigInteger.valueOf(pow); return exp_b.modPow(pow_b, BigInteger.valueOf(MOD)).longValue(); } public static int powoftwo(long n){ int count = 0; while(n != 0) { n >>= 1; count++; } return count - 1; } public static void rotate(int[] nums, int k) { int n = nums.length; if(k > 0) { for(int j = 0; j < k; j++) { for (int i = 0; i < n; i++) { int temp = nums[(i + k) % n]; nums[(i + k) % n] = nums[i]; nums[i] = temp; } } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader("chat.txt")); st = new StringTokenizer(""); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } public char nextChar() { return next().charAt(0); } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nextCharArray() { return nextLine().toCharArray(); } } } /*class Pair implements Comparable<Pair> { int V; int H; public Pair(int count, int val) { this.V = count; this.H = val; } public void setV(int v) { V = v; } public void setH(int h) { H = h; } @Override public int compareTo(Pair o) { if(this.V != o.V) return Integer.compare(this.V, o.V); else return Integer.compare(this.H, o.H); } public boolean equals(Pair o) { return this.H == o.H && this.V == o.V; } }*/ class Pair { int V; int H; public Pair(int x, int y) { this.V = x; this.H = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return V == key.V && H == key.H; } @Override public int hashCode() { int result = V; result = 31 * result + H; return result; } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
dd37c9683a7277042f0fcac4815f167a
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import java.util.Arrays; import java.util.ArrayList; import java.lang.Math; import java.util.Arrays; import java.util.Comparator; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int binarySearch(int a[] ,int k,int l,int h){ while(l<=h){ int mid = (l+h)/2; if(a[mid]==k) return mid; else if(a[mid]>k) h=mid-1; else if(a[mid]<k) l=mid+1; } return -1; } static int binarySearch(ArrayList<Integer> a ,int k,int l,int h){ while(l<=h){ int mid = (l+h)/2; if(a.get(mid)==k) return mid; else if(a.get(mid)>k) h=mid-1; else if(a.get(mid)<k) l=mid+1; } return -1; } static String reverse(String input) { char[] a = input.toCharArray(); int l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; if (a == b) return a; if (a > b) return gcd(a-b, b); return gcd(a, b-a); } static int lcm(int a, int b) { return (a*b)/gcd(a, b); } static int solve(int A, int B) { int count = 0; for (int i = 0; i < 21; i++) { if (((A >> i) & 1) != ((B >> i) & 1)) { count++; } } return count; } static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static long fact(int n) { long res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public static long count(long k) { return k * (k - 1) / 2; } static boolean isPrime(int n) { // if(n==1) return false; if(n==2) return true; if (n%2==0) return false; int l = (int)Math.sqrt(n); for(int i=3;i<=l;i+=2) { if(n%i==0) return false; } return true; } static int negMod(int n){ int a = (n % 1000000007 + 1000000007) % 1000000007; return a; } public static int sum(long x) { int sum = 0; while (x > 0) { sum += x % 10; x /= 10; } return sum; } public static int max(int x, int y, int z) { return (int)Math.max(Math.max(x, y), z); } public static int min(int x, int y, int z) { return (int)Math.min(Math.min(x, y), z); } static void bipartite(int n,int c,int color[]){ visited[n] = 1; color[n] = c; Iterator<Integer> i = adj.get(n).listIterator(); while (i.hasNext()) { int a = i.next(); if (visited[a]==0) bipartite(a,c^1,color); } } static double distance(int x,int y,int r1,int r2){ double ans = Math.sqrt((x-r1)*(x-r1) + (y-r2)*(y-r2)); return ans; } static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); static int visited[] = new int[100002]; static void addEdge(int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } static void dfs(int a){ visited[a] = 1; Iterator<Integer> i = adj.get(a).listIterator(); while (i.hasNext()) { int n = i.next(); if (visited[n]==0) { dfs(n); } } } static boolean dfscycle(int node , int parent){ visited[node] = 1; Iterator<Integer> i = adj.get(node).listIterator(); while (i.hasNext()) { int n = i.next(); if (visited[n]==0) { if(dfscycle(n,node) == true) return true; } else if(n!=parent) return true; } return false; } static int mod=1000003; static long m=1073741824; static ArrayList<Long> divisors(long n) { ArrayList<Long> a = new ArrayList<Long>(); int count = 0; for (long i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) a.add(i); else // Otherwise print both { a.add(i); a.add(n/i); } } } return a; } public static void main(String[] args) throws Exception { OutputStream outputStream = System.out; FastReader sc = new FastReader(); PrintWriter w = new PrintWriter(outputStream); // Scanner sc = new Scanner(new File("input.txt")); // PrintWriter out = new PrintWriter(new File("output.txt")); int i,j=0; // int t = 1; int t = sc.nextInt(); while(t>0){ int n = sc.nextInt(); int a[] = new int[n]; boolean neg = false; for(i=0;i<n;i++){ a[i] = sc.nextInt(); if(a[i]<0) neg = true; } int f[] = new int[n]; j=0; ArrayList<Integer> s = new ArrayList<Integer>(); for(i=0;i<n;i++){ f[i] = sc.nextInt(); if(f[i]==1) {j++;} else s.add(a[i]); } if(j==n || j==n-1 || neg==false){ for(i=0;i<n;i++) w.print(a[i]+" "); w.println(); } else{ Collections.sort(s); int l = s.size(); j=l-1; for(i=0;i<n;i++){ if(f[i]==0){ a[i] = s.get(j); j--; } } for(i=0;i<n;i++) w.print(a[i]+" "); w.println(); } t--; } w.close(); } } // System.out.println();
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
b243f78af60488612766df7d9854cbb8
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); ArrayList<Integer> b= new ArrayList<>(); int a[]=sc.readArray(n); for (int i=0;i<n;i++){ int x=sc.nextInt(); if (x==0){ b.add(a[i]); a[i]=Integer.MAX_VALUE; } } Collections.sort(b,Collections.reverseOrder()); int j=0; for (int i=0;i<n;i++){ if (a[i]==Integer.MAX_VALUE){ a[i]=b.get(j); j++; } } for (int i:a){ System.out.print(i+" "); } System.out.println(); } out.flush(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sortReverse(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); // Collections.sort.(l); Collections.sort(l,Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(long n) { long[] a=new long[(int)n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
cc711dc587bd2f9f70f05fb6d0091174
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); ArrayList<Integer> b= new ArrayList<>(); int a[]=sc.readArray(n); for (int i=0;i<n;i++){ int x=sc.nextInt(); if (x==0){ b.add(a[i]); a[i]=(int)1e6; } } Collections.sort(b,Collections.reverseOrder()); int j=0; for (int i=0;i<n;i++){ if (a[i]==(int)1e6){ a[i]=b.get(j); j++; } } for (int i:a){ System.out.print(i+" "); } System.out.println(); } out.flush(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sortReverse(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); // Collections.sort.(l); Collections.sort(l,Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(long n) { long[] a=new long[(int)n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
bffbbbab7b41095fae195e4011116482
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int arr[] = new int[n]; long sum = 0; for(int i = 0 ; i < n ; i++) { arr[i] = sc.nextInt(); sum += arr[i]; } int lock[] = new int[n]; for(int i = 0 ; i < n ; i++) { lock[i] = sc.nextInt(); } if(sum < 0) { for(int i = 0 ; i < n ; i++) { System.out.print(arr[i] + " "); } } else { ArrayList<Integer> pos = new ArrayList<Integer>(); ArrayList<Integer> neg = new ArrayList<Integer>(); for(int i = 0 ; i < n ; i++) { if(lock[i] == 0) { if(arr[i] < 0) neg.add(arr[i]); else pos.add(arr[i]); } } int poss[] = new int[pos.size()]; int negg[] = new int[neg.size()]; for(int i = 0 ; i < pos.size() ; i++) { poss[i] = pos.get(i); } for(int i = 0 ; i < neg.size() ; i++) { negg[i] = neg.get(i); } Arrays.sort(poss); Arrays.sort(negg); int ans[] = new int[n]; for(int i = 0 ; i < n ; i++) { ans[i] = 1000000; } int cnt = pos.size()-1; for(int i = 0 ; i < n ; i++) { if(lock[i] == 0 && ans[i] == 1000000) { if(cnt < 0) break; ans[i] = poss[cnt--]; } } cnt = neg.size()-1; for(int i = 0 ; i < n ; i++) { if(lock[i] == 0 && ans[i] == 1000000) { if(cnt < 0) break; ans[i] = negg[cnt--]; } } for(int i = 0 ; i < n ; i++) { if(lock[i] == 0) System.out.print(ans[i] + " "); else System.out.print(arr[i] + " "); } } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
0d562ec881f5d48c82652512bae748c6
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import javafx.print.Collation; import java.io.*; import java.math.BigInteger; import java.text.CollationElementIterator; import java.util.*; import java.lang.*; import java.util.Comparator; public class ai { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); int cnt[]; void solve() throws Exception { // BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new // FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); // out.flush(); int t = ni(); class Pair{ int a; int b; public Pair(int a,int b){ this.a = a; this.b = b; } } while(t-->0){ int n = ni(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = ni(); } int brr[] = new int[n]; for(int i=0;i<n;i++){ brr[i] = ni(); } ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++){ if(brr[i]==0){ list.add(arr[i]); } } Collections.sort(list,Collections.reverseOrder()); int ans[] = new int[n]; int k=0; for(int i=0;i<n;i++){ if(brr[i]==1)ans[i]=arr[i]; else{ ans[i] = list.get(k++); } } for(int i:ans){ System.out.print(i+" "); } System.out.println(); } } public long gcd(long a,long b){ if(a%b==0)return b; return gcd(b,a%b); } public int gcd(int a,int b){ if(a%b==0)return b; return gcd(b,a%b); } public long pow(long a,long b,int c){ if(b==1)return a%c; long x = pow(a,b/2,c); if(b%2==0){ return (x*x)%c; } else{ return (((x*x)%c)*a)%c; } } public void test(String x){ x += "A"; System.out.println(x); } public void build(long arr[],long brr[],int a[],int n,int l,int r){ if(l==r){ arr[n] = brr[n] = a[l]; } else{ int mid = (l+r)/2; build(arr,brr,a,2*n,l,mid); build(arr,brr,a,2*n+1,mid+1,r); arr[n] = arr[2*n] + arr[2*n+1]; brr[n] = Math.max(brr[2*n],brr[2*n+1]); } } public long sum(long arr[],int l,int r,int n,int start,int end){ if(start>end)return 0; if(l==start && r==end){ return arr[n]; } int mid = (l+r)/2; return sum(arr,l,mid,2*n,start,Math.min(end,mid)) + sum(arr,mid+1,r,2*n+1,Math.max(mid+1,start),end); } public void increment(long arr[],long brr[],int n,int l,int r,int tl,int tr,HashMap<Long,Integer> map){ if(l>r)return; if(l==r && tl==tr){ arr[n] = map.get(arr[n]); brr[n] = map.get(brr[n]); } else{ int mid = (tl+tr)/2; if(brr[2*n]>2) increment(arr,brr,2*n,l,Math.min(r,mid),tl,mid,map); if(brr[2*n+1]>2) increment(arr,brr,2*n+1,Math.max(l,mid+1),r,mid+1,tr,map); arr[n] = arr[2*n] + arr[2*n+1]; brr[n] = Math.max(brr[2*n],brr[2*n+1]); } } public int[] sieve(int n){ int []ans = new int[n]; ans[1]=1; int i=2; while(i<n){ if(ans[i]==0){ int j=2*i; while(j<n){ if(ans[j]==0) ans[j] = i; j+=i; } } i++; } return ans; } public static void main(String[] args)throws Exception { new ai().run(); } void run() throws Exception { // is = new FileInputStream("C:\\Users\\compute\\Desktop\\input.txt"); is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
638602e72cb285e996c0fd98bcf43230
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Collections; public class Code { public static void main(String[] args) throws java.lang.Exception{ // TODO Auto-generated method stub Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] ar=new int[n]; for(int i=0;i<n;i++)ar[i]=sc.nextInt(); ArrayList<Integer> l=new ArrayList<>(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); if(arr[i]==0)l.add(ar[i]); }Collections.sort(l); StringBuilder sb=new StringBuilder(); int index=l.size()-1; for(int i=0;i<n;i++) { if(arr[i]==1) { sb.append(ar[i]+" "); }else { if(index>=0) { sb.append(l.get(index)+" "); index--; } } }out.println(sb); }out.flush(); } }class Reader{ final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[(int)1e8]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
25ad0a69c3dc38cabb4afda6d589b116
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import javafx.util.Pair; import java.util.ArrayList; public class CodeForce { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder sb = new StringBuilder(); static boolean flag = false; static int next(String [] sr,int ind) { return Integer.parseInt(sr[ind]); } public static void main(String[] args) throws IOException { int t=Integer.parseInt(br.readLine()); while(t-->0) {flag=false; String[] sr=br.readLine().split(" "); int n=next(sr,0); int[] arr=new int[n]; ArrayList<Integer> pos=new ArrayList<>(); ArrayList<Integer> neg=new ArrayList<Integer>(); int[] a=new int[n]; sr=br.readLine().split(" "); String[] ss=br.readLine().split(" "); for(int i=0;i<n;i++) a[i]=next(ss,i); int plus=0,neget=0; for(int i=0;i<n;i++) {arr[i]=next(sr,i); if(arr[i]>=0) {plus+=arr[i];if(a[i]!=1)pos.add(arr[i]);} else if(arr[i]<0) {neget+=arr[i];if(a[i]!=1)neg.add(arr[i]);} } if(Math.abs(neget)>plus) { for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(""); continue; }Collections.sort(pos); Collections.reverse(pos); Collections.sort(neg); Collections.reverse(neg); int j=0;int k=0; for(int i=0;i<n;i++) { if(a[i]!=1) {if(j<pos.size()) {arr[i]=pos.get(j); j++; } else { arr[i]=neg.get(k); k++;} } } for(int i=0;i<n;i++) { System.out.print(arr[i]+" ");} System.out.println(""); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
e76b1e68c931a2ea8622c18d54f27539
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter pw; static Scanner sc; static ArrayList<Integer>[] adj; static boolean[] visit; static int[][][] dp; static long ceildiv(long x, long y) { return (x+y-1)/y; } static int mod(long x, int m) { return (int)((x%m+m)%m); } static boolean[] arr; static long gcd(long x, long y) {return y==0?x:gcd(y, x%y);} static int Int(boolean x){ return x?1:0; } public static void main(String[] args) throws Exception { sc = new Scanner(System.in); pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] arr=sc.nextArr(n); boolean[] lock=new boolean[n]; for(int i=0; i<n; i++) lock[i]=sc.nextInt()==1; ArrayList<Integer> unlock=new ArrayList<>(); for(int i=0; i<n; i++){ if(!lock[i]) unlock.add(arr[i]); } Collections.sort(unlock, Collections.reverseOrder()); int j=0; for(int i=0; i<n; i++){ if(lock[i]) pw.print(arr[i]+" "); else pw.print(unlock.get(j++)+" "); } pw.println(); } pw.close(); } static int solve(int i, int f, int used){ if(i==arr.length) return 0; if(dp[i][f][used-1]==-1){ if(used==2) dp[i][f][1]=solve(i+1, 1-f, 1)+f*Int(arr[i]); else dp[i][f][0]=Math.min(solve(i+1, f, 2)+(1-f)*Int(arr[i]), solve(i+1, 1-f, 1)+f*Int(arr[i])); } return dp[i][f][used-1]; } static void put(TreeMap<Pair, Integer> map, Pair p){ if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); } static void rem(TreeMap<Pair, Integer> map, Pair p){ if(map.get(p)==1) map.remove(p); else map.replace(p, map.get(p)-1); } static long pow(long a, long pow){ long ans=1; while(pow>0){ if((pow&1)==1) ans*=a; a*=a; pow>>=1; } return ans; } static int getpow(int x) throws Exception{ int pow=x; pw.println("B "+pow); pw.flush(); sc.next(); pw.println("B "+pow); pw.flush(); if(sc.nextInt()==1){ pow*=x; while(true){ pw.println("B "+pow); pw.flush(); if(sc.nextInt()==0) return pow/x; pow*=x; } }else{ return 1; } } static int[] least; static TreeSet<Integer> prime; static void linearsieve(int x){ least=new int[x+1]; prime=new TreeSet<Integer>(); for(int i=2; i<=x; i++){ if(least[i]==0){ least[i]=i; prime.add(i); } for(int y :prime) { if(i*y<=x) least[i*y]=y; else break; } } } static void printArr(int[] arr) { for (int i = 0; i < arr.length - 1; i++) pw.print(arr[i] + " "); pw.println(arr[arr.length - 1]); } static void printArr(long[] arr) { for (int i = 0; i < arr.length - 1; i++) pw.print(arr[i] + " "); pw.println(arr[arr.length - 1]); } static void printArr(Integer[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(char[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i]==0? '1': arr[i]); pw.println(); } static void printArr(ArrayList<Integer> list) { for (int i = 0; i < list.size(); i++) pw.print(list.get(i)+" "); pw.println(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public Integer[] nextsort(int n) throws IOException{ Integer[] arr=new Integer[n]; for(int i=0; i<n; i++) arr[i]=nextInt(); return arr; } public Pair nextPair() throws IOException{ return new Pair(nextInt(), nextInt()); } public Pair[] nextPairArr(int n) throws IOException{ Pair[] arr=new Pair[n]; for(int i=0; i<n; i++) arr[i]=nextPair(); return arr; } public boolean ready() throws IOException { return br.ready(); } } static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x, int y) { this.x=x; this.y=y; } public int hashCode() { return (this.x*1000+this.y); } public int compareTo(Pair p){ int min1=Math.min(x, y), min2=Math.min(p.x, p.y); if(min1!=min2) return min1-min2; if(x==p.x) return y-p.y; return x-p.x; } public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair p = (Pair) obj; return this.x==p.x && this.y==p.y; } public Pair clone(){ return new Pair(x, y); } public String toString(){ return this.x+" "+this.y; } public void add(Pair p){ x+=p.x; y+=p.y; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
90b221f480d881166add5b95f2d0f60c
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static long[][] dp; static long maxval(int[] a,int len,boolean sta) { if(len==a.length) return 0; int lans=a[len]; int ind =0; if(sta) ind = 1; if(dp[len][ind]!=Long.MAX_VALUE) return dp[len][ind]; long left = maxval(a,len+1,!sta); long right = maxval(a,len+1,sta); if(sta) return dp[len][ind]=Math.max(left+lans, right); else return dp[len][ind]=Math.max(left-lans, right); } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int tc = scan.nextInt(); for(int tc_=0;tc_<tc;tc_++) { int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0;i<n;i++) a[i]=scan.nextInt(); int[] loc = new int[n]; for(int i =0;i<n;i++) loc[i]=scan.nextInt(); List<Integer> li = new ArrayList<>(); for(int i = 0;i<n;i++) { if(loc[i]!=1) li.add(a[i]); } int k=0; Collections.sort(li,Collections.reverseOrder()); for(int i=0;i<n;i++) { if(loc[i]==1) { System.out.print(a[i]+" "); }else { System.out.print(li.get(k)+" "); k++; } } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
b4f34bccb8a15502d42a2c2be42dfbf3
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=1; t=sc.nextInt(); // int t=Integer.parseInt(br.readLine()); while(--t>=0){ int n=sc.nextInt(); ArrayList<Integer> unlock=new ArrayList<>(); // ArrayList<Integer> ans=new ArrayList<>(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); if(arr[i]==0) unlock.add(a[i]); } Collections.sort(unlock); int k=unlock.size()-1; for(int i=0;i<n;i++){ if(arr[i]==1) System.out.print(a[i]+" "); else System.out.print(unlock.get(k--)+" "); } System.out.println(); } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
5f91b9c5be929371f67c57c84521805d
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
//package codeforces; import java.io.IOException; import java.util.*; import java.util.InputMismatchException; /** * @author muhossain * @since 2020-10-01 */ public class B1418 { public static void main(String[] args) { FasterScanner fs = new FasterScanner(); int T = fs.nextInt(); StringBuilder output = new StringBuilder(); for (int t = 0; t < T; t++) { int n = fs.nextInt(); int[] nums = new int[n]; int[] flags = new int[n]; for (int i = 0; i < nums.length; i++) { nums[i] = fs.nextInt(); } List<Integer> moveables = new ArrayList<>(); for (int i = 0; i < flags.length; i++) { flags[i] = fs.nextInt(); if (flags[i] == 0) { moveables.add(nums[i]); } } moveables.sort(Collections.reverseOrder()); int m = 0; StringBuilder tmp = new StringBuilder(); for (int i = 0; i < nums.length; i++) { if (flags[i] == 0) { tmp.append(moveables.get(m++)).append(" "); } else { tmp.append(nums[i]).append(" "); } } output.append(tmp.substring(0, tmp.length() - 1)).append("\n"); } System.out.print(output); } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private 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; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
83b1fdce9b1b6124bc4bf62781485409
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { // static FastReader sc= new FastReader(); static ArrayList<Integer> C; static ArrayList<Integer> B; static int mod=(int)1e9+9; static long dp[]; static int k; static StringBuilder as=new StringBuilder(); static InputReader rd=new InputReader(System.in); public static void main(String[] args) { //HashMap<Long,Long>map =new HashMap<Long, Long>(); //code int t=rd.readInt(); while(t-->0) { int n=rd.readInt(); int a[]=new int[n]; int l[]=new int[n]; for(int i=0;i<n;i++) { a[i]=rd.readInt(); } for(int i=0;i<n;i++) { l[i]=rd.readInt(); } int curr=0; for(int i=0;i<n;i++) { //if(curr<0)break; int min=Integer.MIN_VALUE; int p=-1; if(l[i]==1)continue; for(int j=i+1;j<n;j++) { if(l[j]==1)continue; if(min<a[j]) { min=Math.max(min, a[j]); p=j; } } if(min>a[i]) { curr+=min; int k=a[p]; a[p]=a[i]; a[i]=k; } } for(int i=0;i<n;i++)System.out.print(a[i]+" "); System.out.println(); } } void BFS(int s,int n) { boolean visited[]= new boolean[n]; LinkedList<Integer> q=new LinkedList<>(); } static int MSB(int z) { for (int i=20; i>=0; i--) { if (((z>>i)&1)!=0) return i; } return -1; } static long ans=(long)1e18; static void dfs(int s,ArrayList<ArrayList<Integer>> adj,boolean []visited) { visited[s]=true; for(int i:adj.get(s)) { if(!visited[i])dfs(i, adj, visited); } } static boolean isPowerOfTwo (int x) { /* First x in the below expression is for the case when x is 0 */ return x!=0 && ((x&(x-1)) == 0); } //extended Euclidean Algorithm public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static boolean isPrime(int n) { //check if n is a multiple of 2 if (n%2==0) return false; //if not, then just check the odds for(int i=3;i<=Math.sqrt(n);i+=2) { if(n%i==0) return false; } return true; } static long solve(long n) { long sum=(n*(n+1)/2); long l=sum/2; if(n==3) { return 2; } long k=n; if(sum%2==0) { long j=n; int c=1; boolean flag=false; long s=0; while(j<l) { n--; c++; j+=n; if(j==l) {flag =true;s=n-1;} } long point =l-(j-k); long e=0; if(flag) { e=s*(s-1)/2+(k-s)*(k-s-1)/2; } //System.out.println(e+" "+c); return (c+e); } else return 0; } static class solver{ int d; double w; public solver(int d,double w) { this.d=d; this.w=w; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } static int c=0; static void DFSUtil(int s,ArrayList<ArrayList<solver>> adj,int V,boolean visited[],double pw) { visited[s]=true; c++; // System.out.print(c+" "); for(solver i:adj.get(s)) { if(pw>i.w) { //System.out.println(pw+" "+i.w+" "+(pw>i.w)); continue;} if(!visited[i.d]) { DFSUtil(i.d,adj,V,visited,i.w); } } } public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } static class Ungraph{ int V,E; Edge edge[]; class Edge{ int src,dest; }; public Ungraph(int v,int e) { // TODO Auto-generated constructor stub V=v; E=e; edge=new Edge[e]; for(int i=0;i<e;i++) { edge[i]=new Edge(); } } class subset{ int parent; int rank; } int find(subset subsets[],int i) { if(subsets[i].parent!=i) { subsets[i].parent=find(subsets,subsets[i].parent); } return subsets[i].parent; } //finding union void Union(subset subsets[],int x,int y) { int xroot=find(subsets,x); int yroot=find(subsets,y); if(subsets[xroot].rank<subsets[yroot].rank)subsets[xroot].parent=yroot; if(subsets[xroot].rank<subsets[yroot].rank)subsets[yroot].parent=xroot; else { subsets[xroot].parent = yroot; subsets[yroot].rank++; } } int isCycle(Ungraph graph) { subset subsets[]=new subset [graph.V]; for(int i=0;i<graph.V;i++) { subsets[i] = new subset(); subsets[i].parent=i; subsets[i].rank=0; } for(int i=0;i<graph.E;i++) { int x=find(subsets,graph.edge[i].src); int y=find(subsets,graph.edge[i].dest); if(x==y)return 1; graph.Union(subsets, x, y); } return 0; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
f4e0a3d528d923328863c0924ab4668a
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
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.Collections; public class NegativePrefix { public static void main(String[] args) throws Exception { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int test,size; String line; int [] input; int [] bin; //int [] temp; ArrayList<Integer> temp = new ArrayList<Integer>(); test=Integer.parseInt(sc.readLine()); while(test>0) { temp = new ArrayList<Integer>(); size=Integer.parseInt(sc.readLine()); input=new int [size]; bin=new int [size]; // temp=new int [size]; line = sc.readLine(); String [] listI = line.split(" "); line = sc.readLine(); String [] listB = line.split(" "); for(int i=0;i<size;i++) { input[i]=Integer.parseInt(listI[i]); bin[i]=Integer.parseInt(listB[i]); if(bin[i]==0) { //temp[i]=input[i]; temp.add(input[i]); } } /*for(int i :temp) { System.out.print(i + " "); }*/ //System.out.println(); Collections.sort(temp, Collections.reverseOrder()); /*for(int i :temp) { System.out.print(i + " "); } System.out.println(); */ int c=0; for(int j=0;j<size;j++) { if(bin[j]==0) { //System.out.println(c+"---" + temp.get(c)); input[j]=temp.get(c); c++; } } for(int i=0;i<size;i++) { System.out.print(input[i] + " "); } System.out.println(); test--; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
e32da142fcac03e57548826c8094841f
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class NegativePrefix { public static void main(String[] args) throws Exception { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int test,size; String line; int [] input; int [] bin; ArrayList<Integer> temp = new ArrayList<Integer>(); test=Integer.parseInt(sc.readLine()); while(test>0) { temp = new ArrayList<Integer>(); size=Integer.parseInt(sc.readLine()); input=new int [size]; bin=new int [size]; line = sc.readLine(); String [] listI = line.split(" "); line = sc.readLine(); String [] listB = line.split(" "); for(int i=0;i<size;i++) { input[i]=Integer.parseInt(listI[i]); bin[i]=Integer.parseInt(listB[i]); if(bin[i]==0) { temp.add(input[i]); } } Collections.sort(temp, Collections.reverseOrder()); int c=0; for(int j=0;j<size;j++) { if(bin[j]==0) { input[j]=temp.get(c); c++; } } for(int i=0;i<size;i++) { System.out.print(input[i] + " "); } System.out.println(); test--; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
10787db0084c678d6bc66e0398d955d9
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); int a[]=sc.intArr(n); int b[]=sc.intArr(n); ArrayList<Integer> q=new ArrayList<>(); long neg=0; long pos=0; for (int i = 0; i < b.length; i++) { if(b[i]==0) { q.add(a[i]); if(a[i]<0) neg+=a[i]; else pos+=a[i]; } } Collections.sort(q); int g=0; int w[]=new int[n]; int e[]=new int[n]; for (int i = 0; i < b.length; i++) { if(b[i]==0) { w[i]=q.get(g++); } else w[i]=a[i]; } Collections.sort(q,Collections.reverseOrder()); g=0; for (int i = 0; i < b.length; i++) { if(b[i]==0) { e[i]=q.get(g++); } else e[i]=a[i]; } int sum=0; int x=-1; for (int i = 0; i < e.length; i++) { sum+=w[i]; if(sum<0) x=i; } sum=0; int r=-1; for (int i = 0; i < e.length; i++) { sum+=e[i]; if(sum<0) r=i; } if(x<r) { for(int z:w) pw.print(z+" "); } else { for(int z:e) pw.print(z+" "); } pw.println(); } pw.flush(); } /////////////////////////////////////////////////////////////////////////////////////////// static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static class pair implements Comparable<pair> { int x, y; pair(int s, int d) { x = s; y = d; } @Override public int compareTo(pair p) { return (x == p.x && y == p.y) ? 0 : 1; } @Override public String toString() { return x + " " + y; } } static long mod(long ans, int mod) { return (ans % mod + mod) % mod; } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int log(int n, int base) { int ans = 0; while (n + 1 > base) { ans++; n /= base; } return ans; } static long pow(long b, long e) { long ans = 1; while (e > 0) { if ((e & 1) == 1) ans = ((ans * 1l * b)); e >>= 1; { } b = ((b * 1l * b)); } return ans; } static int powmod(int b, long e, int mod) { int ans = 1; b %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b) % mod); e >>= 1; b = (int) ((b * 1l * b) % mod); } return ans; } static int ceil(int a, int b) { int ans = a / b; return a % b == 0 ? ans : ans + 1; } static long ceil(long a, long b) { long ans = a / b; return a % b == 0 ? ans : ans + 1; } static HashMap<Integer, Integer> compress(int a[]) { TreeSet<Integer> ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } // Returns nCr % p static int C[]; static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; if (C[r] != 0) return C[r]; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public int[] intArr(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] longArr(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(Integer[] x2) { int n = x2.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = x2[i]; x2[i] = x2[r]; x2[r] = tmp; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
26fc67886f6bfbb9e98651ff60992fe7
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out); int T =fr.nextInt() ; while (T-->0) solve(fr , op); op.flush(); op.close(); } }, "1", 1 << 26).start(); } static void solve (FastReader fr , PrintWriter op) { int N =fr.nextInt() ,A[] =new int[N+1] ,i ,j ; boolean lock[] =new boolean[N+1] ; PriorityQueue<Integer> unLock =new PriorityQueue<>(N,Collections.reverseOrder()) ; for (i =1 ; i<=N ; ++i) A[i] =fr.nextInt() ; for (i =1 ; i<=N ; ++i) { j =fr.nextInt() ; if (j==0) unLock.add(A[i]) ; else lock[i] =true ; } for (i =1 ; i<=N ; ++i) { if (lock[i]) op.print(A[i]+" ") ; else op.print(unLock.poll()+" ") ; } op.println() ; } 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(); } String nextLine() { String str =""; try { str =br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()) ; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
9cfd11eefd0c9a4845d6a7f99b5fcbb9
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.PrintWriter; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.nextLine()); for(int a = 0; a < t; a++) { int n = in.nextInt(); long[] arr = new long[n]; for(int i = 0; i < n; i++) { arr[i] = in.nextLong(); } long[] locked = new long[n]; ArrayList<Long> lock = new ArrayList<Long>(); for(int i = 0; i < n; i++) { locked[i] = in.nextLong(); if(locked[i] == 0) { lock.add(arr[i]); } } Collections.sort(lock); for(int i = 0; i < n; i++) { if(locked[i] == 0) { arr[i] = lock.get(lock.size() - 1); lock.remove(lock.size() - 1); } out.print(arr[i] + " "); } out.println(); } out.close(); } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
14ab1589578a25fd07710130158b2595
train_001.jsonl
1600094100
You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$; $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$; $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j &lt; 0$$$. If there are no $$$j$$$ such that $$$p_j &lt; 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { public static void main(String[] args) throws IOException{ try { FastScanner fs = new FastScanner(); int t = fs.nextInt(); while(t-->0) { int n =fs.nextInt(); int l[]=new int[n]; int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=fs.nextInt(); } for(int i=0;i<n;i++) { l[i]=fs.nextInt(); } Vector<Integer> v1 =new Vector<>(); Vector<Integer> v2 =new Vector<>(); for(int i=0;i<n;i++) { if(l[i]==0) { v1.add(a[i]); } } Collections.sort(v1); for(int i=v1.size()-1;i>=0;i--) { v2.add(v1.get(i)); } int j=0; for(int i=0;i<n;i++) { if(l[i]==0) { a[i]=v2.get(j); j++; } } for(int i=0;i<n;i++) { System.out.print(a[i]+" "); } System.out.println(); } } catch (Exception e) { return; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"]
2 seconds
["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"]
NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j &lt; 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k &lt; 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.
Java 8
standard input
[ "sortings", "greedy" ]
9ef180b33717e4d6a21b4c5bb855e15b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.
1,300
Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j &lt; 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.
standard output
PASSED
fba88da5fc57d4d1f0bc7edabb126ae4
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.*; import java.io.*; public class ZeroRem { public static void main(String[] args) throws IOException { Scanner scn=new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ int n = scn.nextInt(),k = scn.nextInt(); int arr[][] = new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ arr[i][j]=0; } } if(k%n == 0){ System.out.println(0); } else{ System.out.println(2); } for(int i=0;i<n && k>0;i++){ for(int j=0;j<n && k>0;j++){ arr[j][(i+j)%n] = 1; k--; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ System.out.print(arr[i][j]); } System.out.println(); } } } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
02996182591c52542e7462f80929b79f
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.util.*; public class CP { static long startTime; static long endTime; static Boolean [] prime ; static Scanner sc = new Scanner(System.in); 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 int lowerBound (Integer[] array, int length, int value) { int l = 0; int r = length; while (l < r) { int mid = (l + r) / 2; if (value < array[mid]) { r = mid; } else { l = mid + 1; } } return l; } public static long gcd(long a, long b){ if (b == 0) return a; else return gcd(b, a % b); } public static long countDivs(long n ){ int cn=0; long sqr = (long)Math.sqrt(n); for (long i = 1; i<=sqr ; ++i) { if(n%i==0){ ++cn; } } cn*=2; if(sqr*sqr==n) cn--; return cn; } static void prime(int x) { //sieve algorithm. nlog(log(n)). prime=new Boolean[ (x+1)]; Arrays.fill(prime,true); prime[0] = prime[1] = false; for (int i = 2; i * i <= x ; i++) if (prime[i]) for (int j = i * i; j <= x; j += i) prime[j] = false; } static int[] sum; static void cumulitiveSum( int [] arr){ sum = new int[arr.length]; sum[0]=arr[0]; for (int i = 1; i <arr.length; i++) { sum[i]=arr[i]+sum[i-1]; } } static boolean isEven(long x ){ return x % 2 == 0; } static boolean isPrime(long x ){ boolean flag = true; int sqr = (int)Math.sqrt(x); if(x<2) return false; for (int i = 2; i <=sqr; i++) { if(x%i==0){ flag=false; break; } } return flag; } public static void main(String [] args) { startTime = System.currentTimeMillis(); int T = sc.nextInt();while (T--!=0) { solve(); } endTime = System.currentTimeMillis(); long duration= endTime-startTime; //System.out.println(duration); } public static void solve() { ////////////////////////////////////////////////////////////////////// int n =sc.nextInt(); int k = sc.nextInt(); int [][] arr= new int[n][n]; if(k%n==0) System.out.println(0); else System.out.println(2); for (int i = 0; i <n && k>=1 ; i++) { for (int j = 0; k>=1 && j <n ; j++) { arr[j][(i+j)%n]=1; k--; } } for (int i = 0; i < n; i++) { for (int j = 0; j <n ; j++) { System.out.print(arr[i][j]); } System.out.println(); } /////////////////////////////////////////////////////////////////////// } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
96e656c337e7d4398134057b731a7eeb
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void solver(InputReader sc, PrintWriter out) throws Exception { int test = sc.nextInt(); for (int ii = 0; ii < test; ii++) { int n = sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[n][n]; int count = 0; while (count < k) { for (int i = 0; i < n; i++) { int j = i; while (true) { if (arr[i][j % n] == 0) { arr[i][j % n] = 1; count++; break; } j++; } if (count >= k) break; } } if(k%n==0) out.println(0); else out.println(2); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(arr[i][j]); } out.println(); } } } public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver(in, out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } } class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair p) { return (this.y - p.y); } } class Tuple implements Comparable<Tuple> { int x, y, z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(Tuple t) { if (this.z == t.z) { if (this.y == t.y) { return t.x - this.x; } else return t.y - this.y; } else return this.z - t.z; } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
9759d15ffc6d5ea591bcfb1d2ab87932
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void solver(InputReader sc, PrintWriter out) throws Exception { int test = sc.nextInt(); for (int ii = 0; ii < test; ii++) { int n = sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[n][n]; int count = 0; while (count < k) { for (int i = 0; i < n; i++) { int j = i; while (true) { if (arr[i][j % n] == 0) { arr[i][j % n] = 1; count++; break; } j++; } if (count >= k) break; } } if(k%n==0) out.println(0); else out.println(2); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(arr[i][j]); } out.println(); } } } public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver(in, out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } } class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair p) { return (this.y - p.y); } } class Tuple implements Comparable<Tuple> { int x, y, z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(Tuple t) { if (this.z == t.z) { if (this.y == t.y) { return t.x - this.x; } else return t.y - this.y; } else return this.z - t.z; } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
fda8d7ea9cc906be88a28501ceab8829
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class file { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static INPUT sc = new INPUT(br); static int INF = Integer.MAX_VALUE,NEG_INF = Integer.MIN_VALUE,SEM_INF = INF / 2,count = 0,MOD = 1000000007,ops = 0; static long MAX_INF = Long.MAX_VALUE; static BigInteger B = new BigInteger("1"); //static Scanner sc = new Scanner(System.in); public static void main (String[] args) throws Exception { try{ int t = sc.getInt(br.readLine()); while(t-- > 0) { testCase(); } out.flush(); }catch(Exception e){ System.out.println("Exception Occured!"); e.printStackTrace(); } } public static void testCase() throws Exception { int n = sc.nextInt(),k = sc.nextInt(); if(k == 0){ writeln(0); for(int x = 0;x < n;x++){ for(int y = 0;y < n;y++) write("0"); writeln(); } return; } if(k % n == 0) writeln(0); else writeln(2); int a[][] = new int[n][n]; for(int x = 0;x < n && k > 0;x++){ for(int y = 0;y < n && k > 0;y++){ k--; int i = y; int j = (x + y) % n; a[i][j] = 1; } } for(int x = 0;x < n;x++){ for(int y = 0;y < n;y++) write(a[x][y] + ""); writeln(); } } public static void writeln() throws Exception { out.write("\n"); } public static void write(Object o) throws Exception { out.write(String.valueOf(o)); } public static void writeln(Object o) throws Exception { out.write(String.valueOf(o) + "\n"); } public static void println() { System.out.println(); } public static void print(Object o) { System.out.print(String.valueOf(o)); } public static void println(Object o) { System.out.println(String.valueOf(o)); } } class INPUT { BufferedReader br; StringTokenizer st; public INPUT(BufferedReader br) { this.br = br; } /*RAW INPUTS*/ public String next() throws Exception { if(st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public String trimLine() throws Exception { try{ return br.readLine().trim(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public String nextLine() throws Exception { try{ return br.readLine(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public float nextFloat() throws Exception { return Float.parseFloat(next()); } public int [] getIntArray( String s) { String input[] = s.split(" "); int res[] = new int[input.length]; for(int x = 0;x < res.length;x++) res[x] = getInt(input[x]); return res; } public long [] getLongArray( String s) { String input[] = s.split(" "); long res[] = new long[input.length]; for(int x = 0;x < res.length;x++) res[x] = getLong(input[x]); return res; } public double [] getDoubleArray( String s) { String input[] = s.split(" "); double res[] = new double[input.length]; for(int x = 0;x < res.length;x++) res[x] = getDouble(input[x]); return res; } public int[][] getIntMatrix(String s,int r,int c) { int i = 0;int mat[][] = new int[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Integer.parseInt(st[i++]); return mat; } public long[][] getlongMatrix(String s,int r,int c) { int i = 0;long mat[][] = new long[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Long.parseLong(st[i++]); return mat; } public int getInt(String s) { return Integer.parseInt(s); } public long getLong(String s) { return Long.parseLong(s); } public float getFloat(String s) { return Float.parseFloat(s); } public double getDouble(String s) { return Double.parseDouble(s); } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
7e041e80458088a89f1853e1e552b14a
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); Writer w=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt();int k=sc.nextInt(); int[][] a=new int[n][n]; int c=0,i=0,j=0,temp=0,tempc=0,ans=0; while(c<k){ tempc=0; j=0; i=temp; for(;j<n;){ c++; a[i%n][j%n]=1; // System.out.println(i+" "+j); i++;j++; tempc++; if(c==k)break; if(tempc==n)break; } if(tempc==n)ans=0; else ans=2; temp++; if(c==k || temp == n)break; } System.out.println(ans); for(i=0;i<n;i++){ for(j=0;j<n;j++){ System.out.print(a[i][j]); } System.out.println(); } } w.flush(); w.close(); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
46b285234c579beedc0b0a34f1cb1c30
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.*; import java.lang.*; public class untitled1 { public static void main (String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int i=0;i<t;i++) { int n=s.nextInt(); int k=s.nextInt(); int[][] arr=new int[n][n]; int [] col=new int[n]; int [] row=new int[n]; int m=k/n; for(int j=0;j<n;j++) { int p=m; int q=j; while(p!=0) { arr[q][j]=1; row[q]+=1; col[j]+=1; q+=1; p-=1; if(q==n) q=0; } } for(int j=0;j<k%n;j++) { int q=(col[j]+j)%n; if(q==n) q=0; arr[q][j]=1; row[q]+=1; col[j]+=1; } int ma1=row[0],ma2=col[0]; int mi1=row[0],mi2=col[0]; for(int j=0;j<n;j++) { if(ma1<row[j]) ma1=row[j]; if(ma2<col[j]) ma2=col[j]; if(mi1>row[j]) mi1=row[j]; if(mi2>col[j]) mi2=col[j]; } System.out.println((int)Math.pow((ma1-mi1),2)+(int)Math.pow((ma2-mi2),2)); for(int j=0;j<n;j++) {for(int z=0;z<n;z++) System.out.print(arr[j][z]); System.out.println(); }} } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
3a873118f8170ac986dc5d34a22e0150
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.FileOutputStream; import java.io.IOException; import java.util.StringTokenizer; public class Pd{ public static void main(String[] args) throws IOException{ FastReader sc = new FastReader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out),"ASCII"),512); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int k = sc.nextInt(); int[][] a = new int[n][n]; int[] r = new int[n]; int[] c = new int[n]; int one = 0; loop:for(int i=0;i<n;i++){ int temp = i; for(int j=0;j<n;j++){ if(one == k) break loop; a[temp][j] = 1; c[j]++; r[temp]++; temp = (temp+1)%n; one++; } } int cmax = 0; int rmax = 0; int cmin = Integer.MAX_VALUE; int rmin = Integer.MAX_VALUE; for(int i=0;i<n;i++){ cmin = Math.min(cmin,c[i]); cmax = Math.max(cmax,c[i]); rmin = Math.min(rmin,r[i]); rmax = Math.max(rmax,r[i]); } int temp = (int)Math.pow((cmax-cmin),2) + (int)Math.pow((rmax-rmin),2); out.write(temp + ""); out.write('\n'); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ out.write(a[i][j] + ""); } out.write('\n'); } out.flush(); } } } 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\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
d942ad0192fb23e6ee6cea893bd9de1e
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.Scanner ; import java.util.ArrayList ; import java.util.Collections ; public class firstjava { public static void main( String[ ] args ) { Scanner in = new Scanner( System.in ) ; int t = 1 ; t = in.nextInt( ) ; while( t -- != 0 ) { long n = in.nextLong( ) ; long k = in.nextLong( ) ; if( k % n == 0 ) System.out.println( "0" ) ; else System.out.println( "2" ) ; Integer[][] arr = new Integer[ ( int ) n ][ (int) n ] ; for( int i = 0 ; i < n ; i ++ ) { for( int j = 0 ; j < n ; j ++ ) { arr[ i ][ j ] = 0 ; } } int ii = 0 , jj = 0 ; while( k -- != 0 ) { arr[ ii ][ jj ] ++ ; ii ++ ; jj ++ ; if( jj == ( int ) n ) { jj = 0 ; } if( ii == ( int ) n ) { ii = 0 ; jj ++ ; jj = jj % (int) n ; } } for( int i = 0 ; i < n ; i ++ ) { for( int j = 0 ; j < n ; j ++ ) { System.out.print( arr[ i ][ j ] ) ; } System.out.println( ) ; } System.out.println( ) ; } } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
0837bf0788655f4d6152cd05b1545ff1
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); DGrid00100 solver = new DGrid00100(); solver.solve(1, in, out); out.close(); } static class DGrid00100 { public void solve(int testNumber, Input in, PrintWriter out) { int kase = in.nextInt(); while(kase-->0) { int n = in.nextInt(), k = in.nextInt(), arr[][] = new int[n][n]; if(k%n==0) { out.println(0); }else { out.println(2); } for(int i = 0; i<n&&k>0; i++) { for(int j = 0; j<n&&k>0; j++) { arr[j][(j+i)%n] = 1; k--; } } for(int i = 0; i<n; i++) { for(int j = 0; j<n; j++) { out.print(arr[i][j]); } out.println(); } } } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); try { st = new StringTokenizer(br.readLine()); }catch(IOException e) { e.printStackTrace(); } } public boolean hasNext() { try { while(!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken("\r\n\t\f "); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
0d095413223fdace107ac845e26a3e8a
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class hello2 {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 sum (String s) { String s1 = ""; if(s.contains("a")) s1+="a"; if(s.contains("e")) s1+="e"; if(s.contains("i")) s1+="i"; if(s.contains("o")) s1+="o"; if(s.contains("u")) s1+="u"; return s1; } public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } public static void main(String args[]) { FastReader input =new FastReader(); int t = input.nextInt(); while(t-->0) { int n = input.nextInt(); int k = input.nextInt(); if(k==0) { System.out.println(0); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(0); } System.out.println(); } continue; } else if(n==k) { System.out.println(0); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) System.out.print(1); else System.out.print(0); } System.out.println(); } } else if(k<n && k!=0) { int count = 0; System.out.println(2); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j && count<k) { System.out.print(1); count++; } else System.out.print(0); } System.out.println(); } } else { int a[][] = new int[n][n]; if(k%n==0) { System.out.println(0); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) a[i][j] = 1; } } int temp = k/n -1; int i =0; int j =0; for(int l=0;l<temp;l++) { // System.out.println("i"); for(i=l+1,j=0;i<n;i++) { a[i][j] = 1; // System.out.println(i + " " + j); j++; } // System.out.println("j"); for(j=n-(l+1),i=0;j<n;j++) { a[i][j] = 1; // System.out.println(i + " " + j); i++; } } for( i=0;i<n;i++) { for( j=0;j<n;j++) { System.out.print(a[i][j]); } System.out.println(); } } else { System.out.println(2); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) a[i][j] = 1; } } int temp = k/n; int i =0; int j =0; int count =n; for(int l=0;l<temp;l++) { if(count==k) break; for(i=l+1,j=0;i<n;i++) { if(count==k) break; a[i][j] = 1; j++; count++; } for(j=n-(l+1),i=0;j<n;j++) { if(count==k) break; a[i][j] = 1; i++; count++; } } for( i=0;i<n;i++) { for( j=0;j<n;j++) { System.out.print(a[i][j]); } System.out.println(); } } } } } // //Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0])); //Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0])); decreasing order public static boolean range(int x,int y,int n,int m) { if(x<0 || x>n-1 || y<0 || y>m-1) return false; return true; } public static int even_element(int b[],int n) { int c[] = new int[n/2 + 1]; int l=0; for(int i=1;i<n;i+=2) { c[l] = b[i]; System.out.print(c[l] + " "); l++; } System.out.println(); if(c.length!=1) { return even_element(c,n/2); } else return c[0]; } static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } } class Pair { int a; int b; Pair(int a,int b) { this.a=a; this.b=b; } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
ca290c17b38670bbe13cc143d8de0edb
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); ///v!=c first type ///v==c second type ///m<=min ///n<=max int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int k=in.nextInt(); int [] [] mat; Solver solver=new Solver(); mat=solver.solve(n,k); // for(int i=0; i<n; i++) { // out.println(Arrays.toString(mat[i])); // } if(k%n==0) out.println(0); else out.println(2); for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { out.print(mat[i][j]); } out.println(); } } out.close(); } static class Solver{ int[][] solve(int n, int k){ int [] [] mat=new int[n][n]; int count=0; int row=0, col=0; while(count<k) { mat[row%n][col%n]=1; count++; row++; col++; if(count%n==0) { row=count/n; } } return mat; } } static class InputReader{ BufferedReader br; StringTokenizer tokenizer; InputReader(InputStream stream){ br=new BufferedReader(new InputStreamReader(System.in)); tokenizer=new StringTokenizer(""); } String next(){ while(!tokenizer.hasMoreTokens()) { try { tokenizer=new StringTokenizer(br.readLine()); }catch(IOException e){ System.out.println(e); } } return tokenizer.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
438a7049d773178c93036125d6a26e05
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
// 1 0 // 1 1 // 2 0 // 2 1 // 2 2 // 2 3 // 2 4 // 3 0 // 3 1 // 3 2 // 3 3 // 3 4 // 3 5 // 3 6 // 3 7 // 3 8 // 3 9 // 4 0 // 4 1 // 4 2 // 4 3 // 4 4 // 4 5 // 4 6 // 4 7 // 4 8 // 4 9 // 4 10 // 4 11 // 4 12 // 4 13 // 4 14 // 4 15 // 4 16 // 5 0 // 5 1 // 5 2 // 5 3 // 5 4 // 5 5 // 5 6 // 5 7 // 5 8 // 5 9 // 5 10 // 5 11 // 5 12 // 5 13 // 5 14 // 5 15 // 5 16 // 5 17 // 5 18 // 5 19 // 5 20 // 5 21 // 5 22 // 5 23 // 5 24 // 5 25 /** * Date: 20 Aug, 2020 * Link: https://codeforces.com/contest/1371/problem/D * * @author: Prasad Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; public class D_1371 { public static void main(String[] args) throws IOException { FastIO in = new FastIO(args); int t = in.ni(); while (t-- > 0) { int n = in.ni(); int k = in.ni(); int a[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k > 0) { a[j][(i + j) % n]++; k--; } } } int max_r = 0; int min_r = n; int max_c = 0; int min_c = n; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { count += a[i][j]; } max_r = Math.max(max_r, count); min_r = Math.min(min_r, count); } for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { count += a[j][i]; } max_c = Math.max(max_c, count); min_c = Math.min(min_c, count); } int f_1 = (int) (Math.pow(max_r - min_r, 2) + Math.pow(max_c - min_c, 2)); System.out.println(f_1); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j]); } System.out.println(); } } in.bw.flush(); } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; public FastIO(String[] args) throws IOException { if (args.length > 1) { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(args[0])))); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(args[1])))); } else { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); } s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][][] gwtree(int n) throws IOException { int m = n - 1; int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = i + 1; to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][][] gwg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][] gtree(int n) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[n - 1]; int to[] = new int[n - 1]; int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 1; to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < n - 1; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
fb03088bc78b29e334b30c9f697a9523
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.sql.Array; import java.util.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000001]; // line length int cnt = 0, c; while((c = read()) <= ' '){} do{ if (c == 13 || c == 10) break; buf[cnt++] = (byte) c; }while ((c = read()) != -1); return new String(buf, 0, cnt); } public String next() throws IOException { byte[] buf = new byte[2000001]; // line length int cnt = 0, c; while((c = read()) <= ' '){} do{ buf[cnt++] = (byte) c; }while ((c = read()) != -1 && c > ' '); return new String(buf, 0, cnt); } public int[] nextArray(int N) throws IOException{ int[] arr = new int[N]; for(int i = 0;i<N;i++)arr[i] = nextInt(); return arr; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' '){c = read();} boolean neg = (c == '-'); if (neg)c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void print(long[] arr){ for(int i = 0 ;i<arr.length;i++){ System.out.print((arr[i])+" "); } System.out.println(""); } public static void print(int[][] arr){ for(int i = 0 ;i<arr.length;i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(""); } } public static void print(ArrayList<Integer> arr){ for(int i:arr){ System.out.print(i+" "); } System.out.println(""); } public static long prime = 1000000007; public static void main(String[] args) throws IOException { Reader sc = new Reader(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int tc = sc.nextInt(); while(tc-- > 0){ int N = sc.nextInt(); int K = sc.nextInt(); int[][] arr = new int[N][N]; int[] next = new int[N]; for(int i = 0;i<N;i++)next[i] = i; while(K>0){ for(int i = 0;i<N;i++){ if(K==0)break; arr[i][next[i]] = 1; next[i] = (next[i]+1)%N; K--; } } int minr = Integer.MAX_VALUE; int minc = Integer.MAX_VALUE; int maxr = -1; int maxc = -1; for(int i = 0;i<N;i++){ int sum = 0; for(int j = 0;j<N;j++){ sum += arr[i][j]; } minr = Math.min(sum,minr); maxr = Math.max(sum,maxr); } for(int i = 0;i<N;i++){ int sum = 0; for(int j = 0;j<N;j++){ sum += arr[j][i]; } minc = Math.min(sum,minc); maxc = Math.max(sum,maxc); } int ans = ((maxr - minr)*(maxr-minr)) + ((maxc - minc)*(maxc-minc)); pw.println(ans); for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ pw.print(arr[i][j]); } pw.println(); } } pw.flush(); } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
8ace214442636a6b20ea76da36c03728
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); //System.out.println("Kickstart baby!!"); int test=s.nextInt(); while(test-->0) { int n=s.nextInt(); int k=s.nextInt(); int[][] a=new int[n][n]; if(k<=n && k!=0) { int c=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { a[i][j]=1; c++; } if(c==k) break; } if(c==k) break; } } else if(k!=0) { int c=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { a[i][j]=1; c++; } } } int[] b=new int[n]; for(int i=0;i<n;i++) b[i]=i+1; while(true) { for(int i=0;i<n;i++) { if(b[i]==n) b[i]=0; a[i][b[i]]=1; b[i]++; if(b[i]==n) b[i]=0; c++; if(c==k) break; } if(c==k) break; } } int ans = f1(a,n); System.out.println(ans); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) System.out.print(a[i][j]); System.out.println(); } } } public static int f1(int[][] a, int n) { int[] r=new int[n]; int[] c=new int[n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { r[i] += a[i][j]; c[j]+=a[i][j]; } } int rmax=0; int rmin=n; int cmax=0; int cmin=n; for(int i=0;i<n;i++) { if(r[i]>rmax) rmax=r[i]; if(r[i]<rmin) rmin=r[i]; if(c[i]>cmax) cmax=c[i]; if(c[i]<cmin) cmin=c[i]; } return ((rmax-rmin)*(rmax-rmin) + (cmax-cmin)*(cmax-cmin)); } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output