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
082558f9b33596477f7218e62ea9fa6d
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.*; public class tmp { public static void main(String [] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); int min = 0, max= n+1; for(int i=1; i<=k; i++){ if(i%2 == 0){ max = (n-(i-1)/2); System.out.print(max + " "); }else{ min = (i+1)/2; System.out.print(min + " "); } } if(k%2 == 0) for(int i=max-1;i>=min+1; i--) System.out.print(i+" "); else for(int i=min+1; i<=max-1; i++) System.out.print(i+" "); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
21d2ae3e03c3be1f28eab8b486aba600
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
//package round275; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), K = ni(); int inf = 1, sup = n; for(int i = 0;i < K;i++){ if(i % 2 == 0){ out.print(inf + " "); inf++; }else{ out.print(sup + " "); sup--; } } if(K % 2 == 0){ for(int i = K;i < n;i++){ out.print(sup + " "); sup--; } }else{ for(int i = K;i < n;i++){ out.print(inf + " "); inf++; } } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
eb9cff744fd7c01ae9eff434685b6cfb
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Mahmoud Aladdin <aladdin3> */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader jin, OutputWriter jout) { int n = jin.int32(); int k = jin.int32(); int ei = 1 + k; int si = 1; boolean first = true; while(si <= ei) { if(si != 1) jout.print(' '); if(first) jout.print(si++); if(!first) jout.print(ei--); first = !first; } si = 1 + k + 1; while(si <= n) { jout.print("", si++); } jout.println(); } } class InputReader { private static final int bufferMaxLength = 1024; private InputStream in; private byte[] buffer; private int currentBufferSize; private int currentBufferTop; private static final String tokenizers = " \t\r\f\n"; public InputReader(InputStream stream) { this.in = stream; buffer = new byte[bufferMaxLength]; currentBufferSize = 0; currentBufferTop = 0; } private boolean refill() { try { this.currentBufferSize = this.in.read(this.buffer); this.currentBufferTop = 0; } catch(Exception e) {} return this.currentBufferSize > 0; } private Byte readChar() { if(currentBufferTop < currentBufferSize) { return this.buffer[this.currentBufferTop++]; } else { if(!this.refill()) { return null; } else { return readChar(); } } } public String token() { StringBuffer tok = new StringBuffer(); Byte first; while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1)); if(first == null) return null; tok.append((char)first.byteValue()); while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) { tok.append((char)first.byteValue()); } return tok.toString(); } public Integer int32() throws NumberFormatException { String tok = token(); return tok == null? null : Integer.parseInt(tok); } } class OutputWriter { private final int bufferMaxOut = 1024; private PrintWriter out; private StringBuilder output; private boolean forceFlush = false; public OutputWriter(OutputStream outStream) { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream))); output = new StringBuilder(2 * bufferMaxOut); } public OutputWriter(Writer writer) { forceFlush = true; out = new PrintWriter(writer); output = new StringBuilder(2 * bufferMaxOut); } private void autoFlush() { if(forceFlush || output.length() >= bufferMaxOut) { flush(); } } public void print(Object... tokens) { for(int i = 0; i < tokens.length; i++) { if(i != 0) output.append(' '); output.append(tokens[i]); } autoFlush(); } public void println(Object... tokens) { print(tokens); output.append('\n'); autoFlush(); } public void flush() { out.print(output); output.setLength(0); } public void close() { flush(); out.close(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
840ab5bdb364e6c50f692ce8c0d3f923
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * TODO: Insert description here. (generated by mfahim) */ public class Round275_Div1_A { public static void main(String[] args) throws Exception { int n = nextInt(); int k = nextInt(); int st = 1, end = k; int[] ar = new int[n]; for (int i = k - 1; i >= 0; i--) { ar[i--] = st; st++; if (i >= 0) { ar[i] = end; end--; } } for (int i = k; i < n; i++) { ar[i] = i + 1; } PrintWriter out = new PrintWriter(System.out); for (int i = 0; i < n; i++) { out.print(ar[i] + " "); } out.println(); out.flush(); } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static double nextDouble() throws Exception { return Double.parseDouble(next()); } static String next() throws Exception { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = br.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s); } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
98fff982f79531db3029dcbf719ce64f
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class DiversePermutation { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stk = new StringTokenizer(br.readLine()); int n,k; n = Integer.parseInt(stk.nextToken()); k = Integer.parseInt(stk.nextToken()); System.out.println(print(findPermutation(n,k))); } public static int[] findPermutation(int n,int k) { int[] ary = new int[n]; for(int i=1;i<=n;i++){ ary[i-1] = i; } int[] aryResult = new int[n]; int count = n-1; //ๅ‰ๆฎต for(int j=1,i=0;j<=k;j+=2,i++){ aryResult[j-1] = ary[i]; aryResult[j] = ary[count--]; } //ๅŽๆฎต if(k%2==0){ for(int index=k;index<n;index++){ aryResult[index] = ary[count--]; } }else{ for(int index=k;index<n;index++){ aryResult[index] = aryResult[index-1]+1; } } return aryResult; } public static String print(int[] ary){ StringBuffer sb = new StringBuffer(""); for(int i=0;i<ary.length;i++){ sb.append(ary[i]); sb.append(" "); } return sb.toString(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
fa73b87a0d6754d79f69753e2b4f6fc8
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.*; import java.util.*; public final class diverse_perm { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static boolean[] v; static int[] a; static int n,k; static void solve() { boolean b1=true,b2=false; a[1]=1; int i; v[1]=true; for(i=2;i<=n && k>0;i++) { if(b1) { a[i]=a[i-1]+k; k--; b1=false; b2=true; v[a[i]]=true; } else { a[i]=a[i-1]-k; k--; b1=true; b2=false; v[a[i]]=true; } } if(i==n+1) { for(int j=1;j<=n;j++) { out.print(a[j]+" "); } out.println(""); } else { for(int j=1;j<=n;j++) { if(!v[j]) { a[i]=j; v[j]=true; i++; } } for(int j=1;j<=n;j++) { out.print(a[j]+" "); } out.println(""); } } public static void main(String args[]) throws Exception { n=sc.nextInt(); k=sc.nextInt(); if(k==1) { for(int i=1;i<=n;i++) { out.print(i+" "); } out.println(""); } else { a=new int[n+1]; v=new boolean[n+1]; solve(); } out.close(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
74663192322334f997bc350affdb539b
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int k = sc.nextInt(); if (k % 2 == 0) { for (int i = 1; i <= k / 2; ++i) { System.out.print(i + " " + (k + 2 - i) + " "); } System.out.print(((k + 2) / 2)+ " "); } else { for (int i = 1; i <= (k + 1) / 2; ++i) { System.out.print(i + " " + (k + 2 - i) + " "); } } for (int i = k + 2; i <= n; ++i) { System.out.print(i + " "); } } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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; } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
ad89f00b755e872b0369d93436a5a0f3
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; public class Permutations { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); for (int i = 1; i < n - k; i++) { System.out.print(i + " "); } int s = n - k; int sign = 1; int c = k; for (int i = n - k; i <= n; i++) { System.out.print(s + " "); s = s + c * sign; c--; sign *= -1; } System.out.println(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
a41f409e78d8d9bbdbd7fa483e56fc5f
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.*; import java.util.*; public class Main { // main public static void main(String [] args) throws IOException { // makes the reader and writer BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // read in StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken())-1; // write to out for (int i=0;i<k;i++) { if (i%2==0) out.print((n-i/2)+" "); else out.print((i+1)/2+" "); } if (k%2==0) for (int i=n-(k+1)/2;i>(k+1)/2;i--) out.print(i+" "); else for (int i=(k+1)/2;i<=n-(k+1)/2;i++) out.print(i+" "); out.println(); // cleanup out.close(); System.exit(0); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
f61a357d518b52b815f236748dce6ee8
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Tifuera */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] answer = new int[n]; for (int i = 1; i <= k + 1; i++) { if (i % 2 == 1) { int m = i / 2; answer[k + 1 - i] = k + 1 - m; } else { answer[k + 1 - i] = i / 2; } } for (int i = k + 2; i <= n; i++) { answer[i - 1] = i; } for (int a : answer) { out.print(a + " "); } } } class InputReader { private BufferedReader reader; private String[] currentArray; private int curPointer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public int nextInt() { if ((currentArray == null) || (curPointer >= currentArray.length)) { try { currentArray = reader.readLine().split(" "); } catch (IOException e) { throw new RuntimeException(e); } curPointer = 0; } return Integer.parseInt(currentArray[curPointer++]); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
9f7990308bc538ea06207e641497ea78
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { public static void main(String[] args) { try { InputScanner scanner = new InputScanner(); int n = scanner.nextInt(); int k = scanner.nextInt(); int start = n - k; int startK = k; int start2 = start - 1; while (k > 0) { int tmp = n - k; System.out.print(n + " " + tmp + " "); n--; k -= 2; } if (startK % 2 == 0) System.out.print(n + " "); while (start2 > 0) { System.out.print(start2 + " "); start2--; } } catch (IOException e) { } } static class InputScanner { BufferedReader br; StringTokenizer st; public InputScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws IOException { String next = next(); next.length(); return Integer.parseInt(next); } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
3daffb884e070dfc5eb7a0c484bbb71c
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
/* Problem: find an order of the permutation of digits < n of length n such that |p1-p2|, |p2-p3|, ... |pn-1 - pn| has exactly k distinct values. Solution: Greedy. First noteyou can create a successive string of 1s by going in ascending or descending order Then note you can get unique numbers, by switching from high to low. Combine these strategies to make k-1 unique, and n-k 1s ex: n = 10, k = 5 1 10 2 9 8 7 6 5 4 3 9 8 7 1 1 1 1 1 1 */ import java.util.Scanner; public class CF482A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); sc.close(); StringBuilder out = new StringBuilder(); // Create k - 1 uniques diffs int low = 2; int high = n; out.append(1); int i = 0; boolean startlow = true; while (i != k-1) { if (i == k - 1) { break; } out.append(" "+high); high--; i++; startlow = !startlow; if (i == k - 1) { break; } out.append(" "+low); low++; i++; startlow = !startlow; } // Create n-k 1 diffs if (startlow) { for (int j = low; j <= high; j++) { out.append(" "+j); } } else { for (int j = high; j >= low; j--) { out.append(" "+j); } } System.out.println(out); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
be5d4cfffe2caae5707243393e0e2b38
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
public class T { private int n, k; protected void solve() { out.print(n); int i = n - 1, j = 1; for (int m = 0; m < k - 1; m++) { out.print(" "); out.print(j); if (j < i) j++; else j--; int t = j; j = i; i = t; } int d = (i > j) ? -1 : 1; while (i != j + d) { out.print(" "); out.print(i); i += d; } } protected void read() { n = in.nui(); k = in.nui(); } public static void main(String[] args) { T t = new T(); try { t.read(); t.solve(); } finally { t.out.close(); } } private static final class InputReader { private static final int EOF = -1; private final byte[] b = new byte[1024]; private int l, p; private int rb() { if (l < 0) throw new RuntimeException(); if (p < l) return b[p++]; try { while ((l = System.in.read(b)) == 0); if (l < 0) return EOF; p = 1; return b[0]; } catch (java.io.IOException e) { throw new RuntimeException(e); } } private void rw() { int b; while ((b = rb()) == ' ' || b == '\r' || b == '\n' || b == EOF); p--; } private int rui() { int n = 0, b; while ((b = rb()) >= '0' && b <= '9') n = n * 10 + (b - '0'); p--; return n; } private int nui() { rw(); return rui(); } private int rsi() { int n = 0, b, s = 0; b = rb(); if (b == '-') s = 1; else p--; while ((b = rb()) >= '0' && b <= '9') n = n * 10 + (b - '0'); p--; return s == 0 ? n : -n; } private int nsi() { rw(); return rsi(); } } private java.io.PrintWriter out = new java.io.PrintWriter(System.out); private InputReader in = new InputReader(); }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
d1853593aa64b09d7dd1a623b34a4ef1
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; public class DiversePermutations { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); for(int i=1;i<=n-k;i++) { System.out.print(i+" "); } int stop=n-k+1; int last=n; for(int i=n-k+1;i<=n;i=i+2) { System.out.print(last+" "); if(stop!=last) System.out.print(stop+" "); last--; stop++; } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
4576498368e41f206dc36cfe53ef457a
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; public class Diverse { public static void main(String[]args){ Scanner in=new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] A = new int[n]; A[0] = 1; int f = 1; int i; for (i = 1; i <= k; i++) { A[i] = A[i - 1] + f * (k - i + 1); f *= -1; } int current = k + 2; while (i < n) A[i++] = current++; for (int j = 0; j < n; j++) System.out.print(A[j] + " "); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
44860681c1405c37dd0ed5db055c73fc
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { new A().solve(); } void solve() throws IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] p = new int[n]; int cnt = 0; int minus = 1; for (int i = 1; i < n; i++) { if (cnt < k) { minus *= -1; cnt++; if (minus == -1) { p[i] = Math.abs(p[i - 1]) + 1; } else { p[i] = Math.abs(p[i - 1]); } p[i] *= minus; } else {// k p[i] = Math.abs(p[i - 1]) + 1; p[i] *= minus; } } int min = 0; for (int i = 0; i < p.length; i++) { min = Math.min(min, p[i]); } for (int i = 0; i < p.length; i++) { p[i] -= min; p[i]++; } StringBuilder sb = new StringBuilder(); sb.append(p[0]); for (int i = 1; i < p.length; i++) { sb.append(" " + p[i]); } System.out.print(sb); } // // // // // // // // // // // // // class FastScanner { private InputStream _stream; private byte[] _buf = new byte[1024]; private int _curChar; private int _numChars; private StringBuilder _sb = new StringBuilder(); FastScanner(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 next() { int c = read(); while (isWhitespace(c)) { c = read(); } _sb.setLength(0); do { _sb.appendCodePoint(c); c = read(); } while (!isWhitespace(c)); return _sb.toString(); } public int nextInt() { return (int) nextLong(); } public long nextLong() { int c = read(); while (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } public boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } } // // // // // // // // // // // // // // // // // // // // // // // //
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
b9ee5fd3a70c0fc1133cd67df32763f2
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; public class Solution { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int index = 0; int next = 1; int[] answer = new int[n]; answer[index++] = next; boolean plus = false; for(int i = n-1; i > n - k; i--){ if(index % 2 == 0){ next = Math.abs(next - i); plus = false; }else{ next = Math.abs(next + i); plus = true; } answer[index++] = next; } while(index < answer.length){ answer[index] = answer[index - 1] + (plus ? -1 : 1); index++; } for(int i = 0; i < answer.length; i++){ System.out.print(answer[i] + " "); } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
c4d1090bf8aad546431a407a02d6f242
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author mongsiry013 */ 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); Task solver = new Task(); solver.solve(1, in, out); out.close(); } } class Task { public void solve(int testNumber, Scanner in, PrintWriter out) { int n, k; n = in.nextInt(); k = in.nextInt(); int ans[] = new int[n]; ans[0] = 1; for(int i=0, j = k; j>0; ++i, j--){ if(i % 2 == 0) ans[i+1] = ans[i] + j; else ans[i+1] = ans[i]-j; } for(int i=k+1; i<n; ++i){ ans[i] = i+1; } for(int i : ans) out.printf(i + " "); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
b22c1a575d9fcab2677712039a4f3431
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; public class A { void run() throws IOException { int n = ni(), k = ni(); int[] d = new int[n]; int a = 1 - k, b = 1, c = n - k; while (c < n) { d[c++] = a; a += 3; if (c == n) { break; } d[c++] = b; b += 1; } for (int i = 1; i <= n; i++) { pw.print(i - d[i - 1]); pw.print(' '); } pw.println(); } void skip() throws IOException { while (br.ready()) { br.readLine(); } } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } return true; } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int ni() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("A.txt"))); if (!OJ) { long timeout = System.currentTimeMillis(); while (br.ready()) { new A().run(); pw.println(); pw.println("----------------------------------"); } pw.println("time: " + (System.currentTimeMillis() - timeout)); } else { new A().run(); } // new A().stress(); br.close(); pw.close(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
02e849d54bf0d16171dc6731bd698406
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.util.Scanner; public class A482 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int K = in.nextInt(); StringBuilder ans = new StringBuilder(); int num = 1; boolean add = true; for (int i = K; i >= 0; i--) { ans.append(num); ans.append(" "); if(add) { num += i; add = false; } else { num -= i; add = true; } } // System.out.println(ans); if(K + 1 < N) { for (int i = K + 2; i <= N; i++) { ans.append(i); ans.append(" "); } } System.out.println(ans.deleteCharAt(ans.length()-1)); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
aff0fd47f821cae7908f3537c7853884
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
256 megabytes
import java.io.*; import java.util.*; import java.util.List; public class Main { private static StringTokenizer st; private static BufferedReader br; public static long MOD = 1000000007; public static long tenFive = 100000; public static double EPS = 0.000000001; public static void print(Object x) { System.out.println(x + ""); } public static String join(List<?> x, String space) { StringBuilder sb = new StringBuilder(); for (Object elt : x) { sb.append(elt); sb.append(space); } return sb.toString(); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line.trim()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static List<Integer> nextInts(int N) throws IOException { List<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < N; i++) { ret.add(nextInt() - 1); } return ret; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int k = nextInt(); int dir = 1; int cur = 1; int jump = n - 1; print(1); for (int i = 0; i < k - 1; i++) { cur += dir * jump; print(cur); jump -= 1; dir *= -1; } for (int i = k; i < n; i++) { cur += dir; print(cur); } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
b32368243a7ea100f0d578a4c28a4200
train_002.jsonl
1414170000
Permutation p is an ordered set of integers p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,โ€‰โ€‰โ€‰p2,โ€‰โ€‰โ€‰...,โ€‰โ€‰โ€‰pn.Your task is to find such permutation p of length n, that the group of numbers |p1โ€‰-โ€‰p2|,โ€‰|p2โ€‰-โ€‰p3|,โ€‰...,โ€‰|pnโ€‰-โ€‰1โ€‰-โ€‰pn| has exactly k distinct elements.
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.util.Locale; import java.util.StringTokenizer; public class A { private static BufferedReader in; private static StringTokenizer st; private static PrintWriter out; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int k = nextInt(); int ans[] = new int [n+1]; boolean used[] = new boolean [n+1]; for (int i = 1; i <=k; i++) { if(i % 2 == 1){ ans[i] = i/2 + 1; }else{ ans[i] = n - ans[i-1] + 1; } used[ans[i]] = true; } int count = k; if(k % 2 ==0){ for (int i = n; i >=1; i--) { if(!used[i]){ ans[++count] = i; } } }else{ for (int i = 1; i <=n; i++) { if(!used[i]){ ans[++count] = i; } } } for (int i = 1; i <= n; i++) { out.print(ans[i]+" "); } out.close(); } private static double nextDouble() throws Exception { return Double.parseDouble(next()); } private static long nextLong() throws Exception { return Long.parseLong(next()); } private static int nextInt() throws Exception { return Integer.parseInt(next()); } private static String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 7
standard input
[ "constructive algorithms", "greedy" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1โ€‰โ‰คโ€‰kโ€‰&lt;โ€‰nโ€‰โ‰คโ€‰105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
cf639b38ced245a6837397414d9caa23
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class pr883H { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); char[] c = in.next().toCharArray(); solve(n, c, out); out.flush(); out.close(); } private static void solve(int n, char[] c, PrintWriter out) { int[] cnt = new int[256 + 3]; for (int i = 0; i < n; i++) { cnt[(int)c[i]]++; } char[] ans; StringBuilder oddChar = new StringBuilder(); StringBuilder evenChar = new StringBuilder(); for (int i = 0; i <= 256 ; i++) { if(cnt[i] > 0) { if(cnt[i] % 2 == 1) { oddChar.append((char)i); cnt[i]--; } while(cnt[i] > 0) { evenChar.append((char)i); cnt[i] -= 2; } } } char[] odd; char[] even; if(oddChar.length() == 0) { even = evenChar.toString().toCharArray(); out.println(1); ans = new char[n]; for (int i = 0; i < n / 2; i++) { ans[i] = ans[n-i-1] = even[i]; } out.println(new String(ans)); return; } while(evenChar.length() % oddChar.length() != 0) { int l = evenChar.length()-1; oddChar.append(evenChar.charAt(l)); oddChar.append(evenChar.charAt(l)); evenChar.deleteCharAt(l); } even = evenChar.toString().toCharArray(); odd = oddChar.toString().toCharArray(); int len = n / odd.length; out.println(n / len); ans = new char[len]; int j = 0; for (int i = 0; i < odd.length; i++) { ans[len/2] = odd[i]; for (int k = 0; k < len / 2; k++) { ans[k] = ans[len-k-1] = even[j++]; } out.print(new String(ans) + " "); } } 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
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
dc80920e09a0788125424980a4bbda0e
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class H { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String word = sc.next(); Map<Character, Integer> count = new HashMap<>(); for (Character c : word.toCharArray()) { count.put(c, count.getOrDefault(c, 0) + 1); } int k = solveK(n, count); System.out.println(k); StringBuilder res = new StringBuilder(); for(int i = 0; i < k; i++) res.append(construct(n / k, count)).append(" "); System.out.println(res); } private static String construct(int len, Map<Character, Integer> count) { StringBuilder res = new StringBuilder(); if(len % 2 == 0){ for(int i = 0; i < len / 2; i++){ for(Character key: count.keySet()){ if(count.get(key) > 0) { count.put(key, count.get(key) - 2); res.append(key); break; } } } } else { for(int i = 0; i < len / 2; i++){ for(Character key: count.keySet()){ if(count.get(key) >= 2) { count.put(key, count.get(key) - 2); res.append(key); break; } } } boolean find = false; for(Character key: count.keySet()){ if(count.get(key) % 2 == 1) { res.append(key); count.put(key, count.get(key) - 1); find = true; break; } } if(!find){ for(Character key: count.keySet()){ if(count.get(key) > 0 ) { res.append(key); count.put(key, count.get(key) - 1); break; } } } } for(int i = 0; i < len / 2; i++){ res.append(res.charAt(len / 2 - i - 1)); } return res.toString(); } private static int solveK(int n, Map<Character, Integer> count) { int odd = 0; for (int x : count.values()) { if (x % 2 == 1) odd += 1; } for (int k = 1; k <= n; k++) { if (n % k != 0) continue; int len = n / k; if (len % 2 == 0 && odd == 0) return k; if (len % 2 == 0 && odd != 0) continue; if(k < odd) continue; if(k == odd) return k; if( (k - odd) % 2 == 0) return k; } return n; } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
961dee93e487d2606528038449afc750
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); ArrayList<StringBuilder> list = new ArrayList<>(); int n = Integer.parseInt(in.readLine()); String string = in.readLine(); int[] freq = new int[200]; for (int i = 0; i < string.length(); i++) { freq[string.charAt(i)]++; } for (int i = 0; i < 200; i++) { if (freq[i] % 2 == 1) { list.add(new StringBuilder((char)(i) + "")); freq[i]--; } } if (list.isEmpty()) { StringBuilder left = new StringBuilder(""); StringBuilder right = new StringBuilder(""); while (true) { boolean flag = false; for (int i = 0; i < 200; i++) { if (freq[i] >= 2) { left.append((char) (i)); right.append((char) (i)); freq[i] -= 2; flag = true; } } if (!flag) { break; } } out.println("1"); out.println(left.toString() + right.reverse().toString()); out.close(); return; } while (true) { /*System.out.println("STRINGS "); for (StringBuilder sb : list) { System.out.println(sb.toString()); }*/ int sum = 0; for (int i = 0; i < 200; i++) { if (freq[i] > 0) { sum += freq[i]; } } if ((sum/2) % list.size() == 0) { out.println(list.size()); for (StringBuilder sb : list) { int per = sum/list.size(); StringBuilder left = new StringBuilder(""); StringBuilder right = new StringBuilder(""); outer: while (true) { for (int i = 0; i < 200; i++) { if (per == 0) { break outer; } if (freq[i] >= 2) { left.append((char) (i)); right.append((char) (i)); freq[i] -= 2; per -= 2; } } } out.print(left.toString() + sb.toString() + right.reverse().toString() + " "); } out.print('\n'); out.close(); return; } for (int i = 0; i < 200; i++) { if (freq[i] >= 2) { list.add(new StringBuilder((char)(i) + "")); list.add(new StringBuilder((char)(i) + "")); freq[i] -= 2; break; } } } } } /* 20 qqqoqqoqMoqMMMqqMMqM */
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
cf447de1e14ec4237d28fdd615f46dfd
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.*; import java.io.*; public class Q1 { static InputReader in=new InputReader(System.in); static PrintWriter out=new PrintWriter(System.out); static int T=1,N,M; static int A[]; static int dp[][]; static ArrayList<Integer> graph[]; public static void main(String args[]) { //T=in.readInt(); int i,j,k; while(T-->0) { N=in.readInt(); String S=in.readString(); HashMap<Character,Integer> map = new HashMap<Character,Integer>(); int co=0,ce=0; for(i=0;i<N;i++) { if(map.containsKey(S.charAt(i))) map.put(S.charAt(i),map.get(S.charAt(i))+1); else map.put(S.charAt(i),1); } Iterator itr = map.entrySet().iterator(); Stack<Character> sto = new Stack<Character>(); Stack<Character> ste = new Stack<Character>(); while(itr.hasNext()) { Map.Entry<Character,Integer> ent = (Map.Entry)itr.next(); char key = (char)ent.getKey(); int val = (int)ent.getValue(); if(val%2==0){ while(val!=0) { ce++; ste.push(key); val-=2; } } else{ co++; sto.push(key); val-=1; while(val!=0) { ste.push(key); ce++; val-=2; } } itr.remove(); } //out.println(co+" "+ce); if(co==0) { out.println(1); Stack rev=new Stack(); while(!ste.isEmpty()) { rev.push(ste.peek()); out.print(ste.pop()); } while(!rev.isEmpty()) { out.print(rev.pop()); } } else { int temp=0,len=-1; //out.println(ce+" "+co); for(i=co;i<N;i+=2) { if((ce-temp)>=i&&(ce-temp)%i==0) { len=i; while(temp!=0){ sto.push(ste.peek()); sto.push(ste.pop());temp--;} break; } temp++; } // out.println(sto.count()); // out.println(ste.count()); if(len!=-1){ out.println(len); while(!sto.isEmpty()) { Stack rev=new Stack(); int tp=0; // out.println((N/len)/2); while(tp++<(N/len)/2) { rev.push(ste.peek()); out.print(ste.pop()); } out.print(sto.pop()); while(!rev.isEmpty()) { out.print(rev.pop()); } out.print(" "); } } else { out.println(N); for(i=0;i<N;i++) out.print(S.charAt(i)+" "); } } } out.flush(); out.close(); } public static void printI0(int a[],int n) { for(int i=0;i<n;i++) { out.println(a[i]); } } public static void printI1(int a[],int n) { for(int i=1;i<=n;i++) { out.println(a[i]); } } public static void printL0(long a[],int n) { for(int i=0;i<n;i++) { out.println(a[i]); } } public static void printL1(long a[],int n) { for(int i=1;i<=n;i++) { out.println(a[i]); } } public static void initializeGraph(int n) { graph=new ArrayList[n+1]; for(int i=0;i<=n;i++) graph[i]=new ArrayList<Integer>(); } } class Pair{ char x; int y; public Pair(char x,int y) { this.x=x; this.y=y; } } 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 void inputI0(int a[],int n) { for(int i=0;i<n;i++) a[i]=readInt(); } public void inputI1(int a[],int n) { for(int i=1;i<=n;i++) a[i]=readInt(); } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public void inputL0(long a[],int n) { for(int i=0;i<n;i++) a[i]=readLong(); } public void inputL1(long a[],int n) { for(int i=1;i<=n;i++) a[i]=readLong(); } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public 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); } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
d6a588ad20fa733b07a4d8e21228049b
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } static class TaskH { public void solve(int testNumber, InputReader in, PrintWriter out) { int[] count = new int[200]; int n = in.nextInt(); String x = in.nextLine(); for (int i = 0; i < n; i++) { int p = (int) x.charAt(i); count[p]++; } int pair = 0; int odd = 0; PriorityQueue<Character> arg = new PriorityQueue<>(); PriorityQueue<Character> odds = new PriorityQueue<>(); for (int i = 0; i < 200; i++) { if (count[i] != 0) { if (count[i] % 2 != 0) { odd++; odds.add((char) i); } pair = pair + count[i] / 2; for (int j = 0; j < count[i] / 2; j++) { arg.add((char) i); } } } if (pair != 0 && odd == 0) { out.println("1"); StringBuilder front = new StringBuilder(); while (!arg.isEmpty()) { front.append(arg.poll()); } out.println(front.toString() + front.reverse().toString()); return; } else if (pair % odd == 0) { out.println(odd); int each = pair / odd; boolean first = true; for (int i = 0; i < odd; i++) { StringBuilder front = new StringBuilder(); for (int j = 0; j < each; j++) { front.append(arg.poll()); } if (!first) out.print(" "); first = false; out.print(front.toString() + odds.poll() + front.reverse().toString()); } out.println(); return; } while (pair > 0) { pair = pair - 1; char ap = arg.poll(); odd = odd + 2; odds.add(ap); odds.add(ap); if (pair % odd == 0) { out.println(odd); int each = pair / odd; boolean first = true; for (int i = 0; i < odd; i++) { StringBuilder front = new StringBuilder(); for (int j = 0; j < each; j++) { front.append(arg.poll()); } if (!first) out.print(" "); first = false; out.print(front.toString() + odds.poll() + front.reverse().toString()); } out.println(); return; } } out.println(n); boolean first = true; for (int i = 0; i < 200; i++) { if (count[i] != 0) { int c = count[i]; char p = (char) i; for (int j = 0; j < c; j++) { if (!first) out.print(" "); out.print(p); first = false; } } } out.println(); } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream a) { br = new BufferedReader(new InputStreamReader(a)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { return null; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
7e2d747e9e5597bfaed107a2e71b6ff0
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class main { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter pw = new PrintWriter(System.out); public static String line; public static StringTokenizer st; public static ArrayList<ArrayList<Integer>> adjList; public static int[] dx = {-1, 0, 1, 0, -1, 1, 1, -1}; public static int[] dy = {0, 1, 0, -1, 1, 1, -1, -1}; public static int INF = 0x3f3f3f3f; public static int MOD = 1000000007; public static boolean valid(int parts, int size, int A, int B){ if(size % 2 == 0){ return A == 0; } else{ return A <= parts && (parts - A) % 2 == 0; } } public static void main(String[] args) throws Exception{ int N = Integer.parseInt(br.readLine()); HashMap<Character, Integer> d = new HashMap<Character, Integer>(); String s = br.readLine(); for(int i = 0; i < N; i++){ char c = s.charAt(i); if(!d.containsKey(c)) d.put(c, 0); d.put(c, d.get(c)+1); } ArrayList<Character> A = new ArrayList<Character>(); ArrayList<Character> B = new ArrayList<Character>(); StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); for(Character c : d.keySet()){ for(int i = 0; i < d.get(c)/2; i++){ B.add(c); } if(d.get(c) % 2 != 0){ A.add(c); } } ArrayList<Integer> PF = new ArrayList<Integer>(); for(int i = 1; i * i <= N; i++){ if(N % i == 0){ PF.add(i); if(i * i != N) PF.add(N/i); } } Collections.sort(PF); int ans = 0; for(int i = 0; i < PF.size(); i++){ int parts = PF.get(i); int size = N / parts; if(valid(parts, size, A.size(), B.size())){ ans = PF.get(i); break; } } // System.out.println(A+ " " + B); int a1 = 0; int b1 = 0; pw.print(ans + "\n"); for(int i = 0; i < ans; i++){ StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); int size = N / ans; for(int j = 0; j < size/2; j++){ sb1.append(B.get(b1)); sb2.append(B.get(b1)); b1++; } if(size % 2 != 0){ if(a1 >= A.size()){ A.add(B.get(b1)); A.add(B.get(b1)); b1++; } sb1.append(A.get(a1)); a1++; } pw.print(sb1.toString() + sb2.reverse().toString()); pw.print(i == ans-1 ? "\n" : " "); } pw.close(); br.close(); } } class Pair{ public long x, y; Pair(long _x, long _y){ x = _x; y = _y; } } class Point implements Comparable<Point>{ public double x, y; Point(double x, double y){ this.x = x; this.y = y; } public int compareTo(Point p){ if(x != p.x) return x < p.x ? -1 : 1; else if(y != p.y) return y < p.y ? -1 : 1; return 0; } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
1be0d6aa984cdcf413b72cbf9d055607
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P883H { List<String> makePalindromes(Deque<Character> od, TreeMap<Character, Integer> em, int k, int l) { List<String> sl = new ArrayList(k); char [] s = new char [l]; while ((k--) > 0) { if ((l & 0b1) != 0) { // odd len if (od.size() > 0) { s[l >> 1] = od.pollFirst(); } else { if (em.size() > 0) { Map.Entry<Character, Integer> cc = em.pollLastEntry(); s[l >> 1] = cc.getKey(); if (cc.getValue() > 1) { em.put(cc.getKey(), cc.getValue() - 1); } } else { return null; } } } for (int i = 0, l2 = l >> 1, c = 0; l2 > 0; l2 -= c) { Map.Entry<Character, Integer> cc = em.pollFirstEntry(); if (cc == null) { return null; } c = Math.min(l2, cc.getValue() / 2); for (int j = c; j != 0; s[i] = s[l - i - 1] = cc.getKey(), j--, i++); if ((cc.getValue() - 2 * c) > 0) { em.put(cc.getKey(), cc.getValue() - 2 * c); } } sl.add(new String(s)); } return sl; } public void run() throws Exception { int n = nextInt(); String s = next(); Map<Character, Integer> cc = new HashMap(); for (int i = 0; i < n; i++) { cc.put(s.charAt(i), cc.getOrDefault(s.charAt(i), 0) + 1); } TreeMap<Character, Integer> em = new TreeMap(); Deque<Character> od = new ArrayDeque(); for (Map.Entry<Character, Integer> me : cc.entrySet()) { char c = me.getKey(); int v = me.getValue(); if ((v & 0b1) == 0) { em.put(c, v); } else { od.add(c); if (v > 1) { em.put(c, v & (~1)); } } } for (int k = 1; k <= n; k++) { if ((n % k) != 0) { continue; } List<String> pl = makePalindromes(new ArrayDeque(od), new TreeMap(em), k, n / k); if (pl != null) { println(pl.size()); for (String p : pl) { print(p + " "); } break; } } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P883H().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
ec91df3f29b4582e704bd6d7a3a2e352
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.util.*; public class MainH { public static void main(String[] args) { StdIn in = new StdIn(); int n=in.nextInt(); int[] cnt = new int[256]; String s = in.next(); for(char c : s.toCharArray()) ++cnt[c]; List<Character> oddEntries = new ArrayList<Character>(); for(int i=0; i<256; ++i) if(cnt[i]%2==1) { oddEntries.add((char)i); --cnt[i]; } if(oddEntries.isEmpty()) { StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); int i=0; while(true) { while(i<256&&cnt[i]==0) ++i; if(i>=256) break; a.append((char) i); b.append((char) i); cnt[i]-=2; } b.reverse(); System.out.println(1); System.out.println(a.toString()+b.toString()); return; } while(true) { if((n-oddEntries.size())/2%oddEntries.size()==0) { System.out.println(oddEntries.size()); int i=0, pairsPWord=(n-oddEntries.size())/2/oddEntries.size(); for(char c : oddEntries) { StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); for(int j=0; j<pairsPWord; ++j) { while (cnt[i] == 0) ++i; a.append((char) i); b.append((char) i); cnt[i] -= 2; } b.reverse(); System.out.print(a.toString()+c+b.toString()+" "); } return; } else { for(int i=0; i<256; ++i) { if(cnt[i]>0) { oddEntries.add((char)i); oddEntries.add((char)i); cnt[i]-=2; break; } } } } } interface Input { public String next(); public String nextLine(); public int nextInt(); public long nextLong(); public double nextDouble(); } static class StdIn implements Input { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(String filename) { try{ din = new DataInputStream(new FileInputStream(filename)); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { 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 int[] readIntArray(int n) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt(); return ar; } public long nextLong() { 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 long[] readLongArray(int n) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong(); return ar; } public double nextDouble() { 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() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
a1143a882816794b114b7e78e2d8d897
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.util.*; public class MainH { public static void main(String[] args) { StdIn in = new StdIn(); int n=in.nextInt(); int[] cnt = new int[256]; String s = in.next(); for(char c : s.toCharArray()) ++cnt[c]; List<Character> oddEntries = new ArrayList<Character>(); for(int i=0; i<256; ++i) if(cnt[i]%2==1) { oddEntries.add((char)i); --cnt[i]; } if(oddEntries.isEmpty()) { StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); int i=0; while(true) { while(i<256&&cnt[i]==0) ++i; if(i>=256) break; a.append((char) i); b.append((char) i); cnt[i]-=2; } b.reverse(); System.out.println(1); System.out.println(a.toString()+b.toString()); return; } while(true) { if((n-oddEntries.size())/2%oddEntries.size()==0) { System.out.println(oddEntries.size()); int i=0, pairsPWord=(n-oddEntries.size())/2/oddEntries.size(); for(char c : oddEntries) { StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); for(int j=0; j<pairsPWord; ++j) { while (cnt[i] == 0) ++i; a.append((char) i); b.append((char) i); cnt[i] -= 2; } b.reverse(); System.out.print(a.toString()+c+b.toString()+" "); } return; } else { for(int i=0; i<256; ++i) { if(cnt[i]>0) { oddEntries.add((char)i); oddEntries.add((char)i); cnt[i]-=2; break; } } } } } interface Input { public String next(); public String nextLine(); public int nextInt(); public long nextLong(); public double nextDouble(); } static class StdIn implements Input { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(String filename) { try{ din = new DataInputStream(new FileInputStream(filename)); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { 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 int[] readIntArray(int n) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt(); return ar; } public long nextLong() { 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 long[] readLongArray(int n) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong(); return ar; } public double nextDouble() { 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() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
db74c73da2eaa49df8bc878e70b873f2
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { in.NextInt(); char[] s = in.Next().toCharArray(); int[] charCount = new int[256]; for (char c : s) { charCount[c]++; } int oddCount = 0; for (int i : charCount) { if (i % 2 != 0) oddCount++; } if (oddCount == 0) { int t = 0; for (int i = 0; i < s.length / 2; i++) { while (charCount[t] == 0) { t++; } s[i] = (char) (t); s[s.length - 1 - i] = s[i]; charCount[t] -= 2; } out.println(1); out.println(s); return; } for (int i = oddCount; i < s.length; i++) { if (s.length % i == 0) { int pLength = s.length / i; if (pLength % 2 == 1) { out.println(s.length / pLength); char[] t = new char[pLength]; for (int j = 0; j < s.length / pLength; j++) { int c = 0; for (int k = 0; k < (pLength - 1) / 2; k++) { while (charCount[c] < 2) { c++; } t[k] = (char) (c); t[pLength - 1 - k] = (char) (c); charCount[c] -= 2; } c = 0; while (c < 256 && charCount[c] % 2 == 0) { c++; } if (c == 256) { c = 0; while (charCount[c] == 0) { c++; } } t[pLength / 2] = (char) (c); charCount[c]--; out.print(t); out.print(" "); } out.println(); return; } } } //nothing found. out.println(s.length); for (char c : s) { out.print("" + (char) c + " "); } out.println(); } } public static int GetMax(int[] ar) { int max = Integer.MIN_VALUE; for (int a : ar) { max = Math.max(max, a); } return max; } public static int[] GetCount(int[] ar) { return GetCount(ar, GetMax(ar)); } public static int[] GetCount(int[] ar, int maxValue) { int[] dp = new int[maxValue + 1]; for (int a : ar) { dp[a]++; } return dp; } 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()); } public int[] NextIntArray(int n) { return NextIntArray(n, 0); } public int[] NextIntArray(int n, int offset) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = NextInt() - offset; } return a; } public int[][] NextIntMatrix(int n, int m) { return NextIntMatrix(n, m, 0); } public int[][] NextIntMatrix(int n, int m, int offset) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = NextInt() - offset; } } return a; } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
45bb82845a67d302d6ada6a198bd9ed6
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class TaskH { private static BufferedReader in; private static StringTokenizer tok; private static PrintWriter out; public static String readToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static int readInt() throws IOException { return Integer.parseInt(readToken()); } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); run(); in.close(); out.close(); } public static final int CHAR_COUNT = 257; public static void run() throws IOException { int n = readInt(); int[] counts = new int[CHAR_COUNT]; Deque<Character> middle = new ArrayDeque<>(); String s = in.readLine(); for (int i = 0; i < n; i++) { counts[s.charAt(i)]++; } int k = 0; // ะบะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั‡ะตั‚ะฝั‹ั… for (int i = 0; i < CHAR_COUNT; i++) { if (counts[i] % 2 != 0) { counts[i]--; middle.push((char) i); k++; } } if (k == 0) { out.println(1); StringBuilder str = new StringBuilder(); for (char c = 0; c < CHAR_COUNT; c++) { for (int i = 0; i < counts[c] / 2; i++) str.append(c); } out.println(str.toString() + str.reverse().toString()); } else { while (n % k != 0 || (n / k) % 2 == 0) { char ch = 0; for (char c = 0; c < CHAR_COUNT; c++) { if (counts[c] >= 2) { ch = c; counts[c] -= 2; break; } } middle.push(ch); middle.push(ch); k += 2; } out.println(k); int m = n / k - 1; for (int i = 0; i < k; i++) { StringBuilder str = new StringBuilder(); int j = m; for (char c = 0; c < CHAR_COUNT; c++) { if (counts[c] > 0) { if (counts[c] >= j) { for (int jj = 0; jj < j / 2; jj++) { str.append(c); } counts[c] -= j; j = 0; } else { for (int jj = 0; jj < counts[c] / 2; jj++) { str.append(c); } j -= counts[c]; counts[c] = 0; } if (j == 0) break; } } out.print(str.toString() + middle.pop() + str.reverse().toString() + " "); } } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
b5113d9b66b8f6507c2008fcb4d87cc8
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); Thread th = new Thread(null, new Runnable(){public void run(){new Task1().solve(in, out);}},"Task1",1<<24); try{ th.start(); th.join(); } catch(InterruptedException e){} out.close(); } static class Task1{ static final int MOD = 1000000007; static final int MAX = 400001; static final int R = 256; public void solve(InputReader in, PrintWriter out){ int n = in.nextInt(); ArrayList<Integer> divisors = new ArrayList<Integer>(); for(int i=1; i*i<=n; i++){ if(n%i==0){ if(i%2==1 || (n/i)%2==1){ divisors.add(i); if(i!=n/i) divisors.add(n/i); } } } Collections.sort(divisors); /*for(Integer i: divisors) out.println(i);*/ //if(1>0) return; String s = in.next(); int[] hash = new int[R]; for(int i=0; i<s.length(); i++) hash[s.charAt(i)]++; int start = 0, even = 0, odd = 0, ec = 0, oc = 0; ArrayList<Character> E = new ArrayList<Character>(), O = new ArrayList<Character>(); for(int i=0; i<R; i++){ int temp = hash[i]; while(temp>0){ if(temp==1){ O.add((char)i); temp = 0; } else { E.add((char)i); temp -= 2; } } even += hash[i]/2; odd += hash[i]%2; } /*out.println("---------------------"); for(Character c: E) out.print(c+""); out.println(); for(Character c: O) out.print(c+""); out.println(); out.println(odd+" "+even); out.println("--------------------");*/ if(n%2==0 && odd==0){ out.println(1); StringBuilder s1 = new StringBuilder(""); StringBuilder s3 = new StringBuilder(""); for(int j=0; j<even; j++){ s1.append(E.get(ec)); s3.append(E.get(ec++)); } s3.reverse(); out.print(s1.toString()+s3.toString()+" "); return; } else if(n%2==1 && odd==1){ out.println(1); StringBuilder s1 = new StringBuilder(""); StringBuilder s3 = new StringBuilder(""); for(int j=0; j<even; j++){ s1.append(E.get(ec)); s3.append(E.get(ec++)); } s3.reverse(); out.print(s1.toString()+O.get(oc++)+s3.toString()+" "); return; } boolean flag = false; while(start<divisors.size()){ int first = divisors.get(start); // number int second = n/first; // length if(odd == first){ // this is the answer flag = true; out.println(first); for(int i=0; i<first; i++){ StringBuilder s1 = new StringBuilder(""); StringBuilder s2 = new StringBuilder(""); StringBuilder s3 = new StringBuilder(""); s2.append(O.get(oc++)); for(int j=0; j<second/2; j++){ s1.append(E.get(ec)); s3.append(E.get(ec++)); } s3.reverse(); out.print(s1.toString()+s2.toString()+s3.toString()+" "); } break; } else if(odd<first && (first-odd)/2<=even && (first-odd)%2==0){ // break some even into odds even -= (first-odd)/2; for(int j=0; j<(first-odd)/2; j++){ O.add(E.get(ec)); O.add(E.get(ec++)); } flag = true; out.println(first); for(int i=0; i<first; i++){ StringBuilder s1 = new StringBuilder(""); StringBuilder s2 = new StringBuilder(""); StringBuilder s3 = new StringBuilder(""); s2.append(O.get(oc++)); for(int j=0; j<second/2; j++){ s1.append(E.get(ec)); s3.append(E.get(ec++)); } s3.reverse(); out.print(s1.toString()+s2.toString()+s3.toString()+" "); } break; }else { start++; } } if(!flag){ out.println(n); for(int i=0; i<n; i++){ out.print(s.charAt(i)+" "); } } } long gcd(long a, long b){ while(a>0){ long rem = b%a; b = a; a = rem; } return b; } long expo(long a, long b, long MOD){ long result = 1; while (b>0){ if (b%2==1) result=(result*a)%MOD; b>>=1; a=(a*a)%MOD; } return result%MOD; } long inverseModullo(long numerator, long denominator, long MOD){ return ((numerator )*(expo(denominator, MOD-2, MOD))) ; } } static class Task2{ public void solve(InputReader in, PrintWriter out){ // } } static class DijkstraSP { long[] distTo; DirectedEdge[] edgeTo; IndexMinPQ<Long> pq; public DijkstraSP(EdgeWeightedDigraph G, int s){ distTo= new long[G.V()]; edgeTo= new DirectedEdge[G.V()]; pq= new IndexMinPQ<Long>(G.V()); //maxN = G.V() for(int i=0; i<G.V(); i++){ distTo[i]=Long.MAX_VALUE; } distTo[s]=0; pq.insert(s, 0L); while(!pq.isEmpty()){ int v = pq.delMin(); for(DirectedEdge e: G.adj(v)){ relax(e); } } } private void relax(DirectedEdge e){ int v=e.from(), w=e.to(); if(distTo[w] > distTo[v]+e.weight()){ distTo[w]= distTo[v]+e.weight(); edgeTo[w]= e; if(pq.contains(w)){ if(pq.keyOf(w)>distTo[w]) pq.changeKey(w, distTo[w]); } else pq.insert(w, distTo[w]); } } } static class EdgeWeightedDigraph { private final int V; private LinkedList<DirectedEdge>[] adj; @SuppressWarnings("unchecked") public EdgeWeightedDigraph(int V){ this.V=V; adj=(LinkedList<DirectedEdge>[])new LinkedList[V]; for(int i=0; i<V; i++){ adj[i]=new LinkedList<DirectedEdge>(); } } public void addEdge(DirectedEdge e){ adj[e.from()].add(e); } public Iterable<DirectedEdge> adj(int v){ return adj[v]; } public int V(){ return V; //number of vertices } } static class DirectedEdge { private int v, w; private long weight; public DirectedEdge(int v, int w, long weight){ this.v=v; this.w=w; this.weight=weight; } public int from(){ return v; } public int to(){ return w; } public long weight(){ return weight; } } static class IndexMinPQ<Key extends Comparable<Key>>{ private int[] a, b; private Key[] keys; private int N, maxN; @SuppressWarnings("unchecked") public IndexMinPQ(int capacity){ this.maxN=capacity-1; this.N=0; this.a=new int[maxN+1]; this.b=new int[maxN+1]; this.keys=(Key[])new Comparable[maxN+1]; for(int i=0; i<maxN+1; i++) a[i]=-1; } public boolean isEmpty(){ return N==0; } public int size(){ return N; } public boolean contains(int index){ return a[index] != -1; } public void insert(int index, Key key){ N++; a[index]=N-1; b[N-1]=index; keys[index]=key; swim(N-1); } public int minIndex(){ return b[0]; } public Key minKey(){ return keys[b[0]]; } public Key keyOf(int index){ return keys[index]; } public int delMin(){ int min=b[0]; exch(0,--N); sink(0); a[min]= -1; b[N]= -1; return min; } public void changeKey(int index, Key newKey){ if(contains(index)){ keys[index]=newKey; swim(a[index]); sink(a[index]); } else throw new IllegalArgumentException("There is no key associated with this index."); } /* General Helper Functions */ private boolean greater(int i, int j){ return keys[b[i]].compareTo( keys[b[j]] ) > 0; } private void exch(int i, int j){ int swap=b[i]; b[i]=b[j]; b[j]=swap; a[b[i]]=i; a[b[j]]=j; } /* Heap Helper Functions */ private void swim(int child){ int root=(child-1)/2; while(greater(root, child)){ exch(root, child); child=root; root=(child-1)/2; } } private void sink(int root){ int child=2*root +1; while(child<N){ if(child<N-1) if(greater(child, child+1)) child++; if(greater(root, child)) exch(root, child); else break; root=child; child=2*root+1; } } } static class InputReader{ final InputStream stream; final byte[] buf = new byte[8192]; int curChar, numChars; SpaceCharFilter filter; public InputReader(){ this.stream = System.in; } public int read(){ if(numChars == -1) throw new InputMismatchException(); if(curChar >= numChars){ curChar = 0; try{ numChars = stream.read(buf); } catch(IOException e){ throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt(){ int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-'){ sgn = -1; c = read(); } int res = 0; do{ if(c<'0' || c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res*sgn; } public long nextLong(){ int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-'){ sgn = -1; c = read(); } long res = 0; do{ if(c<'0' || c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res*sgn; } public String next(){ int c = read(); while(isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.appendCodePoint(c); c = read(); }while(!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c){ if(filter != null) return filter.isSpaceChar(c); return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
8b7f4e27adcebfeec55b2078dcd28063
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.*; import java.io.*; public class ProblemH { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); String s = in.readString(); int[] cnt = new int[256]; for(int i = 0; i < n; i++) cnt[s.charAt(i)]++; ArrayList<Integer> list = new ArrayList<>(); for(int i = 1; i <= Math.sqrt(n); i++){ if(n % i == 0){ list.add(i); if(i * i != n) list.add(n / i); } } Collections.sort(list); int lol = 0; for(int i = 0; i < 256; i++){ lol += cnt[i] / 2; } for(int k : list){ int y = n / k; int x = k * (y / 2); if(lol >= x){ out.println(k); ArrayList<Character> l1 = new ArrayList<>(); for(int i = 0; i < 256; i++){ if(cnt[i] % 2 != 0){ l1.add((char)(i)); cnt[i]--; } } int z = lol - x; z *= 2; for(int i = 0; i < 256; i++){ while(z > 0 && cnt[i] > 0){ l1.add((char)i); cnt[i]--; z--; } } int p = 0; int q = 0; while(k-- > 0){ char[] c = new char[y]; int r = 0; while(r < y / 2){ while(cnt[q] <= 0) q++; c[r] = (char)(q); c[y - r - 1] = (char)(q); cnt[q] -= 2; r++; } if(y % 2 != 0){ c[r] = l1.get(p++); } out.print(new String(c) + " "); } out.println(); break; } } out.close(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x,y; Pair (int x,int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return Integer.compare(this.x,o.x); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } 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 long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } 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); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
b33ca55d5f7ec215089365d10b054f95
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.*; public class Problem883H { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String s = in.next(); Map<Character, Integer> freq = new HashMap<>(2 * 26 + 10); for (int i = 0; i < n; i++) { freq.compute(s.charAt(i), (k, v) -> v == null ? 1 : v + 1); } LinkedList<Character> odds = new LinkedList<>(); LinkedList<Character> evens = new LinkedList<>(); for (Map.Entry<Character, Integer> entry : freq.entrySet()) { if (entry.getValue() % 2 == 1) { odds.add(entry.getKey()); entry.setValue(entry.getValue() - 1); } int val = entry.getValue(); if (val > 0) { while (val != 0) { val -= 2; evens.addLast(entry.getKey()); } entry.setValue(0); } } if (odds.size() == 0) { System.out.println(1); char[] res = new char[n]; Iterator<Character> iterator = evens.iterator(); for (int i = 0; i < n / 2; i++) { res[i] = res[n - i - 1] = iterator.next(); } System.out.println(new String(res)); return; } while (evens.size() % odds.size() != 0) { Character c = evens.pollLast(); odds.addLast(c); odds.addLast(c); } System.out.println(odds.size()); int len = n / odds.size(); char[] res = new char[len]; Iterator<Character> iterator = evens.iterator(); for (Character odd : odds) { res[len / 2] = odd; for (int i = 0; i < len / 2; i++) { res[i] = res[len - i - 1] = iterator.next(); } System.out.print(new String(res) + " "); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
743cd5eeb928d4937eb9f82facfa9a30
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
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.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } static class TaskH { private int num(char c) { if (c >= 'a' && c <= 'z') { return c - 'a'; } else if (c >= 'A' && c <= 'Z') { return c - 'A' + 26; } else { return c - '0' + 52; } } private char rev(int n) { if (n < 26) return (char) (n + 'a'); else if (n < 52) return (char) (n - 26 + 'A'); else return (char) (n - 52 + '0'); } public void solve(int testNumber, FastScanner in, PrintWriter out) { int N = in.ni(); int[] cnt = new int[100]; String s = in.ns(); for (int i = 0; i < N; i++) { cnt[num(s.charAt(i))]++; } LinkedList<Character> even = new LinkedList<>(); LinkedList<Character> odd = new LinkedList<>(); for (int i = 0; i < 100; i++) { if (cnt[i] == 0) continue; if (cnt[i] % 2 == 1) { odd.add(rev(i)); } for (int j = 0; j < cnt[i] / 2; j++) { even.add(rev(i)); } } if (odd.size() <= 1) { out.println(1); StringBuilder pal = new StringBuilder(); for (Character c : even) { pal.append(c); } out.print(pal); if (!odd.isEmpty()) out.print(odd.pollFirst()); out.print(pal.reverse()); out.println(); } else { for (int div = 1; div <= N; div++) { if (N % div == 0 && (N / div) % 2 == 1) { if (odd.size() > div || (div - odd.size()) % 2 == 1) continue; char[] center = new char[div]; for (int i = 0; i < div; i++) { if (!odd.isEmpty()) { center[i] = odd.pollFirst(); } else { center[i] = center[i + 1] = even.pollFirst(); i++; } } out.println(div); int size = (N / div - 1) / 2; for (int i = 0; i < div; i++) { StringBuilder pal = new StringBuilder(); for (int j = 0; j < size; j++) { pal.append(even.pollFirst()); } out.print(pal); out.print(center[i]); out.print(pal.reverse()); out.print(' '); } return; } } } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
b864bd0fcb5b66a1ec9e8e3a419bee38
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; /** * Created by dtnha on 10/20/2017. */ public class PalindromicCut { public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); String s = Reader.next(); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } Set<Character> keys = map.keySet(); List<Character> oddCharacterList = new ArrayList<>(); StringBuffer evenCharacterBuffer = new StringBuffer(); for (Character c : keys) { int value = map.get(c); if (value % 2 == 0) { for (int i = 0; i < value; i++) { evenCharacterBuffer.append(c); } } else { oddCharacterList.add(c); for (int i = 0; i < value - 1; i++) { evenCharacterBuffer.append(c); } } } int evenLength = evenCharacterBuffer.length(); int oddSize = oddCharacterList.size(); StringBuffer res = new StringBuffer(); if (oddSize == 0 || oddSize == 1) { res.append(1 + "\n"); StringBuffer leftCharacters = new StringBuffer(); int x = 0; while (x <= evenLength - 1) { leftCharacters.append(evenCharacterBuffer.charAt(x)); x = x + 2; } res.append(leftCharacters); for (Character c : oddCharacterList) { res.append(c); } StringBuffer rightCharacters = leftCharacters.reverse(); res.append(rightCharacters); } else { int minsubString = oddSize; int len = 0; while (minsubString <= n) { if (n % minsubString == 0) { len = n / minsubString; if (len % 2 == 1) { break; } } minsubString++; } if (len >= 3) { res.append(minsubString + "\n"); int x = 0; for (int i = 0; i < oddSize; i++) { StringBuffer word = new StringBuffer(); Character oddC = oddCharacterList.get(i); int distance = len - 1; StringBuffer left = new StringBuffer(); while (distance > 0) { left.append(evenCharacterBuffer.charAt(x)); distance = distance - 2; x = x + 2; } word.append(left); word.append(oddC); StringBuffer right = left.reverse(); word.append(right); res.append(word + " "); } Character oddC = null; for (int i = oddSize; i < minsubString; i++) { StringBuffer word = new StringBuffer(); StringBuffer left = new StringBuffer(); int distance = len - 1; while (distance > 0) { left.append(evenCharacterBuffer.charAt(x)); distance = distance - 2; x = x + 2; } word.append(left); if (oddC != null) { word.append(oddC); oddC = null; } else { oddC = evenCharacterBuffer.charAt(x); word.append(oddC); x = x+2; } StringBuffer right = left.reverse(); word.append(right); res.append(word + " "); } } else { res.append(n + "\n"); for (int i = 0; i < n; i++) { res.append(s.charAt(i) + " "); } } } System.out.println(res.toString()); } private static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ public static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
cc694f16c0b4399c847162f398b1f54a
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.io.*; public class TestClass{ static class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } //reads in the next string public String next() throws Exception { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret = ret.append((char)c); c = read(); } while (c > ' '); return ret.toString(); } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(char x) { writer.println(x); } public void print(char x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void printf(String format, Object args) { writer.printf(format, args); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static int count[]; public static void main(String args[]) throws Exception { Parser s = new Parser(System.in); OutputWriter out = new OutputWriter(System.out); int N=s.nextInt(); char str[]=s.next().toCharArray(); char ch[]=new char[62]; int k=0; int start_a=0; for (int i = 0; i <26 ; i++) { ch[k++]=(char)(i+'a'); } int start_A=k; for (int i = 0; i <26 ; i++) { ch[k++]=(char)(i+'A'); } int start_0=k; for (int i = 0; i <10 ; i++) { ch[k++]=(char)(i+'0'); } count=new int[62]; for (int i = 0; i <str.length; i++) { int x=str[i]; if(x>=48&&x<=57){ int y=str[i]-'0'; count[start_0+y]++; } else{ if(x>=65&&x<=90){ int y=str[i]-'A'; count[start_A+y]++; } else{ int y=str[i]-'a'; count[start_a+y]++; } } } int even=0; int odd=0; int even_count=0; ArrayList<Character> list_even=new ArrayList<Character>(); ArrayList<Character> list_odd=new ArrayList<Character>(); for (int i = 0; i <62 ; i++) { if(count[i]>0){ int x=count[i]%2; if(x==0){ even++; even_count+=count[i]; for (int j = 0; j <count[i] ; j++) { list_even.add(ch[i]); } } else{ odd++; even_count+=count[i]; even_count--; for (int j = 0; j <count[i]-1 ; j++) { list_even.add(ch[i]); } list_odd.add(ch[i]); } } } if(odd==0){ Deque<Character> ans=new LinkedList<>(); for (int i = 0; i <list_even.size() ; i++) { ans.addFirst(list_even.get(i)); i++; ans.addLast(list_even.get(i)); } out.println(1); while (ans.size()>0){ out.print(ans.poll()+""); } } else { // System.out.println("here"); int pairs=even_count/2; int ans=N; for (int i = odd; i <=N ; i++) { // System.out.println(i+" xx"); if(N%i==0){ int left=N/i; int sec=(N-i)/2; if(sec%i==0){ ans=i; break; } } } if(true){ int div=N/ans; // System.out.println(ans); Deque<Character> arr[]=new LinkedList[ans]; for (int i = 0; i <ans ; i++) { arr[i]=new LinkedList<>(); } int m=0; for ( m = 0; m <list_odd.size() ; m++) { arr[m].addFirst(list_odd.get(m)); } // System.out.println(m); int j=0; while (m<ans){ // System.out.println(m+" "+j+" "+ans); arr[m++].addFirst(list_even.get(j++)); } for (int f = 0; f < ans ; f++) { for (int i = 0; i <(div-1)/2 ; i++) { arr[f].addFirst(list_even.get(j++)); arr[f].addLast(list_even.get(j++)); }} out.println(ans); for (int i = 0; i <ans ; i++) { while (arr[i].size()>0){ out.print(arr[i].poll()+""); } out.print(" "); } } // else{ // out.println(N); // for (int i = 0; i <str.length ; i++) { // // out.print(str[i]+" "); // } // } } out.close(); }}
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
ccee0767a6c5281860c256f30883d4eb
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.io.*; public class TestClass{ static class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } //reads in the next string public String next() throws Exception { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret = ret.append((char)c); c = read(); } while (c > ' '); return ret.toString(); } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(char x) { writer.println(x); } public void print(char x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void printf(String format, Object args) { writer.printf(format, args); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static int count[]; public static void main(String args[]) throws Exception { Parser s = new Parser(System.in); OutputWriter out = new OutputWriter(System.out); int N=s.nextInt(); char str[]=s.next().toCharArray(); char ch[]=new char[62]; int k=0; int start_a=0; for (int i = 0; i <26 ; i++) { ch[k++]=(char)(i+'a'); } int start_A=k; for (int i = 0; i <26 ; i++) { ch[k++]=(char)(i+'A'); } int start_0=k; for (int i = 0; i <10 ; i++) { ch[k++]=(char)(i+'0'); } count=new int[62]; for (int i = 0; i <str.length; i++) { int x=str[i]; if(x>=48&&x<=57){ int y=str[i]-'0'; count[start_0+y]++; } else{ if(x>=65&&x<=90){ int y=str[i]-'A'; count[start_A+y]++; } else{ int y=str[i]-'a'; count[start_a+y]++; } } } int even=0; int odd=0; int even_count=0; ArrayList<Character> list_even=new ArrayList<Character>(); ArrayList<Character> list_odd=new ArrayList<Character>(); for (int i = 0; i <62 ; i++) { if(count[i]>0){ int x=count[i]%2; if(x==0){ even++; even_count+=count[i]; for (int j = 0; j <count[i] ; j++) { list_even.add(ch[i]); } } else{ odd++; even_count+=count[i]; even_count--; for (int j = 0; j <count[i]-1 ; j++) { list_even.add(ch[i]); } list_odd.add(ch[i]); } } } if(odd==0){ Deque<Character> ans=new LinkedList<>(); for (int i = 0; i <list_even.size() ; i++) { ans.addFirst(list_even.get(i)); i++; ans.addLast(list_even.get(i)); } out.println(1); while (ans.size()>0){ out.print(ans.poll()+""); } } else { // System.out.println("here"); int pairs=even_count/2; int ans=N; for (int i = odd; i <=N ; i++) { // System.out.println(i+" xx"); if(N%i==0){ int left=N/i; int sec=(N-i)/2; if(sec%i==0){ ans=i; break; } } } if(true){ int div=N/ans; // System.out.println(ans); Deque<Character> arr[]=new LinkedList[ans]; for (int i = 0; i <ans ; i++) { arr[i]=new LinkedList<>(); } int m=0; for ( m = 0; m <list_odd.size() ; m++) { arr[m].addFirst(list_odd.get(m)); } // System.out.println(m); int j=0; while (m<ans){ // System.out.println(m+" "+j+" "+ans); arr[m++].addFirst(list_even.get(j++)); } for (int f = 0; f < ans ; f++) { for (int i = 0; i <(div-1)/2 ; i++) { arr[f].addFirst(list_even.get(j++)); arr[f].addLast(list_even.get(j++)); }} out.println(ans); for (int i = 0; i <ans ; i++) { while (arr[i].size()>0){ out.print(arr[i].poll()+""); } out.print(" "); } } // else{ // out.println(N); // for (int i = 0; i <str.length ; i++) { // // out.print(str[i]+" "); // } // } } out.close(); }}
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
03d9c167ff1e449dca6061cc3173ff39
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
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.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } static class TaskH { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); int[] cnt = new int[128]; for (int i = 0; i < n; i++) { cnt[s.charAt(i)]++; } int oddCnt = 0; for (int i = 0; i < 128; i++) { if (cnt[i] % 2 == 1) oddCnt++; } ArrayList<Integer> qty = new ArrayList<>(); for (int i = 1; i * i <= n; i++) { if (n % i == 0) { qty.add(i); if (n / i != i) { qty.add(n / i); } } } qty.sort(Integer::compareTo); for (int q : qty) { if ((q == 1 && oddCnt == n % 2) || ((n / q) % 2 == 1 && q >= oddCnt && (q - oddCnt) % 2 == 0) || ((n / q) % 2 == 0) && oddCnt == 0) { out.println(q); out.println(build(cnt, q, n)); return; } } } String build(int[] charCnt, int qty, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < qty; i++) { sb.append(buildPal(charCnt, n / qty)); if (i != qty - 1) sb.append(" "); } return sb.toString(); } String buildPal(int[] charCnt, int len) { char[] ans = new char[len]; if (len % 2 == 1) { for (int i = 0; i < 128; i++) { if (charCnt[i] % 2 == 1) { charCnt[i]--; ans[len / 2] = (char) i; break; } } if (ans[len / 2] == 0) { for (int i = 0; i < 128; i++) { if (charCnt[i] > 0) { charCnt[i]--; ans[len / 2] = (char) i; break; } } } } char ind = 0; for (int i = 0; i < len / 2; i++) { while (charCnt[ind] < 2) ind++; ans[i] = ind; ans[len - i - 1] = ind; charCnt[ind] -= 2; } return new String(ans); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
6315c7e7d9a230e4f886f15d0d570581
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.*; import java.io.*; /** * @author me **/ public class Test { public static void main(String[] args) { Scanner scannered = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = scannered.nextInt(); String s = scannered.next(); int[] copied = new int[150]; for(int i = 0 ; i < n ; i++) { copied[s.charAt(i)]++; } int odd = 0; for(int i = 0 ; i < 150 ; i++) if(copied[i]%2 == 1) odd++; if(odd > 0) { int addOn = 0; while(n%(odd+addOn) != 0 || (n%(odd+addOn) == 0 && (n/(odd+addOn)%2 == 0))) addOn+=2; int length = n/(odd+addOn); char[][] res = new char[odd+addOn][length]; int idx = 0; for(char i = 0 ; i < 150 ; i++) { if(copied[i]%2 == 1) { res[idx++][length/2] = i; copied[i]--; } } for(char i = 0 ; i < 150 ; i++) { while(idx < res.length && copied[i] > 0) { res[idx++][length/2] = i; res[idx++][length/2] = i; copied[i]-=2; } } idx = 0; int idx2 = 0; for(char k = 0 ; k < 150 ; k++) { for(int i = 0 ; i < copied[k] ; i+=2) { while(res[idx][idx2] > 0) { idx2 = 0; idx++; } res[idx][idx2] = k; res[idx][length-idx2-1] = k; idx2++; } } out.println(res.length); for(int i = 0 ; i < res.length ; i++) out.print(new String(res[i]) + " "); } else { char[] res = new char[n]; int idx = 0; for(char k = 0 ; k < 150 ; k++) { for(int i = 0 ; i < copied[k] ; i+=2) { res[idx] = k; res[n-idx-1] = k; idx++; } } out.println(1); out.println(new String(res)); } out.close(); } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
acfb9355182d7236ea8a77df2adf64ae
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { MyReader reader = new MyReader(System.in); MyWriter writer = new MyWriter(System.out); new Solution().run(reader, writer); writer.close(); } private void run(MyReader reader, MyWriter writer) throws IOException { int n = reader.nextInt(); String s = reader.nextString(); Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.putIfAbsent(c, 0); map.merge(c, 1, (e1, e2) -> e1 + e2); } Set<Character> set = new HashSet<>(); StringBuilder w = new StringBuilder(); for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() % 2 == 1) { set.add(entry.getKey()); } else { for (int i = 0; i < entry.getValue() / 2; i++) { w.append(entry.getKey()); } } } if (set.size() == 0) { writer.print(1); writer.println(); writer.print(w.toString() + w.reverse().toString()); return; } int ans = set.size(); for (int i = ans; i <= n; i++) { if (n % i == 0 && n / i % 2 == 1) { ans = i; break; } } writer.print(ans); writer.println(); int length = n / ans; char[] r = new char[ans]; StringBuilder[] q = new StringBuilder[ans]; for (int i = 0; i < ans; i++) { q[i] = new StringBuilder(); } int i = 0; for (char c : set) { r[i++] = c; map.merge(c, 1, (e1, e2) -> e1 - e2); } for (char c : s.toCharArray()) { if (i >= ans) { break; } if (map.get(c) > 0) { r[i++] = c; r[i++] = c; map.merge(c, 2, (e1, e2) -> e1 - e2); } } i = 0; for (Map.Entry<Character, Integer> entry : map.entrySet()) { for (int j = 0; j < entry.getValue() / 2; j++) { if (q[i].length() * 2 + 1 < length) { q[i].append(entry.getKey()); } else { i++; j--; } } } for (int j = 0; j < ans; j++) { writer.print(q[j].toString() + r[j] + q[j].reverse().toString() + " "); } } static class MyReader { final BufferedInputStream in; final int bufSize = 1 << 16; final byte buf[] = new byte[bufSize]; int i = bufSize; int k = bufSize; final StringBuilder str = new StringBuilder(); MyReader(InputStream in) { this.in = new BufferedInputStream(in, bufSize); } int nextInt() throws IOException { return (int) nextLong(); } int[] nextIntArray(int n) throws IOException { int[] m = new int[n]; for (int i = 0; i < n; i++) { m[i] = nextInt(); } return m; } int[][] nextIntMatrix(int n, int m) throws IOException { int[][] a = new int[n][0]; for (int j = 0; j < n; j++) { a[j] = nextIntArray(m); } return a; } long nextLong() throws IOException { int c; long x = 0; boolean sign = true; while ((c = nextChar()) <= 32) ; if (c == '-') { sign = false; c = nextChar(); } if (c == '+') { c = nextChar(); } while (c >= '0') { x = x * 10 + (c - '0'); c = nextChar(); } return sign ? x : -x; } long[] nextLongArray(int n) throws IOException { long[] m = new long[n]; for (int i = 0; i < n; i++) { m[i] = nextLong(); } return m; } int nextChar() throws IOException { if (i == k) { k = in.read(buf, 0, bufSize); i = 0; } return i >= k ? -1 : buf[i++]; } String nextString() throws IOException { int c; str.setLength(0); while ((c = nextChar()) <= 32 && c != -1) ; if (c == -1) { return null; } while (c > 32) { str.append((char) c); c = nextChar(); } return str.toString(); } String nextLine() throws IOException { int c; str.setLength(0); while ((c = nextChar()) <= 32 && c != -1) ; if (c == -1) { return null; } while (c != '\n') { str.append((char) c); c = nextChar(); } return str.toString(); } char[] nextCharArray() throws IOException { return nextString().toCharArray(); } char[][] nextCharMatrix(int n) throws IOException { char[][] a = new char[n][0]; for (int i = 0; i < n; i++) { a[i] = nextCharArray(); } return a; } } static class MyWriter { final BufferedOutputStream out; final int bufSize = 1 << 16; final byte buf[] = new byte[bufSize]; int i = 0; final byte c[] = new byte[30]; static final String newLine = System.getProperty("line.separator"); MyWriter(OutputStream out) { this.out = new BufferedOutputStream(out, bufSize); } void print(long x) throws IOException { int j = 0; if (i + 30 >= bufSize) { flush(); } if (x < 0) { buf[i++] = (byte) ('-'); x = -x; } while (j == 0 || x != 0) { c[j++] = (byte) (x % 10 + '0'); x /= 10; } while (j-- > 0) buf[i++] = c[j]; } void print(int[] m) throws IOException { for (int a : m) { print(a); print(' '); } } void print(long[] m) throws IOException { for (long a : m) { print(a); print(' '); } } void print(String s) throws IOException { for (int i = 0; i < s.length(); i++) { print(s.charAt(i)); } } void print(char x) throws IOException { if (i == bufSize) { flush(); } buf[i++] = (byte) x; } void print(char[] m) throws IOException { for (char c : m) { print(c); } } void println(String s) throws IOException { print(s); println(); } void println() throws IOException { print(newLine); } void flush() throws IOException { out.write(buf, 0, i); out.flush(); i = 0; } void close() throws IOException { flush(); out.close(); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
28b334ea1d51b25e3068af1d96df34cf
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class m { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); int[] upper = new int[26]; int[] lower = new int[26]; int[] digits = new int[10]; for (int i = 0; i < s.length(); i++) { if (Character.isDigit(s.charAt(i))) digits[s.charAt(i) - '0']++; else if (Character.isUpperCase(s.charAt(i))) upper[s.charAt(i) - 'A']++; else lower[s.charAt(i) - 'a']++; } int odd = 0; int even = 0; for (int i = 0; i < 26; i++) { if (upper[i] % 2 == 1) odd++; if (lower[i] % 2 == 1) odd++; even += (lower[i] / 2 + upper[i] / 2) * 2; } for (int i = 0; i < 10; i++) { if (digits[i] % 2 == 1) odd++; even += (digits[i] / 2) * 2; } int z; int x = 0; for (z = 1; z <= n; z++) if (n % z == 0 && (n / z - 1) % 2 == 0 && n - z <= even) { x = (n / z - 1) / 2; break; } if (even == n) { z = 1; x = n / 2; } PrintWriter out = new PrintWriter(System.out); out.println(z); for (int j = 0; j < z; j++) { StringBuilder st = new StringBuilder(); StringBuilder end = new StringBuilder(); boolean done = false; for (int i = 0; i < 26; i++) if (upper[i] % 2 == 1 || (z == n && upper[i] != 0)) { end.append((char) (i + 'A')); upper[i] -= 1; done = true; break; } for (int i = 0; i < 26 && !done; i++) if (lower[i] % 2 == 1 || (z == n && lower[i] != 0)) { end.append((char) (i + 'a')); lower[i] -= 1; done = true; break; } for (int i = 0; i < 10 && !done; i++) if (digits[i] % 2 == 1 || (z == n && digits[i] != 0)) { end.append((char) (i + '0')); digits[i] -= 1; done = true; break; } for (int i = 0; i < 26 && st.length() + end.length() <= n / z - 2; i++) { while (upper[i] > 1 && st.length() + end.length() <= n / z - 2) { upper[i] -= 2; st.append((char) (i + 'A')); end.append((char) (i + 'A')); } } for (int i = 0; i < 26 && st.length() + end.length() <= n / z - 2; i++) { while (lower[i] > 1 && st.length() + end.length() <= n / z - 2) { lower[i] -= 2; st.append((char) (i + 'a')); end.append((char) (i + 'a')); } } for (int i = 0; i < 10 && st.length() + end.length() <= n / z - 2; i++) { while (digits[i] > 1 && st.length() + end.length() <= n / z - 2) { digits[i] -= 2; st.append((char) (i + '0')); end.append((char) (i + '0')); } } if (st.length() + end.length() < n / z) { done = false; for (int i = 0; i < 26; i++) if (upper[i] > 0) { end = new StringBuilder((char) (i + 'A') + "").append(end); upper[i] -= 1; done = true; break; } for (int i = 0; i < 26 && !done; i++) if (lower[i] > 0) { end = new StringBuilder((char) (i + 'a') + "").append(end); lower[i] -= 1; done = true; break; } for (int i = 0; i < 10 && !done; i++) if (digits[i] > 0) { end = new StringBuilder((char) (i + '0') + "").append(end); digits[i] -= 1; done = true; break; } } out.println(((st.reverse()).append(end)).toString()); } out.flush(); out.close(); } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
b74d464595a187f62e6b4e9c7bedd7be
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author rokk- */ public class ACM2017H { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.nextLine(); String string = scanner.nextLine(); int numPairs = 0, numSingles = 0; HashMap<Character, Integer> charCounts = new HashMap<Character, Integer>(); Queue<Character> pairs = new LinkedList<Character>(); Queue<Character> singles = new LinkedList<Character>(); for (int i = 0; i < n; i++) { char c = string.charAt(i); if (!charCounts.containsKey(c)) { charCounts.put(c, 0); } int count = charCounts.get(c) + 1; charCounts.put(c, count); if (count % 2 == 0) { numPairs++; pairs.add(c); } } for (char key : charCounts.keySet()) { if (charCounts.get(key) % 2 == 1) { numSingles++; singles.add(key); } } int numPalindromes = 0; if (numSingles < numPairs) { while (numSingles > 0) { if (numPairs % numSingles == 0) { break; } numPairs--; numSingles+=2; char c= pairs.remove(); singles.add(c); singles.add(c); } } if (numSingles == 0) { numPalindromes = 1; System.out.println("" + numPalindromes); char[] temp = new char[n]; for (int j = 0; j < temp.length / 2; j++) { char c = pairs.remove(); temp[j] = c; temp[temp.length - 1 - j] = c; } System.out.print(new String(temp) + " "); } else if (numPairs >= numSingles && numPairs % numSingles == 0) { numPalindromes = numSingles; System.out.println("" + numPalindromes); for (int i = 0; i < numPalindromes; i++) { char[] temp = new char[numPairs / numSingles * 2 + 1]; temp[(temp.length - 1) / 2] = singles.remove(); for (int j = 0; j < (temp.length - 1) / 2; j++) { char c = pairs.remove(); temp[j] = c; temp[temp.length - 1 - j] = c; } System.out.print(new String(temp) + " "); } } else if (numPairs != numSingles) { numPalindromes = n; System.out.println("" + numPalindromes); for (int i = 0; i < n; i++) { System.out.print(string.charAt(i) + " "); } } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
5553510344cc24550833c33591e25042
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class H_ { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); char[] s = sc.next().toCharArray(); int[] cnt = new int[128]; for (int i = 0; i < n; i++) cnt[s[i]]++; int cntEven = 0; boolean allEven = true; for (int i = 0; i < cnt.length; i++) { if(cnt[i]%2 == 1) { allEven = false; break; } } ArrayList<Character> fill = new ArrayList<Character>(); ArrayList<Character> pal = new ArrayList<Character>(); for (int i = 0; i < 128; i++) { if(cnt[i] % 2 == 1) { pal.add((char)i); cnt[i]--; } cntEven += cnt[i]; for (int j = 0; j < cnt[i]; j++) { fill.add((char)i); } } if(pal.size() == 0) { Collections.sort(fill); int ind = 0; pw.println(1); StringBuilder pre = new StringBuilder(""); StringBuilder suf = new StringBuilder(""); for (int i = 0; i < n/2; i++) { pre.append(fill.get(ind++)); suf.append(fill.get(ind++)); } pw.print(pre); pw.print(suf.reverse()); pw.println(); pw.flush(); pw.close(); return; } int pals = pal.size(); int ans = 0; for (int l = 1; l <= n; l+=2) { int rem = cntEven - (l-1)*pals; if(rem < 0) continue; if(rem % l == 0) ans = l; } Collections.sort(fill); int ind = 0; int words = n/ans; int others = words - pal.size(); for (int i = 0; i < others; i+=2) { pal.add(fill.get(ind++)); pal.add(fill.get(ind++)); } pw.println(words); for (int i = 0; i < pal.size(); i++) { StringBuilder pre = new StringBuilder(); StringBuilder suf = new StringBuilder(); for (int j = 0; j < (ans-1)/2; j++) { pre.append(fill.get(ind++)); suf.append(fill.get(ind++)); } pw.print(pre); pw.print(pal.get(i)); pw.print(suf.reverse()); if(i != pal.size()-1) pw.print(" "); } pw.println(); pw.flush(); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
624afb7b5161837c50b2c671bbadb025
train_002.jsonl
1508573100
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.
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.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } static class TaskH { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); int[] cnt = new int[128]; for (int i = 0; i < n; i++) { cnt[s.charAt(i)]++; } int oddCnt = 0; for (int i = 0; i < 128; i++) { if (cnt[i] % 2 == 1) oddCnt++; } ArrayList<Integer> qty = new ArrayList<>(); for (int i = 1; i * i <= n; i++) { if (n % i == 0) { qty.add(i); if (n / i != i) { qty.add(n / i); } } } qty.sort(Integer::compareTo); for (int q : qty) { if ((q == 1 && oddCnt == n % 2) || ((n / q) % 2 == 1 && q >= oddCnt && (q - oddCnt) % 2 == 0) || ((n / q) % 2 == 0) && oddCnt == 0) { out.println(q); out.println(build(cnt, q, n)); return; } } } String build(int[] charCnt, int qty, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < qty; i++) { sb.append(buildPal(charCnt, n / qty)); if (i != qty - 1) sb.append(" "); } return sb.toString(); } String buildPal(int[] charCnt, int len) { char[] ans = new char[len]; if (len % 2 == 1) { for (int i = 0; i < 128; i++) { if (charCnt[i] % 2 == 1) { charCnt[i]--; ans[len / 2] = (char) i; break; } } if (ans[len / 2] == 0) { for (int i = 0; i < 128; i++) { if (charCnt[i] > 0) { charCnt[i]--; ans[len / 2] = (char) i; break; } } } } char ind = 0; for (int i = 0; i < len / 2; i++) { while (charCnt[ind] < 2) ind++; ans[i] = ind; ans[len - i - 1] = ind; charCnt[ind] -= 2; } return new String(ans); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\naabaac", "8\n0rTrT022", "2\naA"]
3 seconds
["2\naba aca", "1\n02TrrT20", "2\na A"]
null
Java 8
standard input
[ "implementation", "brute force", "strings" ]
d062ba289fd9c373a31ca5e099f9306c
The first line contains an integer n (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰4ยท105) โ€” the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.
1,800
Print to the first line an integer k โ€” minimum number of palindromes into which you can cut a given string. Print to the second line k strings โ€” the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
standard output
PASSED
2eb5efc21523804e34142a4eb0e83403
train_002.jsonl
1494860700
Digital collectible card games have become very popular recently. So Vova decided to try one of these.Vova has n cards in his collection. Each of these cards is characterised by its power pi, magic number ci and level li. Vova wants to build a deck with total power not less than k, but magic numbers may not allow him to do so โ€” Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character.At the moment Vova's character's level is 1. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static final int INF = (int)1e9; static int V, s, t; //s != t static ArrayList<Integer>[] adjList; static int[][] res; //instead of res, you can use c[][], f[][] so as not to destroy the graph static int[] p; //res (residual) = c (capacity) - f (flow) static int edmondsKarp() //O(min(VE^2, flow * E)) for adjList, O(V^3E) { int mf = 0; while(true) { Queue<Integer> q = new LinkedList<Integer>(); p = new int[V]; Arrays.fill(p, -1); q.add(s); p[s] = s; while(!q.isEmpty()) { int u = q.remove(); if(u == t) break; for(int v: adjList[u]) if(res[u][v] > 0 && p[v] == -1) { p[v] = u; q.add(v); } } if(p[t] == -1) break; mf += augment(t, INF); } return mf; } static int augment(int v, int flow) { if(v == s) return flow; flow = augment(p[v], Math.min(flow, res[p[v]][v])); res[p[v]][v] -= flow; res[v][p[v]] += flow; return flow; } static boolean[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new boolean[N+1]; isComposite[0] = isComposite[1] = true; for (int i = 2; i <= N; ++i) if (!isComposite[i]) { if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) isComposite[j] = true; } } static void addEdge(int i,int j,int cost) { adjList[i].add(j); adjList[j].add(i); res[i][j]=cost; } public static void main(String[] args) throws Exception{ PrintWriter pw=new PrintWriter(System.out); MScanner sc = new MScanner(System.in); sieve(200000); int n=sc.nextInt(),k=sc.nextInt(); int[][]in=new int[n][3]; for(int i=0;i<n;i++) { in[i]=sc.intArr(3); } int ans=-1; int lo=1,hi=n; V=n+2; s=V-2;t=V-1; while(lo<=hi) { int lvl=(lo+hi)>>1; boolean[]valid=new boolean[n]; for(int i=0;i<n;i++) { valid[i]=(in[i][2]<=lvl); } int maxOne=-1,max=0; for(int i=0;i<n;i++) { if(in[i][1]==1 && valid[i]) { if(in[i][0]>max) { max=in[i][0]; maxOne=i; } } } for(int i=0;i<n;i++) { if(in[i][1]==1 && valid[i] && i!=maxOne) { valid[i]=false; } } res=new int[V][V]; adjList=new ArrayList[V]; for(int i=0;i<V;i++)adjList[i]=new ArrayList<>(); int total=0; for(int i=0;i<n;i++) { if(!valid[i])continue; for(int j=0;j<n;j++) { if(!valid[j])continue; if(isComposite[in[i][1]+in[j][1]])continue; if(in[i][1]%2==0) { addEdge(i, j, INF); } else { addEdge(j, i, INF); } } if(in[i][1]%2==0) { addEdge(s, i, in[i][0]); } else { addEdge(i, t, in[i][0]); } total+=in[i][0]; } int totPower=total-edmondsKarp(); if(totPower>=k) { ans=lvl; hi=lvl-1; } else { lo=lvl+1; } } pw.println(ans); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void addX(int[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } static void addX(long[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } }
Java
["5 8\n5 5 1\n1 5 4\n4 6 3\n1 12 4\n3 12 1", "3 7\n4 4 1\n5 8 2\n5 3 3"]
2 seconds
["4", "2"]
null
Java 11
standard input
[ "binary search", "flows", "graphs" ]
de725cbd81d17d8e44c766e7b7e23f3d
The first line contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100, 1โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰100000). Then n lines follow, each of these lines contains three numbers that represent the corresponding card: pi, ci and li (1โ€‰โ‰คโ€‰piโ€‰โ‰คโ€‰1000, 1โ€‰โ‰คโ€‰ciโ€‰โ‰คโ€‰100000, 1โ€‰โ‰คโ€‰liโ€‰โ‰คโ€‰n).
2,400
If Vova won't be able to build a deck with required power, print โ€‰-โ€‰1. Otherwise print the minimum level Vova has to reach in order to build a deck.
standard output
PASSED
655ca938bc417ff19e63d5a8b216f1e5
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); int d = s.nextInt(); int h = s.nextInt(); if (2 * h < d || (h == 1 && d == 1 && n > 2)){ System.out.println("-1"); } else{ int branch_left = h; int branch_right = d - h; int non_leaf_root = -1; int bef = 1; int curr = 2; for(int i = 0; i < branch_left; i++, bef = curr, curr++){ System.out.println(bef + " " + curr); if(bef != 1) non_leaf_root = bef; } bef = 1; for(int i = 0; i < branch_right; i++, bef = curr, curr++){ System.out.println(bef + " " + curr); if(bef != 1) non_leaf_root = bef; } if(non_leaf_root == -1) non_leaf_root = 1; for(; curr <= n; curr++){ System.out.println(non_leaf_root + " " + curr); } } s.close(); } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
c786eaeb04095ada86624e2230002316
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static int INF = (int) 1e9 + 7; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), d = sc.nextInt(), h = sc.nextInt(); if(d > 2*h || h == 1 && h == d && n > 2) out.println(-1); else{ int cur = 2; d -= h; for (int i = 0; i < h && cur <= n; i++) { out.println(cur-1 + " " + cur); cur++; } int prev = 1; for (int i = 0; i < d && cur <= n; i++) { out.println(prev + " " + cur); prev = cur; cur++; } while(cur <= n){ out.println((h == 1?"1 ":"2 ") + cur++); } } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } 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 boolean ready() throws IOException { return br.ready(); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
999f458fae6769aefd6ca36d4badd396
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; import java.util.ArrayList; public class Test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n=scan.nextInt(), d=scan.nextInt(), h=scan.nextInt(); if (d>h+h || d<h || (d==1 && n>2)) System.out.println(-1); else { for (int i=1; i<=h; i++) System.out.printf("%d %d \n", i, i+1); for (int i=h+1; i<=d; i++) System.out.printf("%d %d \n", i!=h+1 ? i:1, i+1); for (int i=d+1; i<n; i++) System.out.printf("%d %d \n", h!=d ? 1:2, i+1); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
9470615b0d941d9f7fbe8980de579800
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * @author muhossain * @since 2020-02-11 */ public class B639 { public static void main(String[] args) { FastScanner fs = new FastScanner(System.in); int n = fs.nextInt(); int d = fs.nextInt(); int h = fs.nextInt(); if (d > 2 * h || (n >= 3 && d == 1)) { System.out.println("-1"); } else { StringBuilder output = new StringBuilder(); for (int i = 1; i <= h; i++) { output.append(i + " " + (i + 1)).append("\n"); } int pNode = 1; int cNode = h + 2; for (int i = 1; i <= d - h; i++) { output.append(pNode + " " + cNode).append("\n"); pNode = cNode; cNode++; } for (; cNode <= n; cNode++) { int root = (h == 1) ? 1 : 2; output.append(root + " " + cNode).append("\n"); } System.out.print(output); } } static class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
63d0ff281dcd232b23d893d4d6e957b5
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * @author muhossain * @since 2020-02-11 */ public class B639 { public static void main(String[] args) { FastScanner fs = new FastScanner(System.in); int n = fs.nextInt(); int d = fs.nextInt(); int h = fs.nextInt(); if (d > 2 * h || (n >= 3 && d == 1)) { System.out.println("-1"); } else { StringBuilder output = new StringBuilder(); for (int i = 1; i <= h; i++) { output.append(i + " " + (i + 1)).append("\n"); } int pNode = 1; int cNode = h + 2; for (int i = 1; i <= d - h; i++) { output.append(pNode + " " + cNode).append("\n"); pNode = cNode; cNode++; } for (; cNode <= n; cNode++) { int root = (h == 1) ? 1 : 2; //trying if 4 2 1 is present in the judge test cases // int root = 2; output.append(root + " " + cNode).append("\n"); } System.out.print(output); } } static class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
ae7fe25bd2f183b37dfb11bc629a51af
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class C658 { private static boolean home = !"true".equals(System.getProperty("ONLINE_JUDGE")); private static boolean debug = false; public static void main(String[] args) throws IOException { int nrTeste = 3; String[] inputs = {"5 3 2\n", "8 5 2\n", "8 4 2\n"}; String[] expected = {"1 2\n1 3\n3 4\n3 5", "-1\n", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5\n"}; for (int i = 0; home && i < nrTeste; i++) { System.out.print("\nExpect: " + expected[i] + "\n Got: "); System.setIn(new ByteArrayInputStream(inputs[i].getBytes())); solve(); } if (!home) { solve(); } System.out.close(); } public static void solve() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String[] line; line = br.readLine().split(" "); int n = Integer.parseInt(line[0]); int d = Integer.parseInt(line[1]); int h = Integer.parseInt(line[2]); if (h > d || d > 2*h || d < h || (n>2 && d<2)) { pw.println("-1"); } else { // build height for (int i = 1; i <= h; i++) { pw.printf("%d %d\n", i, i+1); } // build diameter if (d> h) { pw.printf("%d %d\n", 1, h+2); int missing = d- h -1; for (int i = h+2; i< h+2 + missing; i++) { pw.printf("%d %d\n", i, i+1); } } // build rest of tree for (int i = Math.max(d, h)+2; i <= n; i++) { pw.printf("%d %d\n", h, i); } } br.close(); pw.flush(); } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
6e0fcb0be1ddadd11c50ab03c5425d1e
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; tk = new StringTokenizer(in.readLine()); int n = parseInt(tk.nextToken()),d = parseInt(tk.nextToken()),h = parseInt(tk.nextToken()); if(d-h > h || d>n-1) { System.out.println("-1"); return; } int cur = 2; int e = 0; for(int i=0; i<h; i++) { out.append(cur-1).append(" ").append(cur).append("\n"); e++; cur++; if(e==n-1 && i+1<h) { System.out.println("-1"); return; } } if(d==h && cur<=n) { if(h==1) { System.out.println(-1); return; } else { for(int i=cur; i<=n; i++) out.append(2).append(" ").append(i).append("\n"); } System.out.print(out); return; } if(e>n-1 || cur-1>n) { System.out.println("-1"); return; } if(e==n-1) { System.out.print(out); return; } out.append("1 ").append(cur).append("\n"); cur++; e++; if(e > n-1) { System.out.println("-1"); return; } for(int i=1; i<d-h; i++) { out.append(cur-1).append(" ").append(cur).append("\n"); cur++; e++; if(e==n-1 && i+1<d-h) { System.out.println(-1); return; } } int i=0; while(e < n-1) { if(i==0) out.append(1).append(" ").append(cur).append("\n"); else out.append(cur-1).append(" ").append(cur).append("\n"); e++; i++; cur++; if(e<n-1 && cur==n+1) { System.out.println(-1); return; } if(i == min(h,d-h)) i = 0; } if(cur-1>n || e>n-1) { System.out.println("-1"); return; } System.out.print(out); } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
0f28fffce47c1c8c252795d3f69f70b3
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int d = readInt(); int h = readInt(); /* * Construction * 1 to 2 * 2 to 3 * ... * h to h+1 * h is base */ if(2*h < d) { pw.println(-1); continue; } if(d == 1 && n > 2) { pw.println(-1); continue; } int curr = 1; while(curr <= h) { pw.println((curr) + " " + (curr+1)); curr++; } curr++; int extra = d - h; if(extra > 0) { int connect = curr; extra--; pw.println(1 + " " + connect); curr++; while(extra-- > 0) { pw.println(connect + " " + curr); connect = curr; curr++; } } while(curr <= n) { pw.println(h + " " + curr); curr++; } } pw.close(); } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
890fe101e4398e53796842831b905ae7
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; public class Tree{ public static void main(String [] args){ Scanner sc=new Scanner(System.in); int n=0; int d=0; int h=0; n=sc.nextInt(); d=sc.nextInt(); h=sc.nextInt(); if(d>2*h || d<h || (d==1 && n>2)) {System.out.println("-1");} else { for(int i=0; i<h;i++) { System.out.print(i+1+" "); System.out.println(i+2); } if(h<d) {System.out.print(1+" "); System.out.println(h+2); } for(int i=h+1; i<d; i++) { System.out.print(i+1+" "); System.out.println(i+2); } for(int i=d; i<n-1;i++) { System.out.print(h+" "); System.out.println(i+2); } } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
f09c53b8a2a70339c72028fa46061036
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.*; import java.io.*; /** * * @author umang */ public class B639 { public static int mod = 1000000007; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int d = in.nextInt(); int h = in.nextInt(); if(d<=2*h && !(d==1 && n>2)){ int count=1; while(count<=h){ w.println((count)+" "+(count+1)); count++; } if(count<n){ count++; boolean f=false; if(d>h){ w.println(1+" "+(count)); f=true; } else{ while(count<=n){ w.println(2+" "+count); count++; } } while(count<=d){ w.println(count+" "+(count+1)); count++; f=true; } if(f) count++; while(count<=n){ w.println(1+" "+count); count++; } } } else w.println("-1"); w.close(); } 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
b72feac6960e62c7e734c931209cccba
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
/** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class rnd132_C { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class P implements Comparable{ private int x, y; public P(int x, int y) { this.x = x; this.y = y; } public int hashCode() { return (x * 31) ^ y; } public boolean equals(Object o) { if (o instanceof P) { P other = (P) o; return (x == other.x && y == other.y); } return false; } public int compareTo(Object obj) { P l = (P) obj; if (this.x == l.x){ if (this.y == l.y) return 0; return (this.y < l.y)? -1: 1; } return (this.x < l.x)? -1: 1; } } public static void main(String[] args){ FastScanner s = new FastScanner(System.in); StringBuilder op=new StringBuilder(); int n=s.nextInt(); int d=s.nextInt(); int h=s.nextInt(); int[] pr=new int[n+1]; if(h>d)System.out.println(-1); else{ if(h==d) { if(h==1&&n>2){ System.out.println(-1);return; } int v=2; while(h>0){ System.out.println(v-1 + " " + v);h--; v++; } while(v<=n){ System.out.println(2 +" " +v);v++; } } else{ if((d%2==0 && h<d/2) || (d%2!=0 &&h<(d+1)/2)) System.out.println(-1); else{ int v=2; int H=h; while(h>0&&v<=n){ System.out.println(v-1 + " " + v); pr[v]=1; v++;h--; } h=d-H;System.out.println(1+ " " + v);h--;pr[v]=1;v++; while(h>0&&v<=n){ System.out.println(v-1 + " " + v);pr[v]=1; v++;h--; } for(int i=2;i<=n;i++) if(pr[i]==0){System.out.println(1 + " " + i);pr[i]=1;} } } } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
982719a2d383a8855a437273cc781ee4
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B639 { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static String nextLine() throws IOException { return br.readLine(); } static char nextChar() throws IOException { return (char) br.read(); } public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); run(); pw.close(); } static boolean[][] matrix; static int p = 1; private static void run() { int n = nextInt(); int d = nextInt(); int h = nextInt(); if (d > h * 2 || (n > 2 && d == 1)) { pw.print(-1); return; } int i = 2; for (int k = 0; k < 2 && i <= n && d > 0; k++) { pw.println(1 + " " + i); d--; i++; for (int j = 0; j < h - 1 && d > 0; j++) { pw.println((i - 1) + " " + i); i++; d--; } } int p = 1; if (h >= 2) p++; while (i <= n) { pw.println(p + " " + i); i++; } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
d6bcbb84fde6bd7fe37b46808aa4aa3d
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class P { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(), d = sc.nextInt(), h = sc.nextInt(); if (d > 2 * h || (d == h && d == 1 && N != 2)) out.println(-1); else if (N == 2) { out.print("1 2"); } else { int cur = 1, nxt = 2; for (int i = 0; i < h; ++i) { out.println(cur + " " + nxt); cur++; nxt++; } if (d == h) { cur = 2; for (int c = h + 1; c < N; ++c, nxt++) out.println(cur + " " + nxt); } else { for (int c = h + 1; c < N;) { out.flush(); cur = 1; for (int i = 0; i < d - h && c < N; ++i) { out.println(cur + " " + nxt); cur = nxt; nxt++; c++; } } } } out.close(); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
0bc548a3eaf89f26fc1bf15dc8a2ae7f
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; public class BearAndTree { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfVertices = input.nextInt(); int diameterOfTree = input.nextInt(); int heightBetweenVertices = input.nextInt(); searchOfPath(numberOfVertices, diameterOfTree, heightBetweenVertices); input.close(); } private static void searchOfPath(int numberOfVertices, int diameterOfTree, int heightBetweenVertices) { if (2 * heightBetweenVertices < diameterOfTree || (heightBetweenVertices == 1 && diameterOfTree == 1 && numberOfVertices > 2)) { System.out.println("-1"); return; } for (int i = 2; i <= heightBetweenVertices + 1; i++) { System.out.println((i - 1) + " " + i); } for (int i = 1; i <= diameterOfTree - heightBetweenVertices; i++) { System.out.println(((i == 1) ? 1 : heightBetweenVertices + i) + " " + (heightBetweenVertices + i + 1)); } for(int i = 0; i < numberOfVertices - diameterOfTree - 1; i++) { System.out.println((heightBetweenVertices == diameterOfTree ? 2 : 1) + " " + (i + diameterOfTree + 2)); } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
d2b10ae8c443357cee0319aa9c7de3b7
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class BearAndTheForgottenTree { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int d = Integer.parseInt(st.nextToken()); int h = Integer.parseInt(st.nextToken()); if( d>2*h) System.out.println("-1"); else if(n==2 && h==1 && d==1) System.out.println("1 2"); else if(d - h > h || (d == h && d == 1 && n > 2)) System.out.println("-1"); else { TreeSet<Integer> tree = new TreeSet<>(); int counter = 1; int to = 0; int height = h; int rem = d-h; if(d-h <0 || n < d) System.out.println("-1"); else{ while(height-->0){ System.out.println(counter+1+" "+(to+1)); to = counter; counter++; // System.out.println("hiiii"); } int last = 0; // counter = 1; to = 0; while(rem-->0){ // System.out.println(counter+"*------"); System.out.println(last+1+" "+ (counter+1)); last=counter++; } // counter--; int extra = 1; if(d==h){ extra = counter-1; } for(int i = counter; i<n ; i++){ System.out.println(extra+" "+(i+1)); to++; } } } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
4c6d182d34ccaa1b26a4c0651fa0fb59
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int h = in.nextInt(); if (d > 2 * h || (n > 2 && d == 1)) { System.out.println("-1"); } else { for (int i = 1; i <= h; i++) { System.out.println(i + " " + (i + 1)); } for (int i = h + 1; i <= d; i++) { if (i == h + 1) System.out.println("1 " + (i + 1)); else System.out.println(i + " " + (i + 1)); } for (int i = d + 1; i < n; i++) { if (h == d) System.out.println("2 " + (i + 1)); else System.out.println("1 " + (i + 1)); } } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
6e471416840ac91ca4ac8cd91f39d8b4
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
import java.util.Scanner; public class BearAndForgottenTree3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int h = in.nextInt(); if (d > 2 * h || (n > 2 && d == 1)) { System.out.println("-1"); } else { for (int i = 1; i <= h; i++) { System.out.println(i + " " + (i + 1)); } for (int i = h + 1; i <= d; i++) { if (i == h + 1) System.out.println("1 " + (i + 1)); else System.out.println(i + " " + (i + 1)); } for (int i = d + 1; i < n; i++) { if (h == d) System.out.println("2 " + (i + 1)); else System.out.println("1 " + (i + 1)); } } } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
608ef8be7e116161efa9053ae6b4bb4c
train_002.jsonl
1459182900
A tree is a connected undirected graph consisting of n vertices and nโ€‰โ€‰-โ€‰โ€‰1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeย โ€” he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeย โ€“ in this case print "-1".
256 megabytes
/*Author LAVLESH*/ import java.util.*; import java.io.*; public class solution{ static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st=new StringTokenizer(""); static 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 static void main(String[]args)throws IOException{ PrintWriter op =new PrintWriter(System.out,true); int n=Integer.parseInt(next()); double d=Integer.parseInt(next()); double h=Integer.parseInt(next()); if(h<Math.ceil(d/2)||h>d||(h==1&&d==1&&n!=2)){op.println(-1);return;} int count=1; for(int i=0;i<(int)h;i++) if(count+1<=n)op.println(count+" "+(++count)); while(count+1<=n){ if(d!=h)op.println(1+" "+(++count)); else op.println(2+" "+(++count)); for(int i=0;i<(int)(d-h)-1;i++) { if(count+1<=n)op.println(count+" "+(++count)); } } op.close(); } }
Java
["5 3 2", "8 5 2", "8 4 2"]
2 seconds
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
NoteBelow you can see trees printed to the output in the first sample and the third sample.
Java 8
standard input
[ "constructive algorithms", "trees", "graphs" ]
32096eff277f19d227bccca1b6afc458
The first line contains three integers n, d and h (2โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰1โ€‰โ‰คโ€‰hโ€‰โ‰คโ€‰dโ€‰โ‰คโ€‰nโ€‰-โ€‰1)ย โ€” the number of vertices, diameter, and height after rooting in vertex 1, respectively.
1,600
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nโ€‰-โ€‰1 lines, each with two space-separated integersย โ€“ indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
standard output
PASSED
669c12e10a33edec689213b29156dda1
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.*; import java.util.*; public class Div2_354_C { public static int getAnswer(boolean [] binaryString, int k) { int switched = 0, i = 0, j = -1, ans = 1; for(i = 0;i < binaryString.length;i++) { while(j < binaryString.length && switched <= k) { j++; if(j < binaryString.length && binaryString[j]) switched++; } ans = Math.max(j-i, ans); if(binaryString[i]) switched--; } return ans; } public static void main(String[] args) throws IOException { BufferedInputStream bis = new BufferedInputStream(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(bis)); String line; while((line = br.readLine()) != null && !line.trim().equals("")) { StringTokenizer st = new StringTokenizer(line); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int ans = 0; line = br.readLine().trim(); for(char c = 'a';c <= 'b';c++) { boolean [] binaryString = new boolean[n]; for (int i = 0; i < n; i++) { binaryString[i] = line.charAt(i)!=c; } ans = Math.max(ans, getAnswer(binaryString, k)); } System.out.println(ans); } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
b041c4b7dfdcfe67de1899a3217530b7
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.*; import java.util.*; public class VasyaAndString { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(); char[] a = in.readString().toCharArray(); int bad = 0, prev = 0; int result = 0; for (int i = 0; i < n; i++) { if(a[i] == 'b') bad++; if(bad > k) { while(prev <= i && a[prev] == 'a') prev++; prev++; bad--; } result = Math.max(result, i - prev + 1); } prev = 0; bad = 0; for (int i = 0; i < n; i++) { if(a[i] == 'a') bad++; if(bad > k) { while(prev <= i && a[prev] == 'b') prev++; prev++; bad--; } result = Math.max(result, i - prev + 1); } out.println(result); out.close(); } static class Node implements Comparable<Node>{ int num, freq, idx; public Node (int u, int v, int idx) { this.num = u; this.freq = v; this.idx = idx; } public void print() { out.println(num + " " + freq + " " + idx); } public int compareTo(Node n) { if(this.freq == n.freq) return Integer.compare(this.num, n.num); return Integer.compare(-this.freq, -n.freq); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
9f01de8585d6f39148b3d07c0037d806
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Mai { public static class FastReaderFile { BufferedReader br; StringTokenizer st; public FastReaderFile(InputStream in) { br = new BufferedReader(new InputStreamReader(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 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 PrintWriter out; public static int ser ( int x[] , int start , int end , int val ) { while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( x[mid] == val ) return mid ; if ( x[ mid ] <= val ) start = mid + 1 ; else end = mid - 1 ; } return -start - 1 ; } public static boolean isPrime( long n) { if (n < 2) return false; if (n < 4) return true; if (n%2 == 0 || n%3 == 0) return false; for (long i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0) return false ; return true; } static long gcd(long a, long b) { return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b); } static long lcm(long a, long b) { long lcm = (a / gcd(a, b)) * b; return lcm > 0 ? lcm : -lcm ; } public static int search( int x[] , int val ) { return ser( x , 0 , x.length - 1 , val ); } public static String remove ( String s , int i ) { return s.substring(0, i) + s.substring(i+1) ; } // for (Map.Entry<Integer, Integer> e : x.entrySet()) // { // e.getValue() , e.getKey public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here FastReader in = new FastReader(); // Scanner in = new Scanner(System.in) ; // FastReaderFile in = new FastReaderFile(new FileInputStream("fruits.in")) ; // out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")), true) ; out = new PrintWriter(new BufferedOutputStream(System.out), true) ; int n = in.nextInt() , k = in.nextInt() , max = 0 , j = 0 , c = 0 , i = 0 , t = 0 ; String s = in.next() ; char ch = 'a' ; while ( j < n ) { while ( j < n && s.charAt(j) == ch ) { ++j ; ++c ; } // out.append("c = " + c + " t = " + t + " " + " j = " + j + " "); max = Math.max(max, c); if (t < k && j < n && s.charAt(j) != ch ) while ( t < k && j < n && s.charAt(j) != ch ) { ++c ; ++j ; ++t ; } else if ( t >= k && s.charAt(i) == ch ) { while ( t >= k && i < n && s.charAt(i) == ch ) { --c ; ++i ; } --c ; ++i ; --t ; } else if ( t >= k ) { --c ; ++i ; --t ; } max = Math.max(max, c); // out.println( " c = " + c + " t = " + t + " j = " + j ); } j = 0 ; i = 0 ; t = 0 ; c = 0 ; ch = 'b'; while ( j < n ) { while ( j < n && s.charAt(j) == ch ) { ++j ; ++c ; } // out.append("c = " + c + " t = " + t + " " + " j = " + j + " "); max = Math.max(max, c); if (t < k && j < n && s.charAt(j) != ch ) while ( t < k && j < n && s.charAt(j) != ch ) { ++c ; ++j ; ++t ; } else if ( t >= k && s.charAt(i) == ch ) { while ( t >= k && i < n && s.charAt(i) == ch ) { --c ; ++i ; } --c ; ++i ; --t ; } else if ( t >= k ) { --c ; ++i ; --t ; } max = Math.max(max, c); // out.println( " c = " + c + " t = " + t + " j = " + j ); } out.println(max); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
54386d2668b342d671a3d1d7e81b57ab
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class vasya { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); char[] chars = in.readLine().toCharArray(); int max = 0; for(char ch = 'a'; ch <= 'b'; ch++) { int l = 0; int r = k - 1; int diff = 0; for(int i = l; i <= Math.min(n-1, r); i++) { if(chars[i] != ch) { diff++; } } max = Math.max(max, r - l + 1); while(r < n - 1) { r++; if(chars[r] != ch) { diff++; } while(diff > k && l <= r) { if(chars[l] != ch) { diff--; } l++; } max = Math.max(max, r - l + 1); } } out.println(max); in.close(); out.close(); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
10576979b7cd94201149de4c1aa73ac8
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader fi = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, fi, out); out.close(); } static class Task { public void solve(int testNumber, InputReader fi, PrintWriter out) { int i,j,n,l,m,k,index,len,ans; n=fi.nextInt(); k=fi.nextInt(); String s=fi.readString(); l=s.length(); index=0; len=ans=0; ArrayList<Integer> aindex=new ArrayList<>(); ArrayList<Integer> bindex=new ArrayList<>(); for (i=0;i<l;i++){ if (s.charAt(i)=='a') aindex.add(i); else bindex.add(i); } //now check for a int asize=aindex.size(); int bsize=l-asize; int left,right; left=right=0; if (k<bsize) ans=bindex.get(k); else ans=n; for (i=0;i<bsize;i++){ left=bindex.get(i); if (i+k+1 < bsize){ right=bindex.get(i+k+1); } else right=n; ans=Math.max(ans,right-left-1); } if (k<asize) ans=Math.max(aindex.get(k),ans); else ans=n; left=right=0; for (i=0;i<asize;i++){ left=aindex.get(i); if (i+k+1 < asize){ right=aindex.get(i+k+1); } else right=n; ans=Math.max(ans,right-left-1); } out.println(ans); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n+1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
60a511d27c182ac84c6a1516767e471b
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { new Solver().run(); } } class Solver { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); private int max(char target, int n, int k, String s) { char[] cs = s.toCharArray(); int ret = 0; int t = 0; for (int i = 0; i < n; i++) { if (cs[i] != target) { t++; ret = Math.max(ret, t); } else t = 0; } int i = 0; int cur = 0; int curK = 0; List<Integer> is = new ArrayList(); for (; i < n; i++) { if (cs[i] != target) { cur = i; } else if (curK < k) { is.add(i); curK++; cur = i; } else { break; } } int from = 0; ret = Math.max(ret, cur - from + 1); if (is.size() == 0) return ret; for (; i < n; i++) { if (cs[i] != target) { cur++; ret = Math.max(ret, cur - from + 1); } else { int j = is.remove(0); cur++; is.add(i); from = j + 1; ret = Math.max(ret, cur - from); } } return ret; } private void solve() { int n = in.nextInt(); int k = in.nextInt(); String s = in.next(); out.println(Math.max(max('a', n, k, s), max('b', n, k, s))); } void run() { solve(); out.flush(); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
a985c472e53a8aae26a3e70c369d51f0
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
// package cf676; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; public class CFC { private static final String INPUT = "8 1\n" + "aabaabaa\n"; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFC().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public void solve() { int n = sc.nextInt(); int k = sc.nextInt(); String line = sc.nextLine(); int ans = max(line, n, k, 'a'); ans = Math.max(ans, max(line, n, k, 'b')); System.out.println(ans); } int max(String line, int n, int k, int chr) { int lim = k; int last = 0; for (int j = 0; j < n; j++) { if (line.charAt(j) != chr) { if (lim > 0) { lim--; } else { break; } } last = j+1; } int ans = last; for (int i = 1; i < n - k; i++) { if (line.charAt(i - 1) != chr) { lim = 1; for (int j = last; j < n; j++) { if (line.charAt(j) != chr) { if (lim > 0) { lim--; } else { break; } } last = j+1; } ans = Math.max(ans, last - i); } } return ans; } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
6895ca8cd547ea0b93d32092a31a7042
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
// package cf676; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; public class CFC { private static final String INPUT = "8 1\n" + "babaabba\n"; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFC().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public void solve() { int n = sc.nextInt(); int k = sc.nextInt(); String line = sc.nextLine(); int ans = max(line, n, k, 'a'); ans = Math.max(ans, max(line, n, k, 'b')); System.out.println(ans); } int max(String line, int n, int k, int chr) { int ans = 0; int r = 0; for (int i = 0; i < n; i++) { for (int j = r; j < n; j++) { if (line.charAt(j) != chr) { if (k > 0) { k--; } else { break; } } r = j + 1; } ans = Math.max(ans, r - i); if (line.charAt(i) != chr) k = 1; } return ans; } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
62d8233bf5ec2ff544553e92736c0754
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static InputStream inputstream = System.in; static PrintStream outputstream = System.out; static InputReader in = new InputReader(inputstream); static PrintWriter out = new PrintWriter(outputstream); public static void main(String []args){ int n = in.nextInt(); int k = in.nextInt(); int res = 0; String s = in.next(); int[] sum = new int[n + 1]; for (int i = 0; i < n; i++) { sum[i + 1] = sum[i] + (s.charAt(i) == 'a' ? 1 : 0); } for (int fr = 0; fr < n; fr++) { int left = fr; int right = n; while (right - left > 1) { int mid = (left + right) / 2; int cnt = sum[mid + 1] - sum[fr]; int len = mid - fr + 1; if (Math.min(cnt, len - cnt) <= k) { left = mid; } else { right = mid; } } res = Math.max(res, left - fr + 1); } out.println(res); out.flush(); } } class InputReader { //ๆ”พๅˆฐไฝ ็š„ไธป็จ‹ๅบ็š„ไธ‹ๆ–นๅ’ฏ BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } String next() { if (!hasNext()) throw new RuntimeException(); return tokenizer.nextToken(); } boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { return false; } return true; } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
022e9af48b22cffdb6d2b93a08ee9a28
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); String str = in.next(); int left = 0; int right = 0; int max = 0; int cnt = 0; if(str.charAt(0) == 'b') cnt++; while(right < n) { if(cnt > k) { if(str.charAt(left) == 'b') cnt--; left++; } else if(cnt <= k) { max = Math.max(max, (right+1)-left); right++; if(right < n && str.charAt(right) == 'b') cnt++; } } left = 0; right = 0; cnt = 0; if(str.charAt(0) == 'a') cnt++; while(right < n) { if(cnt > k) { if(str.charAt(left) == 'a') cnt--; left++; } else if(cnt <= k) { max = Math.max(max, (right+1)-left); right++; if(right < n && str.charAt(right) == 'a') cnt++; } } out.println(max); 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()); } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
f25f55007316192aea2ca29eab656296
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; public class VasyaAndString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); String str = sc.next(); int countA = 0; int countB = 0; ArrayList<Integer> IndexOfA = new ArrayList<Integer>(); ArrayList<Integer> IndexOfB = new ArrayList<Integer>(); for(int i=0; i<n; i++) { if(str.charAt(i)=='a') { countA += 1; IndexOfA.add(i); } else { countB += 1; IndexOfB.add(i); } } int minCount = Math.min(countA, countB); // System.out.println(minCount); // System.out.println(countA); // System.out.println(countB); if(minCount <= k) System.out.println(str.length()); else { int maxA = IndexOfB.get(k); int maxB = IndexOfA.get(k); if(minCount == countB) { int index = 0; index += 1; while(index+k-1 < IndexOfB.size()) { int firstB = IndexOfB.get(index-1); int lastB = str.length(); if(index+k < IndexOfB.size()) lastB = IndexOfB.get(index+k); maxA = Math.max(maxA, lastB-(firstB+1)); index += 1; } } if(minCount == countA) { int index = 0; index += 1; while(index+k-1 < IndexOfA.size()) { int firstA = IndexOfA.get(index-1); int lastA = str.length(); if(index+k < IndexOfA.size()) lastA = IndexOfA.get(index+k); maxB = Math.max(maxB, lastA-(firstA+1)); index += 1; } } System.out.println(Math.max(maxA,maxB)); } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
72837cb763a969ddccbbc48c4bd97e93
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class VasyaandStrin { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st =new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); // String s = br.readLine(); // int[] d1 = new int[n+1]; // int[] d2 = new int[n+1]; char[] s = br.readLine().toCharArray(); // System.out.println("fds"); int ma = solve(s,k,'a'); int mb = solve(s,k,'b'); System.out.println(Math.max(ma,mb)); } static int solve(char[] s, int k, char c){ int ans=0; for(int i=0,j=0,l=0;i<s.length;i++){ if(j<i){ j=i; l=0; } while(j<s.length && (l<k || s[j]!=c)){ if(s[j]==c){ l++; } j++; } ans = Math.max(ans,j-i); if(s[i]==c){ l--; } } return ans; } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
d8d4b414dd82405c04f32baf4635f575
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.nextInt(); int max=0; int k = in.nextInt(); String s = in.readString(); int p1=0; int p2 =0; int current =k; while (p1<n) { while(p2<n) { if (s.charAt(p2)=='b') { if (current > 0) current--; else break; } p2++; } max= Math.max(max,p2-p1); if (s.charAt(p1)=='b') current++; p1++; } p1=0; p2 =0; current =k; while (p1<n) { while(p2<n) { if (s.charAt(p2)=='a') { if (current > 0) current--; else break; } p2++; } max= Math.max(max,p2-p1); if (s.charAt(p1)=='a') current++; p1++; } out.printLine(max); out.flush(); } } class Graph { int n; LinkedList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new LinkedList[n]; for (int i = 0; i < n; i++) adjList[i] = new LinkedList<>(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
4ea87db13bb15daa9f5a2f595b8dabed
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String l[]; l = bf.readLine().split(" "); int n = Integer.parseInt(l[0]); int k = Integer.parseInt(l[1]); int max = 1; int hi, lo, mid, sum; char[] s = bf.readLine().toCharArray(); int[] prevNotEq; for (char i = 'a'; i <= 'z'; i++) { prevNotEq = new int[n]; for (int j = 0; j < n; j++) { if (j != 0) prevNotEq[j] = prevNotEq[j - 1]; if (s[j] != i) prevNotEq[j]++; lo = -1; hi = j - 1; while (lo + 1 < hi) { mid = (lo + hi) >> 1; sum = prevNotEq[j]; if (mid > 0) sum -= prevNotEq[mid - 1]; if (sum <= k) { hi = mid; } else { lo = mid; } } if (hi > -1) max = Math.max(max, j - hi + 1); } } System.out.println(max); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
befcab1b71a0482f47f4ea7dfd96d894
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class CF676C implements Runnable { public void run() { int n = nextInt(); int k = nextInt(); String s = nextWord(); int ans = getMaxStringBeauty(n, k, s); out.println(ans); out.flush(); } int getMaxStringBeauty(int n, int k, String s) { int left = 0; int right = 0; int aCnt = 0; int bCnt = 0; int ans = 1; if (s.charAt(right) == 'a') { ++aCnt; } else if (s.charAt(right) == 'b') { ++bCnt; } while (right < n-1) { ++right; if (s.charAt(right) == 'a') { ++aCnt; } else if (s.charAt(right) == 'b') { ++bCnt; } while (aCnt > k && bCnt > k) { if (s.charAt(left) == 'a') { --aCnt; } else if (s.charAt(left) == 'b') { --bCnt; } ++left; } ans = Math.max(ans, right - left + 1); } return ans; } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new CF676C()).run(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return null; } private int nextInt() { while (stk == null || !stk.hasMoreElements()) loadLine(); return Integer.parseInt(stk.nextToken()); } private long nextLong() { while (stk == null || !stk.hasMoreElements()) loadLine(); return Long.parseLong(stk.nextToken()); } private double nextDouble() { while (stk == null || !stk.hasMoreElements()) loadLine(); return Double.parseDouble(stk.nextToken()); } private String nextWord() { while (stk == null || !stk.hasMoreElements()) loadLine(); return (stk.nextToken()); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
fb1e1e8d02ac0ef5aa539affad268545
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; public class test { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); String s=sc.next(); int answer=0; int l=0; int count[]=new int[2]; for(int i=0;i<s.length();i++) { count[s.charAt(i)-'a']++; if(Math.min(count[0],count[1])<=k) { answer++; } else { count[s.charAt(l++)-'a']--; }} System.out.println(answer);}}
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
e895e5258e1ab17a3ec4ff2b3f6a1612
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; public class A { static class Node{ int x; int y; public Node(int x,int y){ this.x=x; this.y=y; } } //public static PrintWriter pw; public static PrintWriter pw = new PrintWriter(System.out); public static void solve() throws IOException { // pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in")); FastReader sc = new FastReader(); int n=sc.I(); int k=sc.I(); char s[]=sc.next().toCharArray(); int l=1,h=n; int ans=1; int cc1[]=new int[n+1]; int cc2[]=new int[n+1]; for(int i=1;i<=n;i++) if(s[i-1]=='a') cc1[i]=cc1[i-1]+1; else cc1[i]=cc1[i-1]; for(int i=1;i<=n;i++) if(s[i-1]=='b') cc2[i]=cc2[i-1]+1; else cc2[i]=cc2[i-1]; out : while(l<=h){ int sz=(l+h)/2; int d=0; boolean is=false; for(int i=sz;i<=n;i++){ if(Math.min(cc1[i]-cc1[i-sz],cc2[i]-cc2[i-sz])<=k) is=true; } if(is){ ans=Math.max(ans,sz); l=sz+1; }else h=sz-1; } pw.println(ans); pw.close(); } public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } static BufferedReader br; static long M = (long) 1e9 + 7; static class FastReader { StringTokenizer st; public FastReader() throws FileNotFoundException { //br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in")); 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 I() { return Integer.parseInt(next()); } long L() { return Long.parseLong(next()); } double D() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public boolean hasNext() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } return true; } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
f6d6751d69db8f93922217583c918dc7
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.awt.List; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; //Vaysa and string two pointer technique public class Main { public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n =sc.nextInt(); int k =sc.nextInt(); String str =sc.nextToken();int ans =0; for(int o=0;o<2;o++){ char tmp =(char) ('a'+o); int i=0; int j= 0; int b=0; while(j<n && i<n){ if(str.charAt(j)!=tmp) b++; if(b==k+1){ b--; while(i<=j && i<n &&str.charAt(i)==tmp){ i++; } i++; } ans=Math.max(ans, j-i+1); j++; } } out.print(ans); out.close(); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
0e98941b83413b66c1d09de04c27f9a0
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.awt.List; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; public class Main { public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n= sc.nextInt(); int k=sc.nextInt();String str =sc.nextToken(); if(n==1){ System.out.println(1); return; } int A[]= new int[n+2]; int[] B= new int[n+2]; for(int i=0;i<n;i++){ if(str.charAt(i)=='a') { A[i]=0; B[i]=1; }else{ A[i]=1; B[i]=0; } } for(int i=1;i<n;i++){ A[i]+=A[i-1]; B[i]+=B[i-1]; } int ans =0; for(int i=0;i<n;i++){ int lo=i; int hi=n-1;int ex= 0;int mid=0; for(int j=1;j<=50;j++) { mid = (lo+hi)>>1; if( mid >=0 && mid<n&&str.charAt(i)-'a'+A[mid]-A[i]<=k){ ex=mid; lo=mid+1; }else hi=mid-1; } // System.out.println(ex); ans=Math.max(ans, ex-i+1); } //////////////////////// for(int i=0;i<n;i++){ int lo=i; int hi=n-1;int ex= 0;int mid=0; for(int j=1;j<=50;j++) { mid = (lo+hi)>>1; if(mid>=0 && mid<n &&(str.charAt(i)=='b'?0:1)+B[mid]-B[i]<=k){ ex=mid; lo=mid+1; }else hi=mid-1; } // System.out.println(ex); ans=Math.max(ans, ex-i+1); } System.out.println(ans); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
71bcc6850437ca76c986b69afc8f6520
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.util.*; public class Practice { static int mod = 1000000007; public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.next()); int k = Integer.parseInt(s.next()); String str = s.next(); int a = 0 , b = 0, max = 0, index = 0; for(int i=0;i<n;i++) { if(str.charAt(i)=='a') a++; else b++; if(Math.min(a, b)<=k) max=Math.max(max,a+b); else { if(str.charAt(index)=='a') a--; else b--; index++; } } System.out.println(max); //System.out.println(max); } // static int find(int a[], int t[], int power, int pos, int total){ // if(pos == a.length) // return total; // // int opt1 = 0, opt2 = 0; // // if(pos >= 1 && pos <= a.length - power + 1) // opt1 = find(a, t, 0, pos+power, total + a[pos+power-1] - a[pos-1]); // // if(t[pos] == 1) // opt2 = find(a, t, power, pos+1, total+a[pos]-a[pos-1]); // else // opt2 = find(a, t, power, pos+1, total); // // return Math.max(opt1, opt2); // } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
c4b277a2fefc6d7cff7ff1fc571e9ffa
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
//package com.company; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); String s = in.next(); int[] as = new int[n]; int pointerA = 0; int[] bs = new int[n]; int pointerB = 0; int[][] dp = new int[n][2]; for(int i=0; i<n; i++){ if(s.charAt(i) == 'a'){ as[pointerA] = i; pointerA++; }else{ bs[pointerB] = i; pointerB++; } } pointerA=0; pointerB=0; // a substring int maxa=0; boolean first=true; for (int i=0; i<n; i++){ int ka = k; while(ka>0 && first && i<n){ if(s.charAt(i) == 'b'){ ka--; } dp[i][0] = i+1; maxa = Math.max(maxa,dp[i][0]); i++; } if(i==n){ break; } first = false; if(s.charAt(i) == 'a'){ if(i==0){ dp[i][0] = 1; }else{ dp[i][0] = dp[i-1][0]+1; } }else{ dp[i][0] = i-bs[pointerB]; pointerB++; } maxa = Math.max(maxa,dp[i][0]); } // b substring int maxb=0; boolean first2=true; for (int i=0; i<n; i++){ int ka = k; while(ka>0 && first2 && i<n){ if(s.charAt(i) == 'a'){ ka--; } dp[i][1] = i+1; maxb = Math.max(maxb,dp[i][1]); i++; } if(i==n){ break; } first2 = false; if(s.charAt(i) == 'b'){ if(i==0){ dp[i][1] = 1; }else{ dp[i][1] = dp[i-1][1]+1; } }else{ dp[i][1] = i-as[pointerA]; pointerA++; } maxb = Math.max(maxb,dp[i][1]); } // for(int i=0; i<n; i++){ // System.out.println(dp[i][1]); // } System.out.println(Math.max(maxa,maxb)); } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
d2214b28cfa1457a9924bc14daf0c533
train_002.jsonl
1464188700
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader inputReader = new InputReader(System.in); PrintWriter printWriter = new PrintWriter(System.out, true); int n = inputReader.nextInt(); int k = inputReader.nextInt(); char[] s = inputReader.next().toCharArray(); int currentK = 0; int res = 0; for (int r = 0, l = 0; r < n; r++) { if (s[r] == 'a') { res = Math.max(res, r - l + 1); } else if (s[r] == 'b') { if (currentK < k) { currentK++; } else { while (l < n && s[l] != 'b') { l++; } l++; } res = Math.max(res, r - l + 1); } } currentK = 0; for (int r = 0, l = 0; r < n; r++) { if (s[r] == 'b') { res = Math.max(res, r - l + 1); } else if (s[r] == 'a') { if (currentK < k) { currentK++; } else { while (l < n && s[l] != 'a') { l++; } l++; } res = Math.max(res, r - l + 1); } } printWriter.print(res); printWriter.close(); } private static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; ++i) { array[i] = nextInt(); } return array; } public long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; ++i) { array[i] = nextLong(); } return array; } public double[] nextDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; ++i) { array[i] = nextDouble(); } return array; } public String[] nextStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; ++i) { array[i] = next(); } return array; } public boolean[][] nextBooleanTable(int rows, int columns, char trueCharacter) { boolean[][] table = new boolean[rows][columns]; for (int i = 0; i < rows; ++i) { String row = next(); assert row.length() == columns; for (int j = 0; j < columns; ++j) { table[i][j] = (row.charAt(j) == trueCharacter); } } return table; } public char[][] nextCharTable(int rows, int columns) { char[][] table = new char[rows][]; for (int i = 0; i < rows; ++i) { table[i] = next().toCharArray(); assert table[i].length == columns; } return table; } public int[][] nextIntTable(int rows, int columns) { int[][] table = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextInt(); } } return table; } public long[][] nextLongTable(int rows, int columns) { long[][] table = new long[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextLong(); } } return table; } public double[][] nextDoubleTable(int rows, int columns) { double[][] table = new double[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextDouble(); } } return table; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["4 2\nabba", "8 1\naabaabaa"]
1 second
["4", "5"]
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Java 8
standard input
[ "dp", "two pointers", "binary search", "strings" ]
0151a87d0f82a9044a0ac8731d369bb9
The first line of the input contains two integers n and k (1โ€‰โ‰คโ€‰nโ€‰โ‰คโ€‰100โ€‰000,โ€‰0โ€‰โ‰คโ€‰kโ€‰โ‰คโ€‰n)ย โ€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
1,500
Print the only integerย โ€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.
standard output
PASSED
f3b3f8dc8fe49fca006c3015782c7345
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.*; public class main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int cnt = 0; for(int i = 0; i < n; i++) { int a = sc.nextInt(); if(a == 1) { cnt++; } } int z = n - cnt; if(z == cnt) { System.out.println(z); for(int i = 0; i < z; i++) { System.out.print("0 "); } System.out.println(); continue; } if(z > cnt) { z = z % 2 == 0 ? z : z - 1; System.out.println(z); for(int i = 0; i < z; i++) { System.out.print("0 "); } } else { cnt = cnt % 2 == 0 ? cnt : cnt - 1; System.out.println(cnt); for(int i = 0; i < cnt; i++) { System.out.print("1 "); } } System.out.println(); } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
fa49590932c0561267f558dd1398d4a1
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Forces { private static List<Integer> sport(int[] a) { List<Integer> ans = new ArrayList<>(); int n = a.length; for (int i = 0; i < n; i += 4) { if (i + 4 <= n) { int s = a[i] + a[i + 1] + a[i + 2] + a[i + 3]; if (s >= 2) { ans.add(1); ans.add(1); } else { ans.add(0); ans.add(0); } } else { if (a[i] + a[i + 1] == 2) { ans.add(1); ans.add(1); } else { ans.add(0); } } } return ans; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nn = sc.nextInt(); for (int i = 0; i < nn; i++) { int n = sc.nextInt(); int[] a = new int[n]; for (int j = 0; j < n; j++) { a[j] = sc.nextInt(); } List<Integer> sport = sport(a); System.out.println(sport.size()); for (int j = 0; j < sport.size(); j++) { System.out.print(sport.get(j) + " "); } System.out.println(); } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
0a5972355ceb76c7e9a52fbf6c61de6f
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.*; public class A54 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t>0) { int n=s.nextInt(); int a[]=new int[n]; int no=0; int nz=0; for(int i=0;i<n;i++) { a[i]=s.nextInt(); if(a[i]==0) nz++; if(a[i]==1) no++; } int ans[]; if((n/2)%2==0) { ans=new int[n/2]; if(no>nz) { for(int i=0;i<ans.length;i++) ans[i]=1; } else { ans=new int[n/2]; for(int i=0;i<n/2;i++) ans[i]=0; } } else { if(no>nz) { ans=new int[n/2+1]; for(int i=0;i<ans.length;i++) ans[i]=1; } else { ans=new int[n/2]; for(int i=0;i<n/2;i++) ans[i]=0; } } System.out.println(ans.length); for(int i=0;i<ans.length;i++) System.out.print(ans[i]+" "); System.out.println(); t--; } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
e2a7c95e6b6b0a89c71cc93b230d6a39
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.io.*; import java.util.*; 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 { 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 { 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(); } static int counte(ArrayList<Integer> a){ int e=0; for(int i=0;i<a.size();i++){ if(i%2==0){ e+=a.get(i); } } return e; } static int counto(ArrayList<Integer> a){ int e=0; for(int i=0;i<a.size();i++){ if(i%2!=0){ e+=a.get(i); } } return e; } 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> a1=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]; int o=0; int e=0; int one=0; int zero=0; for(int i=0;i<n;i++){ a1.add(nextInt()); if(a1.get(i)==1){ one++; } if(a1.get(i)==0){ zero++; } } int m=n/2; if(zero<m){ for(int i=0;i<a1.size();){ if(a1.get(i)==0){ a1.remove(i); } else{ i++; } } } e=counte(a1); o=counto(a1); while(e!=o){ if(e>o){ for(int i=0;i<a1.size();i++){ if(i%2==0&&a1.get(i)==1){ a1.remove(i); break; } } e=counte(a1); o=counto(a1); } else if(o>e){ for(int i=0;i<a1.size();i++){ if(i%2!=0&&a1.get(i)==1){ a1.remove(i); break; } } e=counte(a1); o=counto(a1); } } writer.println(a1.size()); for(int i=0;i<a1.size();i++){ writer.print(a1.get(i)+" "); } writer.println(); } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
73c7de89f33d15cb6080819c952f365f
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t=in.nextInt(); while(t-->0){ int n=in.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); ArrayList<Integer> del=new ArrayList<>(); for(int i=0;i<n;i+=2){ if(a[i]!=a[i+1]){ if(a[i]==1) del.add(i); else del.add(i+1); } } System.out.println(n-del.size()); int ind=0; for(int i=0;i<n;i++){ if(ind<del.size() && i==del.get(ind)){ ind++; continue; } else System.out.print(a[i]+" "); } System.out.println(); } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
bfe9245a0e83879a2906ac25262b16e5
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int t=sc.nextInt(); for(int i=0;i<t;i++) { show(); } } private static void show() { int n=sc.nextInt(); int zero=0,one=0; for(int i=0;i<n;i++) { if(sc.nextInt()==0)zero++; else one++; } int x=zero>=one?0:1; int s=n/2; if(x==1&&s%2==1) { s+=1; } System.out.println(s); for(int i=0;i<s;i++) { System.out.print(x+" "); } System.out.println(); } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
3d92d2dda0bdfef4a6630214594179cf
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
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(); int zCnt = 0; for (int i = 0; i < n; i++) if (arr[i] == 0) zCnt++; if (zCnt >= n / 2) { o.println(n / 2); for (int i = 0;i < n / 2; i++) { o.print("0 "); } o.println(); } else { int val = n / 2; if (val % 2 == 1) val++; o.println(val); for (int i = 0; i < val; i++) { o.print("1 "); } o.println(); } } o.close(); o.flush(); return; } public static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
a83c86c203e3526e82aeafbb1973485b
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class contest92{ static Scanner scan = new Scanner(System.in); static int t = scan.nextInt(); public static void main(String[] args){ for(int i=0; i<t; i++){ int n = scan.nextInt(); int[] arr = new int[n]; int a = 0; int v; for(int j=0; j<n; j++){ v = scan.nextInt(); arr[j] = v; if(v==1){ a+=1; } } if(a>n/2){ if(n%4==0){ System.out.println(n/2); for(int k=1; k<n/2;k++){ System.out.print("1 "); } System.out.println("1"); }else{ System.out.println(n/2+1); for(int k=1; k<n/2+1;k++){ System.out.print("1 "); } System.out.println("1"); } }else if(a<n/2){ if(n%4==0){ System.out.println(n/2); for(int k=1; k<n/2;k++){ System.out.print("0 "); } System.out.println("0"); }else{ System.out.println(n/2+1); for(int k=1; k<n/2+1;k++){ System.out.print("0 "); } System.out.println("0"); } }else{ System.out.println(n/2); for(int k=1; k<n/2;k++){ System.out.print("0 "); } System.out.println("0"); } } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
68cc48b0928dcf60b5011c512af61e70
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
//package codeforces.contest.ั1407; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /* 8 2 1 0 2 0 0 4 0 1 1 1 4 1 1 0 0 2 1 1 6 1 1 1 1 1 1 4 1 0 1 0 4 1 1 1 1 1 2 1 1 */ public class A { static void solve() { int n = FS.nextInt(); int[] arr = FS.readArray(n); int s0 = 0, s1 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 1) { s1++; } else { s0++; } } if (s1 > s0) { int y = 0; if ((n / 2) % 2 != 0) { FS.pt.println(n / 2 + 1); y = 1; } else { FS.pt.println(n / 2); } for (int i = 0; i < n / 2 + y; i++) { FS.pt.print("1 "); } } else { FS.pt.println(n / 2); for (int i = 0; i < n / 2; i++) { FS.pt.print("0 "); } } FS.pt.println(); } public static void main(String[] args) { int T = FS.nextInt(); for (int tt = 0; tt < T; tt++) { solve(); } FS.pt.close(); } static class FS { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st = new StringTokenizer(""); static PrintWriter pt = new PrintWriter(System.out); static String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } static int[][] read2Array(int m, int n) { int[][] a = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextInt(); } } return a; } static void printArr(int[] arr) { for (int value : arr) { pt.print(value); pt.print(" "); } pt.println(); } static void print2Arr(int[][] arr, int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { pt.print(arr[i][j]); pt.print(" "); } pt.println(); } pt.println(); } static void close() { pt.close(); } static long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
b8b2b8b4a9929ca27cb50bcf705c3e70
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Equal { static class pair implements Comparable<pair> { int v, w; public pair(int v, int w) { this.v = v; this.w = w; } @Override public int compareTo(pair o) { if (v == o.v) return w - o.w; return o.v - v; } } static class tri implements Comparable<tri> { int v, i, j; public tri(int v, int i, int j) { this.v = v; this.i = i; this.j = j; } @Override public int compareTo(tri o) { return v - o.v; } } static ArrayList<Integer>[] tree; static int timer = 0; static int[] timein; static int[] timeout; static int[][] powerParent; static int[] depth; static int[][] minWeight; static void dfs(int u, int parent) { timein[u] = ++timer; // powerParent[u][0] = parent; //// minWeight[u][0] = weight; // if (parent == -1) // powerParent[u][0] = u; // for (int i = 1; i <= 32; i++) { // powerParent[u][i] = powerParent[powerParent[u][i - 1]][i - 1]; // minWeight[u][i] = Math.min(minWeight[u][i - 1], minWeight[powerParent[u][i - 1]][i - 1]); // } for (int i = 0; i < tree[u].size(); i++) { int v = tree[u].get(i); if (v == parent) continue; depth[v] = depth[u] + 1; dfs(v, u); } timeout[u] = timer; } static boolean isAncestor(int u, int v) { return timein[u] <= timein[v] && timeout[v] <= timeout[u]; } static int lca(int u, int v) { if (isAncestor(u, v)) return u; if (isAncestor(v, u)) return v; for (int i = 32; i >= 0; i--) { int temp = powerParent[u][i]; if (!isAncestor(temp, v)) { u = temp; } } return powerParent[u][0]; } static int distance(int u, int v) { return depth[u] + depth[v] - 2 * depth[lca(u, v)]; } static int nthAncestor(int u, int n) { int c = -1; while (n > 0) { c++; if (n % 2 == 0) { n /= 2; continue; } u = powerParent[u][c]; n /= 2; } return u; } static int nthMinWeight(int u, int n) { int c = -1; int min = (int) (1e9); while (n > 0) { c++; if (n % 2 == 0) { n /= 2; continue; } min = Math.min(min, minWeight[u][c]); u = powerParent[u][c]; n /= 2; } return min; } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, lazy; double[] sTree; public SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new double[N << 1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } public void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } public void update_point(int index, double oval, double nval) // O(log n) { index += N - 1; sTree[index] -= oval; sTree[index] += nval; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] + sTree[index << 1 | 1]; } } public void update_range(int i, int j, double oval, double nval) // O(log n) { update_range(1, 1, N, i, j, oval, nval); } public void update_range(int node, int b, int e, int i, int j, double oval, double nval) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] -= oval; sTree[node] += nval; } else { int mid = b + e >> 1; // propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, oval, nval); update_range(node << 1 | 1, mid + 1, e, i, j, oval, nval); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } // public void propagate(int node, int b, int mid, int e) { // lazy[node << 1] += lazy[node]; // lazy[node << 1 | 1] += lazy[node]; // sTree[node << 1] += (mid - b + 1) * lazy[node]; // sTree[node << 1 | 1] += (e - mid) * lazy[node]; // lazy[node] = 0; // } public double query(int i, int j) { return query(1, 1, N, i, j); } public double query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); double q1 = query(node << 1, b, mid, i, j); double q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 + q2; } } public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("name.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(br.readLine()); while (T-- > 0) { int n=Integer.parseInt(br.readLine()); int z=0;int o=0; st=new StringTokenizer(br.readLine()); for (int i = 0; i <n ; i++) { int x=Integer.parseInt(st.nextToken()); if(x==0) z++; else o++; } if(o>n/2){ if(o%2==1){ o--; } z=0; } else { o=0; } int c=o+z; int x=1; out.println(c); for (int i = 0; i <c ; i++) { if(i==o) x=0; out.print(x); if(i<c-1) out.print(" "); else out.println(); } } out.flush(); out.close(); } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
09124c6d7b033723cf327deb540b0f12
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; /** * * @author HP */ public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int testCases = s.nextInt(); while(testCases-- > 0) { int n = s.nextInt(); int arr[] = new int[n]; int count0 = 0, count1 = 0; for(int i = 0; i < n; ++i) { arr[i] = s.nextInt(); if(arr[i] == 0) { count0++; } else { count1++; } } if(count0 >= n / 2) { System.out.println("\n"+count0); for(int i = 0; i < count0; ++i) { System.out.print("0 "); } } else { if(count1 % 2 == 1) { System.out.println("\n"+(count1 - 1)); for(int i = 0; i < count1 - 1; ++i) { System.out.print("1 "); } } else { System.out.println("\n"+count1); for(int i = 0; i < count1; ++i) { System.out.print("1 "); } } } } } }
Java
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output
PASSED
59e9618ee4a6ce888cdbedf33f7e1296
train_002.jsonl
1599575700
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ โ€” length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
256 megabytes
import java.io.*; import java.math.BigInteger; 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(); while(t-->0){ int n = ni(); int arr[] = new int[n]; for(int i=0;i<n;i++)arr[i] = ni(); int a=0,b=0; for(int i=0;i<n;i++){ if(arr[i]==0)a++; else b++; } if(a>=n/2){ System.out.println(n/2); for(int i=0;i<n/2;i++){ System.out.print("0 "); } } else{ a = n/2; if(a%2==1)a++; System.out.println(a); for (int i = 0; i < a; i++) { System.out.print("1 "); } } System.out.println(); } }public long gcd(long a,long 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
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Java 8
standard input
[ "constructive algorithms", "math" ]
eca92beb189c4788e8c4744af1428bc7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even) ย โ€” length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) ย โ€” elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
1,100
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) โ€” number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
standard output