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
7ddc7001004d305f7b76733ce556fd8a
train_003.jsonl
1461515700
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
256 megabytes
import java.io.*; import java.util.*; public class littleartemmatrix { private static InputReader in; private static PrintWriter out; static class Query { public int t,r,c,x; public Query(int t, int r, int c, int x) { this.t = t; this.r = r; this.c = c; this.x = x; } public Query(int t, int r) { this.t = t; this.r = r; } } public static void main(String[] args) throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out, true); int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); Query[] qs= new Query[q]; for (int i = 0; i < q; i++) { int t = in.nextInt(); if (t == 1) { int r = in.nextInt()-1; qs[i] = new Query(t,r); } else if (t == 2) { int r = in.nextInt()-1; qs[i] = new Query(t,r); } else { int r = in.nextInt()-1, c = in.nextInt()-1, x = in.nextInt(); qs[i] = new Query(t,r,c,x); } } int[][] arr = new int[n][m]; for (int i = q-1; i >= 0; i--) { int t = qs[i].t; if (t == 1) { int tmp = arr[qs[i].r][m-1]; for (int j = m-1; j >= 1; j--) { arr[qs[i].r][j] = arr[qs[i].r][j-1]; } arr[qs[i].r][0] = tmp; } else if (t == 2) { int tmp = arr[n-1][qs[i].r]; for (int j = n-1; j >= 1; j--) { arr[j][qs[i].r] = arr[j-1][qs[i].r]; } arr[0][qs[i].r] = tmp; } else { arr[qs[i].r][qs[i].c] = qs[i].x; } } for (int i = 0; i <n; i++) { for (int j = 0; j < m; j++) { if (j != 0) out.print(" "); out.print(arr[i][j]); } out.println(); } out.close(); System.exit(0); } 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
["2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8", "3 3 2\n1 2\n3 2 2 5"]
2 seconds
["8 2 \n1 8", "0 0 0 \n0 0 5 \n0 0 0"]
null
Java 8
standard input
[ "implementation" ]
f710958b96d788a19a1dda436728b9eb
The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000)Β β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m,  - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
1,400
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.
standard output
PASSED
d70382c6bfb28f4c371aaad17fcb56af
train_003.jsonl
1461515700
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.BufferedReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStreamReader; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top * * @author praveen123 */ 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(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] type = new int[q]; int[] row = new int[q]; int[] col = new int[q]; int[] val = new int[q]; for (int i = 0; i < q; i++) { type[i] = in.nextInt(); if (type[i] == 1) { row[i] = in.nextInt(); } else if (type[i] == 2) { col[i] = in.nextInt(); } else { row[i] = in.nextInt(); col[i] = in.nextInt(); val[i] = in.nextInt(); } } int[][] ans = new int[n][m]; for (int it = q - 1; it >= 0; it--) { switch (type[it]) { case 1: rotateRight(ans, row[it] - 1); break; case 2: rotateDown(ans, col[it] - 1); break; case 3: ans[row[it] - 1][col[it] - 1] = val[it]; } } for (int[] a : ans) { for (int x : a) { out.print(x + " "); } out.println(); } } private void rotateDown(int[][] ans, int col) { int n = ans.length; int fir = ans[n - 1][col]; for (int i = n - 1; i >= 1; i--) { ans[i][col] = ans[i - 1][col]; } ans[0][col] = fir; } private void rotateRight(int[][] ans, int row) { int m = ans[row].length; int fir = ans[row][m - 1]; for (int j = m - 1; j >= 1; j--) { ans[row][j] = ans[row][j - 1]; } ans[row][0] = fir; } } 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
["2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8", "3 3 2\n1 2\n3 2 2 5"]
2 seconds
["8 2 \n1 8", "0 0 0 \n0 0 5 \n0 0 0"]
null
Java 8
standard input
[ "implementation" ]
f710958b96d788a19a1dda436728b9eb
The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000)Β β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m,  - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
1,400
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.
standard output
PASSED
95dfcea31600be80feb803991f4017c2
train_003.jsonl
1461515700
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " ,\t"); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } catch (NullPointerException e) { line=null; } } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } double NextDouble() { String n = inputParser.nextToken(); double val = Double.parseDouble(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { //String filePath="circles.in"; String filePath=null; if(argv.length>0)filePath=argv[0]; new A(filePath); } public A(String inputFile) { openInput(inputFile); //readNextLine(); int T=1;//NextInt(); StringBuilder sb = new StringBuilder(); for(int t=1; t<=T; t++) { readNextLine(); int N = NextInt(); int M = NextInt(); int Q = NextInt(); int [] [] p = new int[N][M]; ArrayList<Integer>shifts = new ArrayList<Integer>(); for(int q=0; q<Q; q++) { readNextLine(); int type=NextInt(); switch(type) { case 1: int rs = NextInt()-1; int tmp=p[rs][0]; for(int i=0; i<M-1; i++) p[rs][i] = p[rs][i+1]; p[rs][M-1] = tmp; shifts.add(rs); break; case 2: int cs = NextInt()-1; int tmp2 = p[0][cs]; for(int i=0; i<N-1; i++) p[i][cs] = p[i+1][cs]; p[N-1][cs]=tmp2; shifts.add(cs+1000); break; default: int R = NextInt()-1; int C= NextInt()-1; p[R][C] = NextInt(); break; } } for(int i=shifts.size()-1; i>=0; i--) { int x = shifts.get(i); if(x>500) { x-=1000; int tmp=p[N-1][x]; for(int j=N-1; j>0; j--) p[j][x] = p[j-1][x]; p[0][x] = tmp; } else { int tmp=p[x][M-1]; for(int j=M-1; j>0; j--) p[x][j] = p[x][j-1]; p[x][0] = tmp; } } for(int i=0; i<N; i++) { for(int j=0; j<M; j++) sb.append(p[i][j]+" "); sb.append("\n"); } sb.append("\n"); } System.out.print(sb); closeInput(); } }
Java
["2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8", "3 3 2\n1 2\n3 2 2 5"]
2 seconds
["8 2 \n1 8", "0 0 0 \n0 0 5 \n0 0 0"]
null
Java 8
standard input
[ "implementation" ]
f710958b96d788a19a1dda436728b9eb
The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000)Β β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m,  - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
1,400
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.
standard output
PASSED
c33098fffcabb2ca425c911f4c3861a5
train_003.jsonl
1461515700
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
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.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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int height = in.nextInt(); int width = in.nextInt(); int queries = in.nextInt(); int[] t = new int[queries]; int[] r = new int[queries]; int[] c = new int[queries]; int[] x = new int[queries]; for (int qi = 0; qi < queries; ++qi) { t[qi] = in.nextInt(); switch (t[qi]) { case 1: r[qi] = in.nextInt() - 1; break; case 2: c[qi] = in.nextInt() - 1; break; case 3: r[qi] = in.nextInt() - 1; c[qi] = in.nextInt() - 1; x[qi] = in.nextInt(); break; } } int[][] res = new int[height][width]; for (int qi = 0; qi < queries; ++qi) if (t[qi] == 3) { int cr = r[qi]; int cc = c[qi]; for (int j = qi; j >= 0; --j) { if (t[j] == 1 && r[j] == cr) { cc = (cc + 1) % width; } if (t[j] == 2 && c[j] == cc) { cr = (cr + 1) % height; } } res[cr][cc] = x[qi]; } for (int cr = 0; cr < height; ++cr) { for (int cc = 0; cc < width; ++cc) { int xx = res[cr][cc]; if (cc > 0) out.print(" "); out.print(xx); } out.println(); } } } 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
["2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8", "3 3 2\n1 2\n3 2 2 5"]
2 seconds
["8 2 \n1 8", "0 0 0 \n0 0 5 \n0 0 0"]
null
Java 8
standard input
[ "implementation" ]
f710958b96d788a19a1dda436728b9eb
The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000)Β β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m,  - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
1,400
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.
standard output
PASSED
81848b929ef320838c19ccaf528f72ae
train_003.jsonl
1461515700
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.SynchronousQueue; public class Round348_A { static final long MOD_10e9_PLUS_7 = 1_000_000_007L; // distributive over + - * (NOT /) public static void main(String[] args) throws IOException { FastReader.init(System.in); int n = FastReader.readInt(); int m = FastReader.readInt(); int q = FastReader.readInt(); ArrayList<int[]> operations = new ArrayList<>(q); for (int i = 0 ; i < q ; i++) { int type = FastReader.readInt(); switch(type) { case 1: int row = FastReader.readInt() - 1; operations.add(new int[] {1, row}); break; case 2: int col = FastReader.readInt() - 1; operations.add(new int[] {2, col}); break; case 3: int r = FastReader.readInt() - 1; int c = FastReader.readInt() - 1; int x = FastReader.readInt(); operations.add(new int[] {3, r, c, x}); break; } } // simulate backwards int[][] xs = new int[n][m]; for (int i = operations.size() - 1 ; i >= 0 ; i--) { int[] op = operations.get(i); switch(op[0]) { case 1: rotateInvRow(xs, op[1]); break; case 2: rotateInvCol(xs, op[1]); break; case 3: xs[op[1]][op[2]] = op[3]; break; } } // result for (int r = 0 ; r < n ; r++) { for (int c = 0 ; c < m ; c++) { System.out.printf("%d ", xs[r][c]); } System.out.println(); } } private static void rotateInvRow(int[][] xs, int r) { int cMax = xs[r].length - 1; int tmp = xs[r][cMax]; System.arraycopy(xs[r], 0, xs[r], 1, cMax); xs[r][0] = tmp; } private static void rotateInvCol(int[][] xs, int c) { int rMax = xs.length - 1; int tmp = xs[rMax][c]; for (int i = rMax ; i >= 1 ; i--) { xs[i][c] = xs[i-1][c]; } xs[0][c] = tmp; } // inspired by https://www.cpe.ku.ac.th/~jim/java-io.html static class FastReader { private static BufferedReader reader; private static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String readString() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = reader.readLine(); if (line == null) { throw new IllegalStateException("No more input"); } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(readString()); } static int[] readIntArray(int length) throws IOException { int[] result = new int[length]; for (int i = 0 ; i < length ; i++) { result[i] = readInt(); } return result; } static int[][] readIntMatrix(int rows, int cols) throws IOException { int[][] matrix = new int[rows][]; for (int i = 0 ; i < rows ; i++) { matrix[i] = readIntArray(cols); } return matrix; } static double readDouble() throws IOException { return Double.parseDouble(readString()); } } }
Java
["2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8", "3 3 2\n1 2\n3 2 2 5"]
2 seconds
["8 2 \n1 8", "0 0 0 \n0 0 5 \n0 0 0"]
null
Java 8
standard input
[ "implementation" ]
f710958b96d788a19a1dda436728b9eb
The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000)Β β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m,  - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
1,400
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.
standard output
PASSED
dfd179affab68cfb3c0cd2416f87c90c
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.math.BigInteger; import java.util.*; public class com { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next().trim(); char[] c = s.toCharArray(); long[] a = new long[300]; long res = 0; for(int i = 0; i<c.length; i++) a[c[i]]++; for(int i = 0; i<300; i++) res+= a[i]*a[i]; System.out.println(res); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
3f307dda916a5224c8d40d7350b55ae3
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class Main { public static void main(String[] arg) { FastScanner scan = null; PrintWriter out = null; try{ scan = new FastScanner(new FileInputStream("input.txt")); out = new PrintWriter(new FileOutputStream("output.txt")); }catch(FileNotFoundException e){ scan = new FastScanner(System.in); out = new PrintWriter(System.out); } String in = scan.next(); HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i < in.length(); i++){ if(!m.containsKey(in.charAt(i) - '0')) m.put(in.charAt(i) - '0', 0); m.put(in.charAt(i) - '0', m.get(in.charAt(i) - '0') + 1); } long ret = 0; for(Integer v : m.values()) { ret += (long) v * (long) v; } out.println(ret); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { try { br = new BufferedReader(new InputStreamReader(is)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.valueOf(next()); } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
eb5442754adb1461a1d572fb7a820b42
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public class ChoosingSymbolPairs { public static void main(String[] args) throws IOException { //Locale.setDefault (Locale.US); Reader in = new Reader(); StringBuilder out = new StringBuilder(); int[] letters, digits; String s; long sum; for (int i = 0; i < 1; i++) { s = in.next(); letters = new int[26]; digits = new int[10]; for (int j = 0; j < s.length(); j++) { if(Character.isAlphabetic(s.charAt(j))) letters[s.charAt(j)-'a']++; else digits[s.charAt(j)-'0']++; } sum = 0; for (int j = 0; j < digits.length; j++) sum += digits[j]*1L*digits[j]; for (int j = 0; j < letters.length; j++) sum += letters[j]*1L*letters[j]; System.out.println(sum); } } static class Reader { BufferedReader br; StringTokenizer st; Reader() { // To read from the standard input br = new BufferedReader(new InputStreamReader(System.in)); } Reader(int i) throws IOException { // To read from a file br = new BufferedReader(new FileReader("Sample Input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
cfa48f5ed6c9a9ca7bca1da8a8b423c4
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.Scanner; public class B_50_Choosing_Symbol_Pairs { public static void main(String[] args){ Scanner input=new Scanner(System.in); String s=input.nextLine().trim(); long count=0; int[] alpha=new int[75]; for(int i = 0; i < s.length(); ++i){ char ch = s.charAt(i); int a=ch-48; count=count+alpha[a]*2+1; alpha[a]++; } System.out.println(count); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
f1ccc902e01a583a1451672ff05b438c
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader in =new BufferedReader(new InputStreamReader(System.in)); String main = in.readLine(); int n = main.length(); int[] check = new int[n]; long ans = 0; long count; for(int i=0;i<n;i++){ if(check[i]==0){ count =0; for(int j = i;j<n;j++){ if(main.charAt(i)==main.charAt(j)) { check[j]=1; count+=1; } } ans += count*count; } } System.out.println(ans); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
be42c7999cc2ccf58bd3acce0887cef6
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main { public static void main(String[] args) throws IOException { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); HashMap<Character, Long> d = new HashMap<Character, Long>(); d.put('q', (long)0); d.put('w', (long)0); d.put('e', (long)0); d.put('r', (long)0); d.put('t', (long)0); d.put('y', (long)0); d.put('u', (long)0); d.put('i', (long)0); d.put('o', (long)0); d.put('p', (long)0); d.put('a', (long)0); d.put('s', (long)0); d.put('d', (long)0); d.put('f', (long)0); d.put('g', (long)0); d.put('h', (long)0); d.put('j', (long)0); d.put('k', (long)0); d.put('l', (long)0); d.put('z', (long)0); d.put('x', (long)0); d.put('c', (long)0); d.put('v', (long)0); d.put('b', (long)0); d.put('n', (long)0); d.put('m', (long)0); d.put('0', (long)0); d.put('1', (long)0); d.put('2', (long)0); d.put('3', (long)0); d.put('4', (long)0); d.put('5', (long)0); d.put('6', (long)0); d.put('7', (long)0); d.put('8', (long)0); d.put('9', (long)0); char[] s = b.readLine().toCharArray(); long aux; for (int i = 0; i < s.length; i++) { if (d.containsKey(s[i])) { aux = d.get(s[i]); aux++; d.put(s[i], aux); } } long suma = 0; Iterator it = d.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); aux = (Long)e.getValue(); suma = suma + (long)Math.pow(aux, 2); } System.out.println((long)suma); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
2aa30937f31a8df788551ea749c08480
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); String s = inp.readLine(); Map<Character, Double> map = new HashMap<Character, Double>(); for(int i = 0; i < s.length(); i++){ if(!map.containsKey(s.charAt(i))) map.put(s.charAt(i), (double) 1); else{ double c = map.get(s.charAt(i)); map.put(s.charAt(i), ++c); } } Set<Character> setOfKeys = map.keySet(); Iterator<Character> iter = setOfKeys.iterator(); double sum = 0; while(iter.hasNext()){ char ch = iter.next(); sum += map.get(ch) * map.get(ch); } System.out.println(Math.round(sum)); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
ef9af5042db746a6720f854c28978063
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class A { static int max = 100000; // compare class // static class compare { int a; int b; public compare(int a, int b) { this.a = a; this.b = b; } } // comparator class // static Comparator<compare> cmp = new Comparator<compare>() { public int compare(compare a, compare b) { if (a.a > b.b) return 1; else if (a.a < b.b) return -1; else return 0; } }; static int getSum(long a) { int result = 0; while (a > 0) { result += a % 10; a /= 10; } return result; } static long ipow(long base, long exp) { long result = 1; for (int i = 0; i < exp; i++) result *= base; return result; } public static void main(String[] args) { Scanner s = new Scanner(System.in); String str = s.nextLine(); int[] chr = new int[128]; for (int i = 0; i < str.length(); i++) chr[str.charAt(i)]++; long result = 0; for (int a : chr) result += (ipow(a, 2)); System.out.println(result); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
c0b61f4b3cc9fea9ade0bc5adcf2d4ea
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); HashMap<Character, Long> d = new HashMap<Character, Long>(); d.put('q', (long)0); d.put('w', (long)0); d.put('e', (long)0); d.put('r', (long)0); d.put('t', (long)0); d.put('y', (long)0); d.put('u', (long)0); d.put('i', (long)0); d.put('o', (long)0); d.put('p', (long)0); d.put('a', (long)0); d.put('s', (long)0); d.put('d', (long)0); d.put('f', (long)0); d.put('g', (long)0); d.put('h', (long)0); d.put('j', (long)0); d.put('k', (long)0); d.put('l', (long)0); d.put('z', (long)0); d.put('x', (long)0); d.put('c', (long)0); d.put('v', (long)0); d.put('b', (long)0); d.put('n', (long)0); d.put('m', (long)0); d.put('0', (long)0); d.put('1', (long)0); d.put('2', (long)0); d.put('3', (long)0); d.put('4', (long)0); d.put('5', (long)0); d.put('6', (long)0); d.put('7', (long)0); d.put('8', (long)0); d.put('9', (long)0); char[] s = br.readLine().toCharArray(); long aux; for (int i = 0; i < s.length; i++) { if (d.containsKey(s[i])) { aux = d.get(s[i]); aux++; d.put(s[i], aux); } } long suma = 0; Iterator it = d.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); aux = (Long)e.getValue(); suma = suma + (long)Math.pow(aux, 2); } System.out.println((long)suma); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
cf605ab76624d2307716d88933891c5f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
//package main; import java.util.*; import java.io.*; import java.math.*; public class Main { static StringTokenizer st; static BufferedReader scan; static PrintWriter out; public static void main(String[] args) throws IOException{ // Scanner scanf = new Scanner(new File("input.txt")); //PrintStream outf = new PrintStream(new File("output.txt")); scan = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String s = next(); int[] a = new int[36]; for(int i = 0; i < s.length(); i++){ int x = s.charAt(i) - 97; if(x < 0){ x += 49 + 26; a[x]++; }else{ a[x]++; } } long ans = 0; for(int i = 0; i < 36; i++)ans += ((long)a[i] * (long)a[i]); out.println(ans); scan.close(); out.close(); //scanf.close(); outf.close(); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static String next() throws IOException{ while(st == null || !st.hasMoreTokens()){ st = new StringTokenizer(scan.readLine()); } return st.nextToken(); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
8f0c12def03b772f4ce47f9758a2a4cd
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
//package main; import java.util.*; import java.io.*; import java.math.*; public class Main { static StringTokenizer st; static BufferedReader scan; static PrintWriter out; public static void main(String[] args) throws IOException{ // Scanner scanf = new Scanner(new File("input.txt")); //PrintStream outf = new PrintStream(new File("output.txt")); scan = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String s = next(); long[] a = new long[36]; for(int i = 0; i < s.length(); i++){ int x = s.charAt(i) - 97; if(x < 0){ x += 49 + 26; a[x]++; }else{ a[x]++; } } long ans = 0; for(int i = 0; i < 36; i++)ans += (a[i] * a[i]); out.println(ans); scan.close(); out.close(); //scanf.close(); outf.close(); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static String next() throws IOException{ while(st == null || !st.hasMoreTokens()){ st = new StringTokenizer(scan.readLine()); } return st.nextToken(); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
2576e29d07f95727b197ef0a8f052ed2
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public class j { public static void main(String a[])throws IOException { Scanner b=new Scanner(System.in); int i=0,n=0; double m=0; String s; s=b.next(); double d[]=new double[125]; d[0]=0; n=s.length(); for(i=0;i<n;i++) d[(int)s.charAt(i)]++; for(i=0;i<125;i++) m+=Math.pow(d[i],2); System.out.print((long)m); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
02c592949cee6c19e3c195bde891cc5b
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
/* * @Author: steve * @Date: 2015-03-26 23:57:24 * @Last Modified by: steve * @Last Modified time: 2015-03-27 00:13:53 */ import java.io.*; import java.util.*; public class ChoosingSymbolPairs { public static void main(String[] args) throws Exception{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); String cad=entrada.readLine(); HashMap<Character,Integer> mapa = new HashMap<Character,Integer>(); for(int i=0;i<cad.length();i++){ if(mapa.containsKey(cad.charAt(i))){ mapa.put(cad.charAt(i),mapa.get(cad.charAt(i))+1); }else{ mapa.put(cad.charAt(i),1); } } long cant=0; for(int i=0;i<26;i++){ char aux=(char) (97+i); if(mapa.containsKey(aux)){ cant+=Math.pow(mapa.get(aux),2); } } for(int i=0;i<10;i++){ char aux=(char) ('0'+i); if(mapa.containsKey(aux)){ cant+=Math.pow(mapa.get(aux),2); } } System.out.println(cant); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
e0de5f89110411971b44d5aefb1fcf3f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; public class Tas050B { public static void main(String... args) throws NumberFormatException, IOException { Solution.main(System.in, System.out); } static class Scanner { private final BufferedReader br; private String[] cache; private int cacheIndex; Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); cache = new String[0]; cacheIndex = 0; } int nextInt() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Integer.parseInt(cache[cacheIndex++]); } long nextLong() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Long.parseLong(cache[cacheIndex++]); } double nextDouble() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Double.parseDouble(cache[cacheIndex++]); } String next() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return cache[cacheIndex++]; } void close() throws IOException { br.close(); } } static class Solution { public static void main(InputStream is, OutputStream os) throws NumberFormatException, IOException { PrintWriter pw = new PrintWriter(os); Scanner sc = new Scanner(is); String input = sc.next(); long[] freq = new long[256]; for (char c : input.toCharArray()) { freq[c]++; } long retVal = 0; for (long i : freq) { retVal += i * i; } pw.println(retVal); pw.flush(); sc.close(); } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
8af09fb1c415913fb4cbea7197ef7f3f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { long ans = 0, ret = 0; ArrayList<Character> dif = new ArrayList<Character>(100); HashMap<Character, Integer> map = new HashMap<Character, Integer>( 100); char[] array = line.toCharArray(); for (int i = 0; i < array.length; i++) { if (!map.containsKey(array[i])) { dif.add(array[i]); map.put(array[i], 1); } else map.put(array[i], map.get(array[i]) + 1); } for (int i = 0; i < dif.size(); i++) { ret = map.get(dif.get(i)); ans += (ret * ret); } out.append(ans+"\n"); } System.out.print(out); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
9185338eb2287a5146d3c5f2a085125f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); char alpha[] = s.nextLine().toCharArray(); char arr[] = new char[256]; Map<Character,Integer> map = new HashMap<Character,Integer>(); int c = 0; long res = 0; for (char ch:alpha) { if (map.containsKey(ch)) map.put(ch, map.get(ch) + 1); else { map.put(ch, 1); arr[c] = ch; c++; } }//read data for (int i = 0;i < c;i++) res += (long)Math.pow(map.get(arr[i]), 2); System.out.println(res); }//main }//class
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
2521b6213c2020962c600139fe63384c
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Zyflair Griffane */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; PandaScanner in = new PandaScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); B solver = new B(); solver.solve(1, in, out); out.close(); } } class B { public void solve(int testNumber, PandaScanner in, PrintWriter out) { long[] freq = new long[256]; char[] str = in.next().toCharArray(); for (char c: str) { freq[c]++; } long res = 0; for (int i = 0; i < 256; i++) { res += freq[i] * (freq[i] - 1); res += freq[i]; } out.println(res); } } class PandaScanner { public BufferedReader br; public StringTokenizer st; public InputStream in; public PandaScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } public String next() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); return next(); } return st.nextToken(); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
d4e43875d3da62439b6789056b0aec0f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { // split de array public static int[ ] atoi( String cad ) { String read[] = cad.split( " " ); int res[] = new int[ read.length ]; for ( int i = 0; i < read.length; i++ ) { res[ i ] = Integer.parseInt( read[ i ] ); } return res; } public static void main( String[ ] args ) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); char cad[] = in.readLine( ).toCharArray( ); long arr[] = new long[ 27 ]; long digits[] = new long[ 10 ]; for ( int i = 0; i < cad.length; i++ ) { if ( cad[ i ] >= '0' && cad[ i ] <= '9' ) { digits[ cad[ i ] - '0' ]++; } else { arr[ cad[ i ] - 'a' ]++; } } long sum = 0; for ( int i = 0; i < arr.length; i++ ) { sum += arr[ i ] * arr[ i ]; } for ( int i = 0; i < digits.length; i++ ) { sum += digits[ i ] * digits[ i ]; } System.out.println( sum ); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
818f421a6368e75815e5a1f878ac2641
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public class B50{ public static void main(String args[]){ Scanner in=new Scanner (System.in); String a=in.next(); ArrayList <String> b=new ArrayList<String>(); ArrayList <Long> c=new ArrayList<Long>(); long d=0l; int i,j; for (i=0;i<a.length();i++){ for (j=0;j<b.size();j++){ if ((b.get(j)).equals(String.valueOf(a.charAt(i)))==true){ c.set(j,c.get(j)+1); break; } } if (j==b.size()){ b.add(String.valueOf(a.charAt(i))); c.add((long)1); } } for (i=0;i<c.size();i++){ d=d+c.get(i)*c.get(i); } System.out.println(d); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
dc071637459d2a44bbc4c3af1a605c2c
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.*; import java.io.*; public class cadenasrep{ public static void main(String args[]) throws IOException{ BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String tmp = lector.readLine(); String charset = "abcdefghijklmnopqrstuvwxyz0123456789"; int vec[] = new int[150]; long res = 0; for(int n = 0;n<tmp.length();n++) vec[(int)tmp.charAt(n)]++; for(int n = 0;n<vec.length;n++) res+=(long)vec[n]*vec[n]; System.out.println(res); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
9c2bb6a0a7d1de6f60ce798234b47923
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * * @author Prateep */ public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // TODO code application logic here InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB{ public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{ char[] base=in.next().toCharArray(); Map<Character,Integer> map=new HashMap<>(); long total=0; for(int i=0;i<base.length;i++){ if(!map.containsKey(base[i]))map.put(base[i],1); else map.put(base[i],map.get(base[i])+1); } for(char key:map.keySet()){ long tmp=map.get(key); total+=(tmp*tmp); } out.println(total); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private BufferedReader br; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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 String nextWhole() throws IOException{ br=new BufferedReader(new InputStreamReader(System.in)); return br.readLine(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String nextLine(){ try{ return reader.readLine(); }catch (IOException e){ throw new RuntimeException(e); } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
727744ddef1c0a210f81681334da8c4f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class B50 { private String ip; private Long result = 0L; private HashMap<Character, Long> charMap = new HashMap<>(); public static void main(String[] args) { B50 obj = new B50(); obj.init(); obj.compute(); System.out.println(obj.result); } private void init() { Scanner scn = new Scanner(System.in); ip = scn.nextLine(); } private void compute() { for(int i = 0;i<ip.length();i++) { if(charMap.containsKey(ip.charAt(i))) { charMap.put(ip.charAt(i), charMap.get(ip.charAt(i)) + 1); } else charMap.put(ip.charAt(i), 1L); } for(Long i: charMap.values()) { if(i == 1) result++; else { result = result + (i*i); } } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
42f6c347de32c9a874d521c40d83a392
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.lang.String; public class Hello { public static void main(String[] args){ int[] tab= new int[500]; InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); String s = in.next(); for(int i = 0 ; i <s.length();i++) tab[s.charAt(i)]++; long odp = 0; for(int i = 0 ; i <499;i++) odp=odp+(long)tab[i]*tab[i]; System.out.println(odp); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
62f14af1b7e1537f9770f9b6b5460726
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CodeD { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for(int i = 0; i < n; i++) vals[i] = next(); return vals; } Integer nextInteger() { String s = next(); if(s == null) return null; return Integer.parseInt(s); } int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for(int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } } public static void main(String[] args) { Scanner sc = new Scanner(); long[] suma = new long[256]; for(char c : sc.next().toCharArray()) suma[c]++; long cuenta = 0; for(int i = 0; i < suma.length; i++) cuenta += (suma[i] * suma[i]); System.out.println(cuenta); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
a9f63afbd5880f7f3a7c2fa96d2194dc
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.Scanner; public class B50 { public static void main (String args[]){ Scanner in = new Scanner(System.in); char a[] = in.next().toCharArray(); long ans = 0 ; long t[] = new long[200]; for(int i = 0 ; i < a.length;i++){ t[a[i]]++; } for(int i = 0 ; i < t.length;i++){ ans += t[i]*t[i]; } System.out.println(ans); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
aa35d87bc520a955111634c621bf11dd
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public class ChoosingSymbolPairs { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String str = f.readLine(); long[] a = new long[36]; for (int i = 0; i < str.length(); i++) if (Character.isLetter(str.charAt(i))) a[str.charAt(i)-'a']++; else a[str.charAt(i)-'0'+26]++; long sum = 0; for (int i = 0; i < a.length; i++) sum += a[i]*a[i]; System.out.println(sum); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
6fabebf4724ab84c968471b5a5338843
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map.Entry; import java.util.StringTokenizer; import javax.swing.text.html.HTMLDocument.Iterator; public class B50 { FastScanner in; PrintWriter out; public void solve() throws IOException { String s = in.next(); HashMap<Character, Long> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { if (!map.containsKey(s.charAt(i))) { map.put(s.charAt(i), (long) 1); } else { map.put(s.charAt(i), map.get(s.charAt(i)) + 1); } } java.util.Iterator<Entry<Character, Long>> it = map.entrySet().iterator(); long ans = 0; for (Long value : map.values()) { ans += (value) * (value); } out.println(ans); } public void run() { try { InputStream inputStream = System.in; in = new FastScanner(inputStream); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String line = br.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } if (st != null && st.hasMoreTokens()) { return true; } return false; } public String next() { if (hasNext()) { return st.nextToken(); } return null; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new B50().run(); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
90f429327a5ac35992e401ffed77d57f
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } public static void main(String[] args) throws Exception { String x=next(); long[] count=new long[26+10]; for(int i=0;i<x.length();i++){ if(Character.isDigit(x.charAt(i))){ count[x.charAt(i)-'0'+26]++; }else{ count[x.charAt(i)-'a']++; } } long res=0; for(int i=0;i<count.length;i++){ res+=(count[i]*(count[i])); } System.out.println(res); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
50ae1420d045d9a0952dbfe2de2fedac
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public final class choosing_pairs { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static int[][] bit; static int maxn=100000; static void update(int r,int c) { while(c<=maxn) { bit[r][c]++; c+=c&-c; } } static long query(int r,int c) { long sum=0; while(c>0) { sum+=bit[r][c]; c-=c&-c; } return 2*sum; } public static void main(String args[]) throws Exception { char[] a=sc.next().toCharArray(); bit=new int[123][maxn+1]; long ans=0; for(int i=0;i<a.length;i++) { update((int)a[i],i+1); ans+=query((int)a[i],i); ans++; } out.println(ans); out.close(); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
8ddc583ff85edb6c72e1a2c28ff5af24
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.Scanner; public class B50 { public static void main (String args[]){ Scanner in = new Scanner(System.in); char a[] = in.next().toCharArray(); long ans = 0 ; long t[] = new long[200]; for(int i = 0 ; i < a.length;i++){ t[a[i]]++; } for(int i = 0 ; i < t.length;i++){ ans += t[i]*t[i]; } System.out.println(ans); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
714eb393deb7bb12cf1b0ed7428df549
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long ans = 0; int []digit = new int [10]; int []character = new int [26]; String s = sc.next(); for (int i = 0; i < s.length(); i++) { if ('a' <= s.charAt(i) && s.charAt(i) <='z') character[s.codePointAt(i)-'a']++; else digit[s.codePointAt(i)-48]++; } for (int i = 0; i < character.length; i++) { ans += (long)character[i]*character[i]; } for (int i = 0; i < digit.length; i++) { ans += (long)digit[i]*digit[i]; } System.out.println(ans); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
d4e7905906216b97e624a79decfa758d
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //50_B public class Main { public static void main(String [] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); String s = rd.readLine(); long [] occ = new long[26]; long ans = 0; long [] nums = new long[10]; for(int i = 0; i < s.length(); i++) { if(Character.isLetter(s.charAt(i))) occ[s.charAt(i) - 'a']++; else { nums[Integer.parseInt(s.charAt(i)+"")]++; } } for(int i = 0; i < occ.length; i++) { ans += occ[i] * occ[i]; } for(int i = 0; i < nums.length; i++) { ans += nums[i] * nums[i]; } System.out.println(ans); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
5527d2d1b5aa2d9497f07a33ca13e798
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.StringTokenizer; public class Task { private static final boolean readFromFile = false; public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FileOutputStream fileOutputStream; FileInputStream fileInputStream; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File("input.txt")); fileOutputStream = new FileOutputStream(new File("output.txt")); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in,out); s.solve(); out.close(); } } class Solver{ InputReader in; PrintWriter out; private int getIndOfChar(char c){ if (c>='a' && c<='z') return c-'a'; else return c-'0'+26; } public void solve(){ String s = in.nextLine(); int a[]=new int[111]; for (int i=0;i<s.length();i++) a[getIndOfChar(s.charAt(i))]++; long ans=0; for (int i=0;i<s.length();i++) ans += a[getIndOfChar(s.charAt(i))]; out.println(ans); } Solver(InputReader in, PrintWriter out){ this.in=in; this.out=out; } } class InputReader{ private BufferedReader buf; private StringTokenizer tok; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public float nextFloat(){ return Float.parseFloat(next()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
28c19bab30d78fca4d6f9a503e4e56d4
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.*; public class Main2 { public static void print(Object x) { System.out.println(x + ""); } public static ArrayList<String> readChars(String s) { ArrayList<String> out = new ArrayList<String>(); for (int i = 0; i < s.length(); i++) { out.add(s.substring(i, i+1)); } return out; } public static void solve(String prophecy) { Map<String, Long> occurrences = new HashMap<String, Long>(); for (int i = 0; i < prophecy.length(); i++) { String ch = prophecy.substring(i, i + 1); if (!occurrences.containsKey(ch)) { occurrences.put(ch, (long) 0); } occurrences.put(ch, occurrences.get(ch) + 1); } long total = 0; for (Map.Entry<String, Long> entry : occurrences.entrySet()) { total += entry.getValue()*entry.getValue(); } print(total); } public static void main(String[] args) { Scanner in = new Scanner(System.in); solve(in.next()); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
acef1822ee9e8572d236bb262ca64672
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s = bf.readLine(); long antwort = 0; TreeMap<Character, Long> counts = new TreeMap(); for(int a = 0; a < s.length(); a++) { if(counts.get(s.charAt(a)) == null) counts.put(s.charAt(a), 1L); else counts.put(s.charAt(a), counts.get(s.charAt(a))+1); } for (Map.Entry<Character, Long> entry : counts.entrySet()) { antwort += entry.getValue()*entry.getValue(); } System.out.println(antwort); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
8fcb66c9cb3de63903e0e8d6d6b765fa
train_003.jsonl
1292862000
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≀ i, j ≀ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
256 megabytes
import java.util.Scanner; /** * * @author userx */ public class ChoosingSyymbolPairs { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); char[] x = new char[s.length()]; boolean[] bo = new boolean[s.length()]; for (int i = 0; i < s.length(); i++) { x[i] = s.charAt(i); bo[i] = true; } java.util.Arrays.sort(x); long sum = 0; long cunt = 0; for (int i = 0; i < s.length(); i++) { if (bo[i] == true) { for (int j = 0; j < s.length(); j++) { if (x[i] == x[j]) { cunt++; bo[j] = false; } else { } } sum = sum + cunt *cunt ; cunt = 0 ; } else { } } System.out.println(sum); } }
Java
["great10", "aaaaaaaaaa"]
2 seconds
["7", "100"]
null
Java 7
standard input
[ "strings" ]
6bb2793e275426eb076972fab69d0eba
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
1,500
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
standard output
PASSED
efbdaae9e4042ec94157d3e7a065e966
train_003.jsonl
1559745300
At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * @author Tran Anh Tai * @template for CP codes */ public class ProbA { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++){ int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n]; for (int j = 0; j < n; j++){ a[j] = in.nextInt(); } int start = -1; int dist = Integer.MAX_VALUE; for (int j = 0; j < n - k; j++){ if (dist > a[j + k] - a[j]){ start = j; dist = a[j + k] - a[j]; } } out.println(a[start] + dist / 2); } } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"]
2 seconds
["3\n500000000\n4"]
null
Java 11
standard input
[ "binary search", "greedy", "brute force" ]
87e39e14d6e33427148c284b16a7fb13
The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) β€” number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k &lt; n$$$) β€” the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_n \le 10^9$$$) β€” points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.
1,600
Print $$$T$$$ integers β€” corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.
standard output
PASSED
6ed950d0ee1b994055c85e44909c78da
train_003.jsonl
1559745300
At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class scratch_35 { static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int t= Reader.nextInt(); for (int i = 0; i <t ; i++) { int n= Reader.nextInt(); int k=Reader.nextInt(); int arr[]= new int[n]; for (int j = 0; j <n ; j++) { arr[j]= Reader.nextInt(); } if(k==0){ System.out.println(arr[0]); } else{ int p1=0; int p2=p1+k; int min= Integer.MAX_VALUE; int ans=0; while(p2<n){ if(arr[p2]-arr[p1]<min){ min= arr[p2]-arr[p1]; ans=arr[p1]+min/2; } p1++; p2++; } System.out.println(ans); } } }}
Java
["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"]
2 seconds
["3\n500000000\n4"]
null
Java 11
standard input
[ "binary search", "greedy", "brute force" ]
87e39e14d6e33427148c284b16a7fb13
The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) β€” number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k &lt; n$$$) β€” the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_n \le 10^9$$$) β€” points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.
1,600
Print $$$T$$$ integers β€” corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.
standard output
PASSED
2b4c7798795f8d576412ba4950fd2373
train_003.jsonl
1559745300
At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.
256 megabytes
import java.io.*; import java.util.*; import java.util.logging.Logger; import static java.lang.System.*; public class C1175 { static BufferedReader br; static long mod = 998244353; static HashSet<Integer> p = new HashSet<>(); public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); // System.out.println((rem*i)); int testcCase = 1; testcCase = cinI(); while (testcCase-- > 0) { int[] nk = readArray(2,0,1); int n = nk[0];int k = nk[1]; long[] arr = readArray(n,0); long min = (long) 1e10; int j = 0; for(int i = 0 ;i<n-k;i++){ if(arr[i+k]-arr[i]<min){ min = arr[i+k]-arr[i]; j=i; } } long x1 = arr[j]+ (arr[j+k]-arr[j])/2; System.out.println(x1); } } public static long min(long a,long b) { return Math.min(a,b); } public static int min(int a,int b) { return Math.min(a,b); } public static int[] readArray(int n,int x ,int z)throws Exception{ int[] arr= new int[n]; String[] ar= cinA(); for(int i =x ;i<n+x;i++){ arr[i]=getI(ar[i-x]); } return arr; } public static long[] readArray(int n,int x )throws Exception{ long[] arr= new long[n]; String[] ar= cinA(); for(int i =x ;i<n+x;i++){ arr[i]=getL(ar[i-x]); } return arr; } public static void arrinit(String[] a,long[] b)throws Exception{ for(int i=0;i<a.length;i++){ b[i]=Long.parseLong(a[i]); } } public static HashSet<Integer>[] Graph(int n,int edge,int directed)throws Exception{ HashSet<Integer>[] tree= new HashSet[n]; for(int j=0;j<edge;j++){ String[] uv = cinA(); int u = getI(uv[0]); int v = getI(uv[1]); if(directed==0){ tree[v].add(u); } tree[u].add(v); } return tree; } public static void arrinit(String[] a,int[] b)throws Exception{ for(int i=0;i<a.length;i++){ b[i]=Integer.parseInt(a[i]); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b * b - 4 * a * c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double) (-b + sqrt_val) / (2 * a), (double) (-b - sqrt_val) / (2 * a)); } public static String cin() throws Exception { return br.readLine(); } public static String[] cinA() throws Exception { return br.readLine().split(" "); } public static String[] cinA(int x) throws Exception{ return br.readLine().split(""); } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } public static Integer cinI() throws Exception { return Integer.parseInt(br.readLine()); } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static long max(long a, long b) { return Math.max(a, b); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x) { System.out.println(String.valueOf(x)); } public static void coutI(long x) { System.out.println(String.valueOf(x)); } public static Long cinL() throws Exception { return Long.parseLong(br.readLine()); } public static void arrInit(String[] arr, int[] arr1) throws Exception { for (int i = 0; i < arr.length; i++) { arr1[i] = getI(arr[i]); } } }
Java
["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"]
2 seconds
["3\n500000000\n4"]
null
Java 11
standard input
[ "binary search", "greedy", "brute force" ]
87e39e14d6e33427148c284b16a7fb13
The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) β€” number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k &lt; n$$$) β€” the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_n \le 10^9$$$) β€” points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.
1,600
Print $$$T$$$ integers β€” corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.
standard output
PASSED
87383145c9a5554d26de40dc058cfdbc
train_003.jsonl
1559745300
At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class C { public static void process(int test_number)throws IOException { int n = ni(), k = ni(), arr[] = new int[n + 1]; for(int i = 1; i <= n; i++) arr[i] = ni(); k++; Arrays.sort(arr, 1, n + 1); int res = oo, x = 0; for(int i = 1; i + k - 1 <= n; i++){ int l = arr[i], r = arr[i + k - 1], mid = l + (r - l)/2; int take = Math.max(r - mid, mid - l); if(take < res){ res = take; x = mid; } } pn(x); } static final int oo = 1234567899; static final long mod = (long)1e9+7l; static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc = new FastReader(); long s = System.currentTimeMillis(); int t = 1; t = ni(); for(int i = 1; i <= t; i++) process(i); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); }; static void pn(Object o){ out.println(o); } static void p(Object o){ out.print(o); } static int ni()throws IOException{ return Integer.parseInt(sc.next()); } static long nl()throws IOException{ return Long.parseLong(sc.next()); } static double nd()throws IOException{ return Double.parseDouble(sc.next()); } static String nln()throws IOException{ return sc.nextLine(); } static long gcd(long a, long b)throws IOException{ return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{ return (b==0)?a:gcd(b,a%b); } static int bit(long n)throws IOException{ return (n==0)?0:(1+bit(n&(n-1))); } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"]
2 seconds
["3\n500000000\n4"]
null
Java 11
standard input
[ "binary search", "greedy", "brute force" ]
87e39e14d6e33427148c284b16a7fb13
The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) β€” number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k &lt; n$$$) β€” the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_n \le 10^9$$$) β€” points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.
1,600
Print $$$T$$$ integers β€” corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.
standard output
PASSED
213961bb02bf6f4df1fc60ff2cbf1f31
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class prop { static Scanner sc; static PrintWriter pw; static int n; static char c[][]; static int memo[][]; static boolean valid(int i, int j) { return (i < n && i >= 0 && j >= 0 && j < n); } static boolean dp(int i, int j, boolean f) { if (i == n || j == n) return true; if (memo[i][j] != -1) { return memo[i][j] == 1 ? true : false; } // System.out.println(i+" "+j); if (f) if (c[i][j] == '0') { memo[i][j] = 0; return false; } else { boolean q = dp(i + 1, j, f) || dp(i, j + 1, f); memo[i][j] = (q ? 1 : 0); return q; } else { if (c[i][j] == '0') { boolean q = dp(i + 1, j, f) || dp(i, j + 1, f); memo[i][j] = (q ? 1 : 0); return q; } else { boolean q = dp(i + 1, j, true) || dp(i, j + 1, true); memo[i][j] = (q ? 1 : 0); return q; } } } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); c = new char[n][m]; ArrayList<char[]> a=new ArrayList<>(); a.add(sc.next().toCharArray()); c[0]=a.get(0).clone(); for (int i = 1; i < n; i++) { String s = sc.next(); c[i] = s.toCharArray(); } for (int i = 0; i < m; i++) { char z[]=a.get(0).clone(); for (int j = 0; j < 26; j++) { z[i]=(char) ('a'+j); a.add(z.clone()); } } char ans[]=new char[m]; boolean e=!true; for (char x[] : a) { boolean f = true; for (int i = 0; i < n; i++) { int q = 0; for (int j = 0; j < x.length; j++) { if (c[i][j] != x[j]) q++; } if (q > 1) f = false; } if (f) { ans = x.clone(); e=true; } } if(e) { for(char w:ans ) pw.print(w); pw.println(); } else { pw.println(-1); } } pw.flush(); } static class p { int x, y; p(int s, int d) { x = s; y = d; } } static class pair implements Comparable<pair> { int a[]; int m, s; pair(int[] x, String q) { String r[] = q.split(":"); a = x; m = Integer.parseInt(r[0] + ""); s = Integer.parseInt(r[1] + ""); } @Override public int compareTo(pair o) { if (m == o.m) return s - o.s; return m - o.m; } } ////////////////////////////////////////////////////////////////////////////////////////////////// static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
68d8873cf3dd7abcfdac3c8e2a65a6ac
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Today1 { static void solve() throws IOException { int n = nextInt(), m = nextInt(), temp; if(n == 1) { out.println(nextLine()); return; } String s[] = new String[n]; for(int i = 0; i < n; ++i) s[i] = nextLine(); for(int ind = 0; ind < m; ++ind) { String s1 = s[0].substring(0, ind), s2 = s[0].substring(ind + 1); for(char ch = 'a'; ch <= 'z'; ++ch) { String ss = s1 + ch + s2; // debug(ss); boolean done = true; for(int i = 1; i < n; ++i) { int count = 0; for(int j = 0; j < m; ++j) { if(s[i].charAt(j) != ss.charAt(j)) { ++count; if(count > 1) break; } } if(count > 1) { done = false; break; } } if(done) { out.println(ss); return; } } } out.println(-1); } public static void main(String args[]) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); // sieve(); int tt = nextInt(); // int tt = 1; for(int test = 1; test <= tt; ++test) { // out.print("Case #" + test + ": "); solve(); } out.close(); } // static final int MAXN = 100001; // static int spf[] = new int[MAXN]; // static void sieve() { // spf[1] = 1; // for (int i = 2; i < MAXN; i++) // spf[i] = i; // for (int i = 4; i < MAXN; i += 2) // spf[i] = 2; // for (int i = 3; i * i < MAXN; i++) { // if (spf[i] == i) { // for (int j = i * i; j < MAXN; j += i) // if (spf[j] == j) // spf[j] = i; // } // } // } static final long mod = (long) (1e9 + 7); static final int inf = (int) (1e9 + 1); static class Pair implements Comparable<Pair> { long first, second; Pair(long a, long b) { first = a; second = b; } public int compareTo(Pair p) { return (int) (this.first - p.first); } public boolean equals(Object p) { Pair p1 = (Pair) p; return (first == p1.first && second == p1.second); } public String toString() { return this.first + " " + this.second; } public int hashCode() { return (int) ((1l * (inf + 1) * this.first + this.second) % mod); } } static class Pairc { char c; int freq; Pairc(char cs, int f) { c = cs; freq = f; } } public static int lowerBound(int[] array, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low; } public static int upperBound(int[] array, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value >= array[mid]) { low = mid + 1; } else { high = mid; } } return low; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } static int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } static long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } static int[] memset(int n, int val) { int ar[] = new int[n]; Arrays.fill(ar, val); return ar; } static void debug(Object... a) { System.out.print("> "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } static void debug(int a[]) { debugnsp(Arrays.stream(a).boxed().toArray()); } static void debug(long a[]) { debugnsp(Arrays.stream(a).boxed().toArray()); } static void debugnsp(Object a[]) { System.out.print("> "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } } /* * Jai Sita Ram Ji * * @author: Nishchal Siddharth Pandey */
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
12472ef1449a48938112a2db0d6f0b25
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.math.*; import java.io.*; import java.util.*; import java.awt.*; public class Main implements Runnable { @Override public void run() { try { new Solver().solve(); System.exit(0); } catch (Exception | Error e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { //new Thread(null, new Main(), "Solver", 1l << 25).start(); new Main().run(); } } class Solver { final Helper hp; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; final Timer timer; final TimerTask task; Solver() { hp = new Helper(MOD, MAXN); hp.initIO(System.in, System.out); timer = new Timer(); task = new TimerTask() { @Override public void run() { try { hp.flush(); System.exit(0); } catch (Exception e) { } } }; //timer.schedule(task, 4700); } void solve() throws Exception { int tc = TESTCASES ? hp.nextInt() : 1; for (int tce = 1; tce <= tc; ++tce) solve(tce); timer.cancel(); hp.flush(); } boolean TESTCASES = true; void solve(int tc) throws Exception { int i, j, k; int N = hp.nextInt(), M = hp.nextInt(); String[] A = hp.getStringArray(N); for (i = 0; i < N; ++i) { String s = A[i]; for (j = 0; j < M; ++j) { for (char c = 'a'; c <= 'z'; ++c) { String p = s.substring(0, j) + c + s.substring(j + 1, M); boolean ok = true; for (String itr : A) if (checkDiff(itr, p) > 1) { ok = false; break; } if (ok) { hp.println(p); return; } } } } hp.println(-1); } int checkDiff(String a, String b) { int c = 0; for (int i = 0; i < a.length(); ++i) if (a.charAt(i) != b.charAt(i)) ++c; return c; } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public String[] getStringArray(int size) throws Exception { String[] ar = new String[size]; for (int i = 0; i < size; ++i) ar[i] = next(); return ar; } public String joinElements(long... ar) { StringBuilder sb = new StringBuilder(); for (long itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(int... ar) { StringBuilder sb = new StringBuilder(); for (int itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(String... ar) { StringBuilder sb = new StringBuilder(); for (String itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(Object... ar) { StringBuilder sb = new StringBuilder(); for (Object itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long... ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int... ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static final int BUFSIZE = 1 << 20; static byte[] buf; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); buf = new byte[BUFSIZE]; } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); buf = new byte[BUFSIZE]; } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } public int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
8cd15118e745585766d8f475a11d1b61
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
// package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int q = 0; q < t; q++){ int n = in.nextInt(), m = in.nextInt(); String slov[] = new String[n]; for(int j = 0; j < n; j++){ slov[j] = in.next(); } boolean bool = false; int cnt = 0, cnt2 = 0; String res = "", org = slov[0]; // outer: for(int j = 0; j < m; j++){ // inner: if(bool){ break; } for(int i = 0; i < 26; i++){ // inner2: res = org.substring(0, j) + Character.toString('a' + i) + org.substring(j + 1); // System.out.println(res); cnt2 = 0; for(int k = 0; k < n; k++){ cnt = 0; for(int l = 0; l < m; l++){ if(slov[k].charAt(l) == res.charAt(l)){ cnt++; } } if(cnt >= m - 1){ cnt2++; } } if(cnt2 == n){ bool = true; break; } } } if(bool){ System.out.println(res); }else{ System.out.println("-1"); } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
2c1d7f8a3ea2ca487df51861e5712ade
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1360F extends PrintWriter { CF1360F() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1360F o = new CF1360F(); o.main(); o.flush(); } static final int A = 26; boolean check(byte[] aa, byte[] bb, int m) { int cnt = 0; for (int j = 0; j < m; j++) if (aa[j] != bb[j]) cnt++; return cnt <= 1; } boolean check(byte[][] aa, int n, int m, byte[] bb) { for (int i = 0; i < n; i++) if (!check(aa[i], bb, m)) return false; return true; } void main() { int t = sc.nextInt(); out: while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); byte[][] aa = new byte[n][]; for (int i = 0; i < n; i++) aa[i] = sc.next().getBytes(); byte[] bb = new byte[m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) bb[j] = aa[i][j]; for (int j = 0; j < m; j++) { byte b = bb[j]; for (byte a = 'a'; a <= 'z'; a++) { bb[j] = a; if (check(aa, n, m, bb)) { println(new String(bb)); continue out; } } bb[j] = b; } } println(-1); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
7caa2143d5603106a31912793bb27227
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main{ static long MOD = 1000000007L; static long [] fac; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static long lMax = 0x3f3f3f3f3f3f3f3fL; static int iMax = 0x3f3f3f3f; static HashMap <Long, Long> memo = new HashMap(); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- int t = sc.nextInt(); //int t = 1; while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); HashMap <String, Integer> map = new HashMap<>(); boolean printed = false; for(int i = 0; i < n; i++) { String s = sc.nextLine(); for(String nei : neighbor(s)) map.put(nei, map.getOrDefault(nei, 0) + 1); } for(Map.Entry<String, Integer> entry : map.entrySet()) if(entry.getValue().equals(n)) { out.println(entry.getKey()); printed = true; break; } if(!printed) out.println(-1); } out.close(); } public static HashSet<String> neighbor(String s) { HashSet<String> res = new HashSet(); int m = s.length(); char c[] = s.toCharArray(); for(int i = 0; i < m; i++) { char ori = c[i]; for(char tmp = 'a'; tmp <= 'z'; tmp++) { c[i] = tmp; res.add(new String(c)); } c[i] = ori; } return res; } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long solve(long cur){ return 0L; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
8d58a693683e20b45a123bd065fe9bff
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Spy_String { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); int m = t.nextInt(); String s[] = new String[n]; StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; ++i) s[i] = t.next(); for (int i = 0; i < m; ++i) { for (char ch = 'a'; ch <= 'z'; ++ch) { StringBuilder sb = new StringBuilder(); if (i > 0) sb.append(s[0].substring(0, i)); sb.append(ch); sb.append(s[0].substring(i + 1)); String comp = sb.toString(); boolean f = true; for (int j = 1; j < n; ++j) { int count = 0; for (int k = 0; k < m; ++k) if (comp.charAt(k) != s[j].charAt(k)) count++; if (count > 1) { f = false; break; } } if (f) { ans.append(comp); break; } } if (ans.length() > 0) break; } if (ans.length() > 0) o.println(ans); else o.println("-1"); } o.flush(); o.close(); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
8621f8b4b4481f7c8cc793c7fc038037
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Spy_String { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); int m = t.nextInt(); HashSet<Character>[] set = new HashSet[m]; StringBuilder ans = new StringBuilder(); String[] a = new String[n]; for (int i = 0; i < m; ++i) set[i] = new HashSet<>(); for (int i = 0; i < n; ++i) { a[i] = t.next(); for (int j = 0; j < m; ++j) set[j].add(a[i].charAt(j)); } for (int i = 0; i < m; ++i) { if (set[i].size() == 1) { ans.append(a[0].charAt(i)); } else break; } int id = ans.length(); if (id >= m - 1) { if (id == m) o.println(ans); else { o.print(ans); o.println(a[0].charAt(m - 1)); } } else { boolean f = false; for (int i = 0; i < n; ++i) { HashSet<String> map = new HashSet<>(); String s = ""; char ch = a[i].charAt(id); for (int j = 0; j < n; ++j) { if (a[j].charAt(id) != ch) { map.add(a[j].substring(id + 1)); s = a[j].substring(id + 1); if (map.size() > 1) break; } } if (map.size() == 1) { boolean r = true; for (int j = 0; j < n; ++j) { int count = 0; if (a[j].charAt(id) == ch) { for (int k = id + 1; k < m; ++k) { if (s.charAt(k - id - 1) != a[j].charAt(k)) { count++; } } } if (count >= 2) { r = false; break; } } if (r) { f = true; ans.append(ch); ans.append(s); break; } } if (f) break; } if (f) o.println(ans); else { o.println("-1"); } } } o.flush(); o.close(); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
312fb632b52f4323d5db2567c14f509b
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.* ; import java.lang.Math ; public class Main { public static void main (String [] args){ Scanner in = new Scanner (System.in) ; int t = in.nextInt() ; while (t-- > 0){ int n , m ; n = in.nextInt() ; m = in.nextInt() ; String [] b = new String [n] ; char [][] a = new char [n][m] ; in.nextLine(); for(int i =0 ;i < n ; i++){ b[i] = in.nextLine(); a[i] = b[i].toCharArray(); } Task hi = new Task() ; hi.solve(a , n , m); } } } class Task { void solve (char [][] a , int n , int m){ int found = 0 ; for(int i = 0 ; i < n && found == 0 ; i++){ char [] s = new char[m] ; for(int j = 0 ; j < m && found == 0; j++){ for(int jj = 0 ; jj < m ; jj++)s[jj] = a[i][jj] ; s[j] = '#' ; int fg = 0 , flag = 0; for(int k = 0 ; k < n && fg == 0;k++ ){ int ans = 0 ; for(int l = 0 ; l < m ; l++){ if(s[l] != a[k][l])ans++; } if(ans == 2 && flag == 1)fg = 1 ; if(ans == 2 && flag == 0){ s[j] = a[k][j] ; flag = 1 ; } if(ans > 2)fg = 1; } if(fg == 0){ found = 1 ; if(s[j] == '#')s[j] = 'a' ; } } if(found == 1)System.out.println(s); } if(found == 0)System.out.println(-1); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
550f8f50a69e0453bfc09b8704797927
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; public class Main{ static String func(String[] arr, int k) { String s = arr[0]; for(int i = 0; i < k; i++) { char[] carr = s.toCharArray(); for(int j = 0; j < 26; j++) { carr[i] = (char)('a' + j); boolean go = true; for(String str : arr) { int find = 0; for(int a = 0; a < k; a++) { if(carr[a] != str.charAt(a)) find++; } if(find > 1) { go = false; break; } } if(go) return new StringBuffer().append(carr).toString(); } } return "-1"; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); for(int t = 0; t < tc; t++){ int n = sc.nextInt(), k = sc.nextInt(); String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = sc.next(); String s = func(arr, k); System.out.println(s); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
a7cfd9e2e0787af32036e7d0234b3766
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.Scanner; public class cf1360_Div3_F { public static void main(String args[]) { Scanner in = new Scanner(System.in); int tc = in.nextInt(); for ( ; tc > 0; tc--) { int n = in.nextInt(); int m = in.nextInt(); char[][] grid = new char[n][]; for (int i = 0; i < n; i++) { grid[i] = in.next().toCharArray(); } boolean flag = true; for (int i = 0; i < m; i++) { char prev = grid[0][i]; for (char val = 'a'; val <= 'z'; val++) { flag = true; grid[0][i] = val; for (int j = 1; j < n; j++) { int c = 0; for (int k = 0; k < m; k++) { if (grid[j][k] != grid[0][k]) c++; } if (c > 1) { flag = false; break; } } if (flag) { System.out.println(grid[0]); break; } } if (flag) break; grid[0][i] = prev; } if (!flag) System.out.println(-1); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
f3094d4082b134dd81d1bd8d3e962e86
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static Boolean[][]memo; static int n,m; static char[][]in; static int[][]changes; static boolean dp(int i,int mask) { if(i>=m)return true; if(memo[i][mask]!=null)return memo[i][mask]; boolean ans=false; for(int c=0;c<26;c++) { int changesMsk=changes[i][c]; if((mask&changesMsk)!=0)continue; ans=(ans||dp(i+1, mask|changesMsk)); } return memo[i][mask]=ans; } static StringBuilder ans; static void trace(int i,int mask) { if(i>=m)return; for(int c=0;c<26;c++) { int changesMsk=changes[i][c]; if((mask&changesMsk)!=0)continue; if(dp(i+1, mask|changesMsk)) { char cur=(char)(c+'a'); ans.append(cur); trace(i+1, mask|changesMsk); return; } } } static void main() throws Exception{ n=sc.nextInt();m=sc.nextInt(); in=new char[n][m]; for(int i=0;i<n;i++)in[i]=sc.nextLine().toCharArray(); changes=new int[m][26]; for(int i=0;i<m;i++) { for(int c='a';c<='z';c++) { for(int j=0;j<n;j++) { if(in[j][i]!=c) { changes[i][c-'a']|=(1<<j); } } } } memo=new Boolean[m][1<<n]; if(!dp(0, 0)) { pw.println(-1); return; } ans=new StringBuilder(); trace(0, 0); pw.println(ans); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0)main(); pw.flush(); } static PrintWriter pw; static MScanner sc; 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; } 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 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; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
9a426b66ef78dfec34f8212b96fe8789
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
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.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); FSpyString solver = new FSpyString(); solver.solve(1, in, out); out.close(); } static class FSpyString { int n; int m; char[][] arr; StringBuilder sb; Boolean[][] memo; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = sc.nextInt(); while (q-- > 0) { n = sc.nextInt(); m = sc.nextInt(); arr = new char[n][m]; for (int i = 0; i < n; i++) arr[i] = sc.next().toCharArray(); memo = new Boolean[m][1 << n]; if (dp(0, 0)) { sb = new StringBuilder(); trace(0, 0); pw.println(sb); } else { pw.println(-1); } } } private void trace(int idx, int msk) { if (idx == m) return; for (char i = 'a'; i <= 'z'; i++) { boolean flag = true; int newMsk = msk; for (int j = 0; j < n; j++) { if (arr[j][idx] != i) { if (((msk) & 1 << j) != 0) { flag = false; break; } newMsk |= 1 << j; } } if (flag && dp(idx + 1, newMsk)) { sb.append(i); trace(idx + 1, newMsk); return; } } } private boolean dp(int idx, int msk) { if (idx == m) return true; // if (memo[idx][msk] != null) // return memo[idx][msk]; boolean valid = false; outer: for (char i = 'a'; i <= 'z'; i++) { boolean flag = true; int newMsk = msk; for (int j = 0; j < n; j++) { if (arr[j][idx] != i) { if (((msk) & 1 << j) != 0) { flag = false; break; } newMsk |= 1 << j; } } if (flag) { valid |= dp(idx + 1, newMsk); } } return memo[idx][msk] = valid; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { try { int n = 0; char c; while (Character.isWhitespace(c = (char) br.read())) ; boolean neg = false; if (c == '-') { neg = true; } else { n += c - '0'; } while (Character.isDigit(c = (char) br.read())) { n *= 10; n += c - '0'; } return neg ? -n : n; } catch (Exception e) { throw new RuntimeException(e); } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
16e9e2bc720f631524326f88a618503c
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
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.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); FSpyString solver = new FSpyString(); solver.solve(1, in, out); out.close(); } static class FSpyString { int n; int m; char[][] arr; StringBuilder sb; Boolean[][] memo; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = sc.nextInt(); while (q-- > 0) { n = sc.nextInt(); m = sc.nextInt(); arr = new char[n][m]; for (int i = 0; i < n; i++) arr[i] = sc.next().toCharArray(); memo = new Boolean[m][1 << n]; if (dp(0, 0)) { sb = new StringBuilder(); trace(0, 0); pw.println(sb); } else { pw.println(-1); } } } private void trace(int idx, int msk) { if (idx == m) return; for (char i = 'a'; i <= 'z'; i++) { boolean flag = true; int newMsk = msk; for (int j = 0; j < n; j++) { if (arr[j][idx] != i) { if (((msk) & 1 << j) != 0) { flag = false; break; } newMsk |= 1 << j; } } if (flag && dp(idx + 1, newMsk)) { sb.append(i); trace(idx + 1, newMsk); return; } } } private boolean dp(int idx, int msk) { if (idx == m) return true; if (memo[idx][msk] != null) return memo[idx][msk]; boolean valid = false; outer: for (char i = 'a'; i <= 'z'; i++) { boolean flag = true; int newMsk = msk; for (int j = 0; j < n; j++) { if (arr[j][idx] != i) { if (((msk) & 1 << j) != 0) { flag = false; break; } newMsk |= 1 << j; } } if (flag) { valid |= dp(idx + 1, newMsk); } } return memo[idx][msk] = valid; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { try { int n = 0; char c; while (Character.isWhitespace(c = (char) br.read())) ; boolean neg = false; if (c == '-') { neg = true; } else { n += c - '0'; } while (Character.isDigit(c = (char) br.read())) { n *= 10; n += c - '0'; } return neg ? -n : n; } catch (Exception e) { throw new RuntimeException(e); } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
33000ec43926f2fc6786c7f278e6587c
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { private static boolean chk(char arr[][],char ref[]) { for(int i=0;i<arr.length;i++) { int temp=0; for(int j=0;j<arr[i].length;j++) { temp+=(arr[i][j]!=ref[j])?1:0; } if(temp>1) { return false; } } return true; } public static void main(String[] args) throws IOException { Scan scan=new Scan(); Print print=new Print(); int T=scan.scanInt(); loop: while(T-->0) { int N=scan.scanInt(); int M=scan.scanInt(); char arr[][]=new char[N][M]; for(int i=0;i<N;i++) { arr[i]=scan.scanString().toCharArray(); } char ref[]=new char[M]; for(int i=0;i<M;i++) { ref[i]=arr[0][i]; } if(chk(arr, ref)) { print.println(new String(ref)); continue loop; } for(int i=0;i<M ;i++) { for(char c='a';c<='z';c++) { ref[i]=c; if(chk(arr, ref)) { print.println(new String(ref)); continue loop; } } ref[i]=arr[0][i]; } print.println("-1"); } print.close(); } static class Print { private final BufferedWriter bw; public Print() { this.bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object)throws IOException { bw.append(""+object); } public void println(Object object)throws IOException { print(object); bw.append("\n"); } public void close()throws IOException { bw.close(); } } static class Scan { private byte[] buf=new byte[1024*1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n) || n==' ') { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
498b43f9661e35c7f03deabb4386ea31
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class Main { private 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()); } public double nextDouble() { return Double.parseDouble(next()); } 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; } } private static String dfs(String[] a, String prefix, int i, int m) { if (i == m) return prefix; Set<Character> chars = new HashSet<>(); for (int j = 0; j < a.length; j++) { chars.add(a[j].charAt(i)); } for (char c: chars) { String next = prefix + c; boolean ok = true; for (String ai: a) { int diff = 0; for (int j = 0; j < next.length(); j++) { if (ai.charAt(j) != next.charAt(j)) diff++; if (diff <= 1) continue; ok = false; break; } if (!ok) break; } if (ok) { String result = dfs(a, next, i + 1, m); if (result.length() > 0) { return result; } } } return ""; } public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = sc.next(); String result = dfs(a, "", 0, m); if (result.length() > 0) { System.out.println(result); } else { System.out.println(-1); } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
56ce687e4687b945db8d47a0425c45a4
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static IO io; static StringBuilder solve(String[] arr, int n, int m) { StringBuilder ans = new StringBuilder(arr[0]); for(int i = 0; i < m; i++) { char save = ans.charAt(i); for(char c = 'a'; c <= 'z'; c++) { ans.setCharAt(i, c); boolean flag = true; for(int j = 0; j < n; j++) { int difference = 0; for(int k = 0; k < m; k++) { if(arr[j].charAt(k) != ans.charAt(k)) difference++; } if(difference > 1) { flag = false; break; } } if(flag) return ans; } ans.setCharAt(i, save); } return new StringBuilder("-1"); } public static void main(String[] args) throws IOException { io = new IO(); for(int t = io.nextInt(); t-- > 0;) { int n = io.nextInt(), m = io.nextInt(); String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = io.nextString(); io.println(solve(arr, n, m)); } io.close(); } static class IO { private byte[] buf; private InputStream in; private PrintWriter pw; private int total, index; public IO() { buf = new byte[1024]; in = System.in; pw = new PrintWriter(System.out); } public int next() throws IOException { if(total < 0) throw new InputMismatchException(); if(index >= total) { index = 0; total = in.read(buf); if(total <= 0) return -1; } return buf[index++]; } public int nextInt() throws IOException { int n = next(), integer = 0; while(isWhiteSpace(n)) n = next(); int neg = 1; if(n == '-') { neg = -1; n = next(); } while(!isWhiteSpace(n)) { if(n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = next(); } else throw new InputMismatchException(); } return neg * integer; } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public long nextLong() throws IOException { long integer = 0l; int n = next(); while(isWhiteSpace(n)) n = next(); int neg = 1; if(n == '-') { neg = -1; n = next(); } while(!isWhiteSpace(n)) { if(n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = next(); } else throw new InputMismatchException(); } return neg * integer; } public double nextDouble() throws IOException { double doub = 0; int n = next(); while(isWhiteSpace(n)) n = next(); int neg = 1; if(n == '-') { neg = -1; n = next(); } while(!isWhiteSpace(n) && n != '.') { if(n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = next(); } else throw new InputMismatchException(); } if(n == '.') { n = next(); double temp = 1; while(!isWhiteSpace(n)) { if(n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = next(); } else throw new InputMismatchException(); } } return doub * neg; } public String nextString() throws IOException { StringBuilder sb = new StringBuilder(); int n = next(); while(isWhiteSpace(n)) n = next(); while(!isWhiteSpace(n)) { sb.append((char)n); n = next(); } return sb.toString(); } public String nextLine() throws IOException { int n = next(); while(isWhiteSpace(n)) n = next(); StringBuilder sb = new StringBuilder(); while(!isEndOfLine(n)) { sb.append((char)n); n = next(); } return sb.toString(); } private boolean isWhiteSpace(int n) { return n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1; } private boolean isEndOfLine(int n) { return n == '\n' || n == '\r' || n == -1; } public void print(Object obj) { pw.print(obj); } public void println(Object... obj) { if(obj.length == 1) pw.println(obj[0]); else { for(Object o: obj) pw.print(o + " "); pw.println(); } } public void close() throws IOException { pw.close(); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
930ba7174868e33402481c23e53ea510
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class Solution { static int n,m; static char arr[][]; static boolean check(char ar[]){ for(int i=0;i<n;i++){ int c=0; for(int j=0;j<m;j++){ if(arr[i][j]!=ar[j]) c++; if(c>1) return false; } } return true; } public static void main(String args[]) throws IOException { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int i, j; boolean ok=true; int t=ok?in.nextInt():1; outer: while(t-->0){ n=in.nextInt(); m=in.nextInt(); arr=new char[n][m]; for(i=0;i<n;i++) arr[i]=in.next().toCharArray(); for(j=0;j<m;j++){ HashSet<Character> set=new HashSet<>(); for(i=0;i<n;i++) set.add(arr[i][j]); if(set.size()>1){ outer1: for(char ch:set){ for(i=0;i<n;i++) if(arr[i][j]!=ch){ char ar[]=new char[m]; for(int k=0;k<m;k++) { if(k==j) ar[k]=ch; else ar[k]=arr[i][k]; } if(check(ar)){ for(int k=0;k<m;k++) sb.append(ar[k]); sb.append("\n"); continue outer; } continue outer1; } } sb.append("-1\n"); continue outer; } } for(i=0;i<m;i++) sb.append(arr[0][i]); sb.append("\n"); } System.out.print(sb); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
bd9accb92a584fdc8edbfad83aeaaee6
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict Not sended * @url <https://codeforces.com/problemset/problem/> * @category ? * @date 24/05/2020 **/ import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CFF { static int N, M; static char[][] A; public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = parseInt(in.readLine()); for (int t = 0; t < T; t++) { StringTokenizer st = new StringTokenizer(in.readLine()); N = parseInt(st.nextToken()); M = parseInt(st.nextToken()); A = new char[N][]; mem = new int[M][1 << N][]; for (int i = 0; i < N; i++) A[i] = in.readLine().toCharArray(); if (!f(0, 0)) System.out.println(-1); else { char[] solution = new char[M]; int p = 0, diff = 0; for (; p < M; p++) { solution[p] = (char) (mem[p][diff][1]+'a'); int k = 0; for (int i = 0; i < N; i++) if (A[i][p] - 'a' == mem[p][diff][1]) k |= (1 << i); diff = ((diff | (~k)) & ((1 << N) - 1)); } System.out.println(new String(solution)); } } } static int mem[][][]; static boolean f(int p, int diff) { if (p == M) return true; if (mem[p][diff] != null) return mem[p][diff][0] == 1; int[] arr = new int[26]; for (int i = 0; i < N; i++) arr[A[i][p] - 'a'] |= (1 << i); boolean ws = false; int[] s = new int[]{0, 0}; for (int i = 0; i < arr.length && !ws; i++) if (arr[i] > 0 && (diff & (~arr[i])) == 0) if (f(p + 1, (diff | (~arr[i])) & ((1 << N) - 1))) { ws = true; s[0] = 1; s[1] = i; } mem[p][diff] = s; return ws; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
045b10d0e29a82dabe5ef0bfa4b47b81
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { private static boolean chk(char arr[][],char ref[]) { for(int i=0;i<arr.length;i++) { int temp=0; for(int j=0;j<arr[i].length;j++) { temp+=(arr[i][j]!=ref[j])?1:0; } if(temp>1) { return false; } } return true; } public static void main(String[] args) throws IOException { Scan scan=new Scan(); Print print=new Print(); int T=scan.scanInt(); loop: while(T-->0) { int N=scan.scanInt(); int M=scan.scanInt(); char arr[][]=new char[N][M]; for(int i=0;i<N;i++) { arr[i]=scan.scanString().toCharArray(); } char ref[]=new char[M]; for(int i=0;i<M;i++) { ref[i]=arr[0][i]; } if(chk(arr, ref)) { print.println(new String(ref)); continue loop; } for(int i=0;i<M ;i++) { for(char c='a';c<='z';c++) { ref[i]=c; if(chk(arr, ref)) { print.println(new String(ref)); continue loop; } } ref[i]=arr[0][i]; } print.println("-1"); } print.close(); } static class Print { private final BufferedWriter bw; public Print() { this.bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object)throws IOException { bw.append(""+object); } public void println(Object object)throws IOException { print(object); bw.append("\n"); } public void close()throws IOException { bw.close(); } } static class Scan { private byte[] buf=new byte[1024*1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n) || n==' ') { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
9541b65f589180e87c64df54943921de
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.Scanner; public class Solution2 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); s.nextLine(); for (int i = 0; i < t; i++) { int n = s.nextInt(); int m = s.nextInt(); s.nextLine(); String[] arr = new String[n]; for (int j = 0; j < n; j++) { arr[j] = s.nextLine(); } solver(n, m, arr); } s.close(); } private static void solver(int n, int m, String[] arr) { String result = arr[0]; if (check(result, arr)) { System.out.println(result); return; } for (int index = 0; index < m; index++) { for (char i = 'a'; i <= 'z'; i++) { String test = result.substring(0, index) + i + result.substring(index + 1); if (check(test, arr)) { System.out.println(test); return; } } } System.out.println(-1); return; } private static boolean check(String result, String[] arr) { int n = arr.length; int m = result.length(); for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < m; j++) { if (count > 1) return false; if (arr[i].charAt(j) != result.charAt(j)) { count++; } } if (count > 1) return false; } return true; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
477e4ae20c4743e79a92edc355abdbca
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; public class contest { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int i=0;i<t;i++) { int n=s.nextInt(); int m=s.nextInt(); String[] arr=new String[n]; for(int j=0;j<n;j++) { arr[j]=s.next(); } char[] temp=arr[0].toCharArray(); int p=0; for(int j=0;j<m;j++) { for(int k=0;k<26;k++) { temp[j]=(char)('a'+k); boolean ans=check(temp,arr); if(ans) { p=1; break; } } if(p==1) { break; } else { temp=arr[0].toCharArray(); } } if(p==0) { System.out.println(-1); } else { for(int j=0;j<m;j++) { System.out.print(temp[j]); } System.out.println(); } } } public static boolean check(char[] temp,String[] arr) { for(int i=0;i<arr.length;i++) { int c=0; for(int j=0;j<arr[i].length();j++) { if(arr[i].charAt(j)!=temp[j]) { c++; } } if(c>1) return false; } return true; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
3bc42f232dd3ecddf95513f95cc08a01
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
// Problem: F. Spy-string // Contest: Codeforces - Codeforces Round #644 (Div. 3) // URL: http://codeforces.com/problemset/problem/1360/F // Memory Limit: 256 MB // Time Limit: 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE; static class Pair{ int first, second; Pair(int first, int second){ this.first = first; this.second = second; } } static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ if(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private long nextLong()throws IOException{ next(); return Long.parseLong(tk.nextToken()); } private String readString()throws IOException{ next(); return tk.nextToken(); } private double nextDouble()throws IOException{ next(); return Double.parseDouble(tk.nextToken()); } private int[] intArray(int n)throws IOException{ next(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } private long[] longArray(int n)throws IOException{ next(); long arr[] = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } } public static void main(String args[])throws IOException{ int t = sc.nextInt(); while(t-->0) solve(); pw.flush(); pw.close(); } private static boolean isConnected(String a, String b){ int len = a.length(), count = 0; // System.out.println(a+" "+b); for(int i=0; i<len; i++) count += (a.charAt(i) == b.charAt(i))?0:1; return count <= 1; } private static void solve()throws IOException{ int n = sc.nextInt(), m = sc.nextInt(); String str[] = new String[n]; for(int i=0; i<n; i++) str[i] = sc.readString(); for(int inter=0; inter<m; inter++){ String pre = (inter>0)?str[0].substring(0, inter):""; String post = (inter+1<m)?str[0].substring(inter+1):""; loop:for(int letter=0; letter<26; letter++){ String word = pre + (char)(letter+'a') + post; // System.out.println(word); for(int i=0; i<n; i++){ if(!isConnected(word, str[i])) continue loop; } pw.println(word); return; } } pw.println("-1"); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
33e7d56d34721fd234d1c8e9e499c6d7
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ruins He */ 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); TaskF solver = new TaskF(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskF { private char[][] s; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); s = new char[n][]; for (int i = 0; i < n; i++) { s[i] = in.nextChars(); } for (int i = 0; i < n; i++) { if (valid(s[i])) { out.println(new String(s[i])); return; } for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (s[i][k] != s[j][k]) { char source = s[i][k]; s[i][k] = s[j][k]; if (valid(s[i])) { out.println(new String(s[i])); return; } s[i][k] = source; } } } } out.println(-1); } private boolean valid(char[] now) { for (char[] chars : s) { if (difference(now, chars) > 1) { return false; } } return true; } private int difference(char[] p, char[] s) { int count = 0; for (int i = 0; i < p.length; i++) { if (p[i] != s[i]) { count++; } } return count; } } static class InputReader { public final BufferedReader reader; public StringTokenizer tokenizer = null; public InputReader(Reader reader) { this.reader = new BufferedReader(reader, 32767); } public InputReader(InputStream inputStream) { this(new InputStreamReader(inputStream)); } public String next() { if (hasNext()) return tokenizer.nextToken(); else throw new NoSuchElementException(); } public int nextInt() { return Integer.parseInt(next()); } public char[] nextChars() { return next().toCharArray(); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String nextLine = reader.readLine(); if (nextLine == null) return false; tokenizer = new StringTokenizer(nextLine); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.hasMoreTokens(); } } static class OutputWriter { private final PrintWriter writer; private OutputWriter(Writer writer, boolean autoFlush) { this.writer = new PrintWriter(new BufferedWriter(writer, 32767), autoFlush); } public OutputWriter(Writer writer) { this(writer, true); } public OutputWriter(OutputStream outputStream) { this(new OutputStreamWriter(outputStream), false); } public OutputWriter println(String string) { writer.println(string); return this; } public OutputWriter println(int value) { writer.println(value); return this; } public void close() { writer.close(); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
307ad3d6de7b698b03ab5be93ffef129
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int t = nextInt(); for (int q = 0; q < t; q++) { int n = nextInt(); int m = nextInt(); char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } boolean was = false; char[] ans = a[0]; for (int j = 0; j < m; j++) { char save = ans[j]; if (!was) { for (char d = 'a'; d <= 'z'; d++) { ans[j] = d; boolean flag = true; for (int z = 0; z < n; z++) { int cntErrors = 0; for (int c = 0; c < m; c++) { if (a[z][c] != ans[c]) { cntErrors++; } } if (cntErrors > 1) { flag = false; break; } } if (flag) { for (int i = 0; i < m; i++) { pw.print(ans[i]); was = true; } break; } } ans[j] = save; } } if (!was) pw.print(-1); pw.println(); } pw.close(); } static long mod = (long) 1e9 + 7; static PrintWriter pw; static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; static char[][] a; static char[] ans; static char[] cur_ans; static boolean able; static int m; static int n; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
f81a747a46a2fabc0a6328a81b1d12f6
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
/** * @author vivek */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { private static void solveTC(int __) { /* For Google */ // ans.append("Case #").append(__).append(": "); //code start int n = scn.nextInt(); int m = scn.nextInt(); ArrayList<String> list = new ArrayList<>(); String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = scn.next(); } list.add(array[0]); for (int i = 0; i < m; i++) { for (char ch = 'a'; ch <= 'z'; ch++) { if (ch != array[0].charAt(i)) { list.add(array[0].substring(0, i) + ch + array[0].substring(i + 1)); } } } for(String ele:list){ if (check(ele,array)){ print(ele); print("\n"); return; } } print(-1); //code end print("\n"); } private static boolean check(String ele, String[] array) { for(String second:array){ if (!check(ele,second)){ return false; } } return true; } private static boolean check(String s1,String s2){ int count=0; for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i)!=s2.charAt(i)){ count++; } if (count>1){ return false; } } return true; } public static void main(String[] args) { // int limit= ; // sieve(limit); scn = new Scanner(); ans = new StringBuilder(); int t = scn.nextInt(); // int t = 1; for (int i = 1; i <= t; i++) { solveTC(i); } System.out.print(ans); } //Stuff for prime start /** * List containing prime numbers <br> * <b>i<sup>th</sup></b> position contains <b>i<sup>th</sup></b> prime number <br> * 0th index is <b>null</b> */ private static ArrayList<Integer> listOfPrimes; /** * query <b>i<sup>th</sup></b> element to get if its prime of not */ private static boolean[] isPrime; /** * Performs Sieve of Erathosnesis and initialise isPrime array and listOfPrimes list * * @param limit the number till which sieve is to be performed */ private static void sieve(int limit) { listOfPrimes = new ArrayList<>(); listOfPrimes.add(null); boolean[] array = new boolean[limit + 1]; Arrays.fill(array, true); array[0] = false; array[1] = false; for (int i = 2; i <= limit; i++) { if (array[i]) { for (int j = i * i; j <= limit; j += i) { array[j] = false; } } } isPrime = array; for (int i = 0; i <= limit; i++) { if (array[i]) { listOfPrimes.add(i); } } } //stuff for prime end /** * Calculates the Least Common Multiple of two numbers * * @param a First number * @param b Second Number * @return Least Common Multiple of <b>a</b> and <b>b</b> */ private static long lcm(long a, long b) { return a * b / gcd(a, b); } /** * Calculates the Greatest Common Divisor of two numbers * * @param a First number * @param b Second Number * @return Greatest Common Divisor of <b>a</b> and <b>b</b> */ private static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static void print(Object obj) { ans.append(obj.toString()); } static Scanner scn; static StringBuilder ans; //Fast Scanner static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } Integer[] nextIntegerArray(int n) { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } String[] nextStringArray() { return nextLine().split(" "); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
088040cd168f984baffda923fb4f5735
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class F { static final boolean RUN_TIMING = false; PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok; public void go() throws IOException { // in = new BufferedReader(new FileReader(new File("test.txt"))); // out = new PrintWriter(new FileWriter(new File("output.txt"))); tok = new StringTokenizer(in.readLine()); int zzz = ipar(); for (int zz = 0; zz < zzz; zz++) { ntok(); int n = ipar(); int m = ipar(); String[] arr = new String[n]; for (int i = 0; i < n; i++) { ntok(); arr[i] = spar(); } String ans = null; OUTER: for (String s : arr) { char[] copy = new char[m]; for (int i = 0; i < m; i++) { copy[i] = s.charAt(i); } for (int i = 0; i < m; i++) { for (char c = 'a'; c <= 'z'; c++) { copy[i] = c; boolean works = true; for (String t : arr) { int diff = 0; for (int e = 0; e < m; e++) { if (copy[e] != t.charAt(e)) { diff++; } } if (diff > 1) { works = false; break; } } if (works) { ans = new String(copy); break OUTER; } } copy[i] = s.charAt(i); } } out.println(ans != null ? ans : -1); } out.flush(); in.close(); } public void ntok() throws IOException { tok = new StringTokenizer(in.readLine()); } public int ipar() { return Integer.parseInt(tok.nextToken()); } public int[] iapar(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ipar(); } return arr; } public long lpar() { return Long.parseLong(tok.nextToken()); } public long[] lapar(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = lpar(); } return arr; } public double dpar() { return Double.parseDouble(tok.nextToken()); } public String spar() { return tok.nextToken(); } public static void main(String[] args) throws IOException { long time = 0; time -= System.nanoTime(); new F().go(); time += System.nanoTime(); if (RUN_TIMING) { System.out.printf("%.3f ms%n", time / 1000000.0); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
2f4a969d48d715a6f1e84214b0fc633e
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1360f { public static void main(String[] args) throws IOException { int t = ri(); next: while(t --> 0) { int n = rni(), m = ni(); char a[][] = new char[n][m], ans[] = new char[m]; for(int i = 0; i < n; ++i) { a[i] = rcha(); } for(int i = 0; i < m; ++i) { ans[i] = a[0][i]; } int score = check(ans, a); if(score <= 1) { prln(ans); } else if(score > 2) { prln(-1); } else { int diff = -1; out: for(int j = 0; j < n; ++j) { int p = 0; for(int i = 0; i < m; ++i) { if(ans[i] != a[j][i] && ++p == 2) { diff = j; break out; } } } for(int i = 0; i < m; ++i) { if(ans[i] != a[diff][i]) { char buf = ans[i]; ans[i] = a[diff][i]; if(check(ans, a) <= 1) { prln(ans); continue next; } else { ans[i] = buf; } } } prln(-1); } } close(); } static int check(char[] s, char[][] a) { int ans = 0; for(char[] str : a) { int p = 0; for(int i = 0; i < s.length; ++i) { if(s[i] != str[i]) { ++p; } } ans = max(ans, p); } return ans; } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
24223767f0f566081e3029a2fae97b98
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class SolutionF { static BufferedReader input; static StringTokenizer _stk; static String readln() throws IOException { String l = input.readLine(); if (l != null) _stk = new StringTokenizer(l, " "); return l; } static String next() { return _stk.nextToken(); } static long nextLong() { return Long.parseLong(next()); } static int nextInt() { return Integer.parseInt(next()); } static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } static PrintWriter output = new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); input = new BufferedReader(new InputStreamReader(System.in)); readln(); int t = nextInt(); for (int testI = 0; testI < t; testI++) { readln(); int n = nextInt(); int m = nextInt(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = readln(); } // int[][][] d = new int[m + 1][26][n]; // int prevMin = 0; // for (int i = 1; i <= m; i++) { // for (int j = 0; j < 26; j++) { // for (int k = 0; k < n; k++) { // int add = 1; // if (s[k].charAt(i - 1) == (j + 'a')) { // add = 0; // } // // d[i][j][k] = prevMin + add; // } // } // } // // dbg(d); // boolean ans = false; // for (int j = 0; j < 26 && !ans; j++) { // boolean kAns = true; // for (int i = 0; i < n && kAns; i++) { // if (d[m][j][i] > 1) { // kAns = false; // } // } // // if (kAns) { // ans = true; // } // } // // // if (!ans) { // output.println(-1); // } else { // output.println(1); // } String solve = solve(s, 0, new HashSet<>(), new StringBuilder(m)); if (solve == null) { output.println("-1"); } else { output.println(solve); } } output.close(); } private static String solve(String[] s, int start, Set<Integer> acc, StringBuilder q) { if (start == s[0].length()){ if (acc.size() <= s.length) { return q.toString(); } else { return null; } } Set<Character> visited = new HashSet<>(); for (int i = 0; i < s.length; i++) { char c = s[i].charAt(start); if (!visited.contains(c)) { visited.add(c); boolean canUse = true; for (int j = 0; j < s.length && canUse; j++) { if (s[j].charAt(start) == c) { continue; } if (acc.contains(j)) { canUse = false; } } if (canUse) { for (int j = 0; j < s.length; j++) { if (s[j].charAt(start) == c) { continue; } acc.add(j); } q.append(c); String ans = solve(s, start + 1, acc, q); if (ans != null) { return ans; } q.deleteCharAt(start); for (int j = 0; j < s.length; j++) { if (s[j].charAt(start) == c) { continue; } acc.remove(j); } } } } return null; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
abb65b9505c7dd0faacd4ff761903aa3
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Problem6 { public String findValid(String[] s, List<List<Character>> cs, int n, int m, int index, char[] x) { for (char l : cs.get(index)) { x[index] = l; if (index + 1 == m) { boolean valid = true; for (int i = 0; i < n && valid; i++) { int diff = 0; for (int j = 0; j < m && valid; j++) { if (x[j] != s[i].charAt(j)) { diff++; if (diff > 1) { valid = false; } } } } if (valid) return new String(x); } else { String res = findValid(s, cs, n, m, index + 1, x); if (res != null) return res; } } return null; } public void run(InputStream in) { Scanner sc = new Scanner(in); int t = sc.nextInt(); while (t > 0) { t--; int n = sc.nextInt(); int m = sc.nextInt(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = sc.next(); } List<List<Character>> cc = new ArrayList<>(); for (int j = 0; j < m; j++) { List<Character> posChars = new ArrayList<>(); posChars.add(s[0].charAt(j)); cc.add(posChars); } boolean valid = true; for (int i = 1; i < n && valid; i++) { int news = 0; for (int j = 0; j < m; j++) { char ch = s[i].charAt(j); if(!cc.get(j).contains(ch)) { cc.get(j).add(ch); news++; } } if(news>2) { valid = false; } } String res = null; if(valid) { res = findValid(s, cc, n,m,0,new char[m]); } System.out.println(res==null?"-1":res); } } public static void main(String[] args) { new Problem6().run(System.in); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
25a81367e6074b1524240f3b88827c42
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import static java.lang.Math.*; public class round644_Solution_6 implements Runnable { private boolean console=false; private long MOD = 1000_000_007L; private int MAX = 1000_001; int n,m; char[][] arr; char[] temp; String ans; boolean isOk(char[] temp){ for(int i=0;i<n;++i){ int diff=0; for(int j=0;j<m;++j){ if(arr[i][j]!=temp[j]){ diff++; } } if(diff>1) return false; } return true; } private void solve1(){ n=in.ni(); m=in.ni(); ans = "-1"; arr = new char[n][m]; temp = new char[m]; for(int i=0;i<n;++i){ arr[i] = in.ns().toCharArray(); } for(int i=0;i<n;++i){ for(int j=0;j<m;++j) { char prev =arr[i][j]; for (char ch = 'a'; ch < 'z'; ++ch) { arr[i][j] = ch; if(isOk(arr[i])){ ans = String.valueOf(arr[i]); break; } } arr[i][j] = prev; } } out.println(ans); } class Pair{ int cnt; char ch; public Pair(int cnt, char ch) { this.cnt = cnt; this.ch = ch; } } private void solve() { int testCases = 1; testCases = in.ni(); while (testCases-->0){ solve1(); } } private void add(Map<Character,Integer> map,char key){ map.put(key,map.getOrDefault(key,0)+1); } private void remove(Map<Character,Integer> map,char key){ if(!map.containsKey(key)) return; map.put(key,map.getOrDefault(key,0)-1); if(map.get(key)==0) map.remove(key); } @Override public void run() { long time = System.currentTimeMillis(); try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } try { solve(); out.flush(); System.err.println(System.currentTimeMillis()-time); System.exit(0); }catch (Exception e){ e.printStackTrace(); System.exit(1); } } /* -------------------- Templates and Input Classes -------------------------------*/ private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new round644_Solution_6().run(); // new Thread(null, new round644_Solution_6(), "Main", 1 << 27).start(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (!console && System.getProperty("user.name").equals("puneet")) { outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt"); inputStream = new FileInputStream("/home/puneet/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } private void maualAssert(int a,int b,int c){ if(a<b || a>c) throw new RuntimeException(); } private void maualAssert(long a,long b,long c){ if(a<b || a>c) throw new RuntimeException(); } private void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private long ModPow(long x, long y, long MOD) { long res = 1L; x = x % MOD; while (y >= 1L) { if ((y & 1L) > 0) res = (res * x) % MOD; x = (x * x) % MOD; y >>= 1L; } return res; } private int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } private int[] arrInt(int n){ int[] arr=new int[n];for(int i=0;i<n;++i)arr[i]=in.ni(); return arr; } private long[] arrLong(int n){ long[] arr=new long[n];for(int i=0;i<n;++i)arr[i]=in.nl(); return arr; } static class FastInput { InputStream obj; public FastInput(InputStream obj) { this.obj = obj; } private byte inbuffer[] = new byte[1024]; private int lenbuffer = 0, ptrbuffer = 0; private int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; } 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();} int ni() { int num = 0, b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; }b = readByte(); }} long nl() { long num = 0;int b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10L + (b - '0'); } else { return minus ? -num : num; }b = readByte(); } } private boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; } float nf() {return Float.parseFloat(ns());} double nd() {return Double.parseDouble(ns());} char nc() {return (char) skip();} } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
b670aa58da4c2b8f8e068f43753a124d
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedOutputStream; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); FSpyString solver = new FSpyString(); solver.solve(1, in, out); out.close(); } static class FSpyString { public void solve(int testNumber, LightScanner in, LightWriter out) { int testCases = in.ints(); loop: for (int testCase = 1; testCase <= testCases; testCase++) { int n = in.ints(), m = in.ints(); char[][] s = in.chars(n); char[] t = s[0].clone(); for (int i = 0; i < m; i++) { mid: for (char c = 'a'; c <= 'z'; c++) { t[i] = c; for (int j = 1; j < n; j++) { int d = 0; for (int k = 0; k < m; k++) if (s[j][k] != t[k]) d++; if (d > 1) { t[i] = s[0][i]; continue mid; } } out.ans(String.valueOf(t)).ln(); continue loop; } } out.ans(-1).ln(); } } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset())); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static class LightScanner implements AutoCloseable { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public char[] chars() { return string().toCharArray(); } public char[][] chars(int h) { char[][] res = new char[h][]; for (int i = 0; i < h; i++) res[i] = chars(); return res; } public int ints() { return Integer.parseInt(string()); } public void close() { try { this.reader.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
4d62825ac35b40bd22b6f545e4ba62dd
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
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.Comparator; public class d extends PrintWriter{ static BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); // static Scanner s=new Scanner(System.in); d() { super(System.out); } public static void main(String[] args) throws IOException{ d d1=new d();d1.main();d1.flush(); }char[] op;int[] ii,jj;int cnt; void main() throws IOException { StringBuilder sb = new StringBuilder();PrintWriter out = new PrintWriter(System.out); String[] s=s(); int t=i(s[0]); while(t-->0){hua=0; String[] s2=s(); n=i(s2[0]); m=i(s2[1]); a=new char[n][m]; for(int i=0;i<n;i++){ a[i]=s()[0].toCharArray(); }char[] ans=new char[m]; go(ans,0); if(hua==1){ for(int i=0;i<m;i++) print(fans[i]); println(); }else println(-1); } }int m,n;char[][] a;char[] fans;int hua=0; void go(char[] ans,int i){ if(i==m){int flag=0; for(int j=0;j<n;j++){int count=0; for(int k=0;k<m;k++){ // System.out.println(a[j][k]+" "+ans[k]); if(a[j][k]!=ans[k]){ count++; } }if(count>1){ flag=1;break; } }if(flag==0){hua=1; fans=ans.clone();return; }return; } int f=0; for(int j=0;j<n;j++){int count=0; for(int k=0;k<i;k++){ // System.out.println(a[j][k]+" "+ans[k]); if(a[j][k]!=ans[k]){ count++; } }if(count>1){ f=1;break; } }if(f==0){ for(int j=0;j<n;j++){ ans[i]=a[j][i]; go(ans,i+1);if(hua==1) return;} }else{ return; } if(hua==1) return; } static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); } static int i(String ss) { return Integer.parseInt(ss); } static long l(String ss) { return Long.parseLong(ss); }static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getFactorizationUsingSeive(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); if (spf[x] != 0) x = x / spf[x]; else break; } return ret; } } class Student12 { int l;long r; public Student12(int l, long r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll12 implements Comparator<Student12> { public int compare(Student12 a, Student12 b){ return a.l-b.l; /* if(b.r<a.r) return -1; else if(b.r==a.r) return 0; return 1;*/ // return b.r-a.r; /* if(b.l<a.l) return -1; else if(b.l==a.l) { return b.r-a.r; } return 1;*/ // return b.r- a.r; // return (int) a.l-(int) b.l; /* if(a.r<b.r) return -1; else if(a.r==b.r){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return 1; */} }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
2ce414d4f5de881080a3ea23e4aea368
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int test = GetInput.getInt(); while (test-- > 0) { int[] ins = GetInput.getArrayInt(); String[] strings = new String[ins[0]]; for (int i = 0; i < ins[0]; i++) { strings[i] = GetInput.getInputString().toString(); } Set<String> plaus = new HashSet<>(); Set<String> copy = new HashSet<>(); plaus.add(strings[0]); copy.add(strings[0]); for (int i = 0; i < strings[0].length(); i++) { for (char c = 'a'; c <= 'z'; ++c) { char[] str = strings[0].toCharArray(); str[i] = c; plaus.add(String.valueOf(str)); copy.add(String.valueOf(str)); } } for (int i = 1; i < ins[0]; i++) { Iterator<String> it = plaus.iterator(); while(it.hasNext()){ String stringToCompare = it.next(); int wrongCoung = 0; String str = strings[i]; for (int j = 0; j < ins[1]; j++){ if (str.charAt(j)!=stringToCompare.charAt(j)){ wrongCoung++; } } if (wrongCoung<=1){ continue; } else { copy.remove(stringToCompare); } } } if (copy.size()==0){ System.out.println("-1"); continue; } else { System.out.println(copy.iterator().next()); } } } private static int mod(int b) { if (b<0){ return -b; } return b; } private static long max(int in, int in1) { if (in > in1){ return in; } return in1; } private static long min(long in, long in1) { if (in>in1){ return in1; } return in; } } class GetInput { static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); static char[] getCharArray() { char[] charArray; try { StringBuilder string = getInputString(); charArray = new char[string.length()]; for (int i = 0; i < string.length(); i++) { charArray[i] = string.charAt(i); } return charArray; } catch (Exception e) { e.printStackTrace(); } charArray = new char[0]; return charArray; } static int[] getArrayInt() { String[] string; int[] array; try { string = bufferedReader.readLine().split("\\s+"); array = new int[string.length]; for (int i = 0; i < string.length; i++) { array[i] = Integer.parseInt(string[i]); } return array; } catch (IOException e) { e.printStackTrace(); } int[] arra = new int[2]; return arra; } static int getInt() { try { String string = bufferedReader.readLine(); return Integer.parseInt(string); } catch (IOException e) { e.printStackTrace(); } return 0; } static StringBuilder getInputString() { try { StringBuilder string = new StringBuilder(); string.append(bufferedReader.readLine()); return string; } catch (IOException e) { e.printStackTrace(); } return new StringBuilder(); } static long getLongInput() { try { String string = bufferedReader.readLine(); return Long.parseLong(string); } catch (IOException e) { e.printStackTrace(); } return 0; } static long[] getLongArrayInput() { String[] string; long[] array; try { string = bufferedReader.readLine().split("\\s+"); array = new long[string.length]; for (int i = 0; i < string.length; i++) { array[i] = Long.parseLong(string[i]); } return array; } catch (IOException e) { e.printStackTrace(); } long[] arra = new long[2]; return arra; } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
82739f4d3fbe3a1e159a2a20373e3242
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Reader in = new Reader(); public static void main(String[] args) throws IOException { Main solver = new Main(); solver.solve(); out.flush(); out.close(); } static int INF = (int)1e9; static int maxn = (int)1e5+5; static int mod = 998244353; static int n,m,q,k,t; void solve() throws IOException{ t = in.nextInt(); while (t --> 0) { n = in.nextInt(); m = in.nextInt(); String[] arr = new String[n]; String tmp = ""; for (int i = 0; i < n; i++) { arr[i] = in.next(); } TreeSet<String> set = new TreeSet<>(); TreeSet<String> tmpset = new TreeSet<>(); HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { tmpset = new TreeSet<String>(); for (int j = 0; j < m; j++) { for (int c = 0; c < 26; c++) { tmp = arr[i].substring(0,j)+(char)('a'+c)+arr[i].substring(j+1); if (tmpset.contains(tmp)) continue; else { tmpset.add(tmp); set.add(tmp); map.put(tmp,map.getOrDefault(tmp,0)+1); } } } } String ans = ""; for (String ss:set) { if (map.get(ss) == n) ans = ss; } if (ans =="") out.println(-1); else out.println(ans); } } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
20b5d5772266871179887a37ef457300
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class Main { int n,m; char s[][]; private void solve()throws IOException { n=nextInt(); m=nextInt(); s=new char[n+1][m+1]; for(int i=1;i<=n;i++) { String s1=nextLine(); for(int j=1;j<=m;j++) s[i][j]=s1.charAt(j-1); } char temp[]=new char[m+1]; for(int i=1;i<=m;i++) temp[i]=s[1][i]; for(int i=1;i<=m;i++) for(int j='a';j<='z';j++) { temp[i]=(char)j; boolean flag=true; for(int p=1;p<=n;p++) { int differ=0; for(int q=1;q<=m;q++) if(temp[q]!=s[p][q]) differ++; if(differ>1) { flag=false; break; } } if(flag) { for(int q=1;q<=m;q++) out.print(temp[q]); out.println(); return; } temp[i]=s[1][i]; } out.println("-1"); } /////////////////////////////////////////////////////////// public void run()throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); st=null; out=new PrintWriter(System.out); int t=nextInt(); while(t-->0) solve(); br.close(); out.close(); } public static void main(String args[])throws IOException{ new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken()throws IOException{ while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine()throws IOException{ return br.readLine(); } int nextInt()throws IOException{ return Integer.parseInt(nextToken()); } long nextLong()throws IOException{ return Long.parseLong(nextToken()); } double nextDouble()throws IOException{ return Double.parseDouble(nextToken()); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
018e233f98bd39735aa47ad30adb3ae4
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; public class Main{ static String func(String[] arr, int k) { String s = arr[0]; for(int i = 0; i < k; i++) { char[] carr = s.toCharArray(); for(int j = 0; j < 26; j++) { carr[i] = (char)('a' + j); boolean go = true; for(String str : arr) { int find = 0; for(int a = 0; a < k; a++) { if(carr[a] != str.charAt(a)) find++; } if(find > 1) { go = false; break; } } if(go) return new StringBuffer().append(carr).toString(); } } return "-1"; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); for(int t = 0; t < tc; t++){ int n = sc.nextInt(), k = sc.nextInt(); String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = sc.next(); String s = func(arr, k); System.out.println(s); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
df15f56e8ff2d4eed069b307fec186fb
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
//I AM THE CREED /* package codechef; // don't place package name! */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; //I AM THE CREED /* package codechef; // don't place package name! */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class HelloWorld{ public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); input.nextInt(); while(input.hasNext()){ int n=input.nextInt(); int m=input.nextInt(); String s=input.next(); String[] l=new String[n-1]; for(int i=0;i<n-1;i++){ l[i]=input.next(); } boolean possible=true; StringBuilder sb=new StringBuilder(); for(int j=0;j<m;j++){ for(int letter=0;letter<26;letter++){ possible=true; for(int i=0;i<n-1;i++){ int diff=0; for(int ind=0;ind<m;ind++){ if(j!=ind){ if(s.charAt(ind)!=l[i].charAt(ind)){ diff++; } if(diff>1){ possible=false; } continue; } char temp=(char)('a'+letter); if(temp!=l[i].charAt(ind)){ diff++; } if(diff>1){ possible=false; } } } if(possible){ for(int a=0;a<m;a++){ if(a!=j){ sb.append(s.charAt(a)); continue; } char temp=(char)('a'+letter); sb.append(temp); } break; } } if(possible){ break; } } if(possible){ System.out.println(sb.toString()); continue; } System.out.println(-1); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
5db2cd5d4f07f0ad869e3e6652178e35
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { var sc = new Scanner(System.in); int T = Integer.parseInt(sc.next()); var sb = new StringBuilder(); for(int t = 0; t < T; t++){ int n = Integer.parseInt(sc.next()); int m = Integer.parseInt(sc.next()); var a = new char[n][m]; for(int i = 0; i < n; i++){ a[i] = sc.next().toCharArray(); } StringBuilder ans = new StringBuilder("-1"); label:for(int i = 0; i < m; i++){ for(int j = 0; j < 26; j++){ var c = a[0].clone(); c[i] = (char)('a' + j); boolean flag = true; for(int k = 0; k < n; k++){ int count = 0; for(int l = 0; l < m; l++){ if(c[l] != a[k][l]) count++; } if(count > 1) flag = false; } if(flag){ ans = new StringBuilder(); for(int k = 0; k < m; k++){ ans.append(c[k]); } break label; } } } sb.append(ans).append(System.lineSeparator()); } System.out.print(sb); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
f0e4f49157f82f4cbac4f4852d9076e1
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int t = in.nextInt(); for (int i=0;i<t;i++) { int n = in.nextInt(); int m = in.nextInt(); ArrayList<char[]> list = new ArrayList<char[]>(); ArrayList<char[]> list_all = new ArrayList<char[]>(); for (int j=0;j<n;j++) { char[] a = in.next().toCharArray(); for (int k=0;k<m;k++) { for (int l=0;l<26;l++) { char[] tmp = new char[m]; for (int o=0;o<m;o++) { tmp[o] = a[o]; } tmp[k] = (char)((int)'a'+l); list_all.add(tmp); } } list.add(a); } boolean flag = false; loop:for (int j=0;j<list_all.size();j++) { for (int k=0;k<n;k++) { int diff = 0; for (int l=0;l<m;l++) { if (list_all.get(j)[l] != list.get(k)[l]) diff++; if (diff == 2) continue loop; } } StringBuilder sb = new StringBuilder(); for (int l=0;l<m;l++) { sb.append(list_all.get(j)[l]); } out.println(sb); flag = true; break loop; } if (!flag) out.println(-1); } out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
1806bbe0ca8889a046efff9a5454cdc8
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class F { static class Task { private char[][] grid; private int n; private int m; private boolean isOk(char[] targetArr) { for (int i = 1; i < n; i++) { int diffCount = 0; for (int j = 0; j < m; j++) { if (targetArr[j] != grid[i][j]) { diffCount++; } } if (diffCount > 1) { return false; } } return true; } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); while ((t--) > 0) { n = in.nextInt(); m = in.nextInt(); grid = new char[n][m]; for (int i = 0; i < n; i++) { grid[i] = in.next().toCharArray(); } char[] arr = grid[0]; String ans = "-1"; boolean isFound = false; for (int j = 0; j < m; j++) { char oldChar = arr[j]; for (char c = 'a'; c <= 'z'; c++) { arr[j] = c; if (isOk(arr)) { ans = new String(arr); isFound = true; break; } arr[j] = oldChar; } if (isFound) { break; } } out.println(ans); } } } private static void sort(double[] arr) { Double[] objArr = Arrays.stream(arr).boxed().toArray(Double[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void sort(int[] arr) { Integer[] objArr = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void sort(long[] arr) { Long[] objArr = Arrays.stream(arr).boxed().toArray(Long[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task task = new Task(); task.solve(1, in, out); out.close(); } public static void main(String[] args) { new Thread(null, () -> solve(), "1", 1 << 26).start(); } 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()); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
695aa76b073cadc7c9f827ee51cc60e5
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; //Mann Shah [ DAIICT ]. public class Main { static long mod = (long) (1e9+7); static InputReader in; static PrintWriter out; static Debugger deb; public static int n,m; public static String ans="-1"; public static void recursion(int i, ArrayList<Character> sb, List<HashSet<Character>> a, char[][] s, int[] vis) { if(i==m) { StringBuilder aa = new StringBuilder(); for(int l=0;l<sb.size();l++) { aa.append(sb.get(l)); } ans = aa.toString(); return; } for( char el : a.get(i)) { int pos =0; for(int j=0;j<n;j++) { if(s[j][i] != el && vis[j]==1) { pos =1; } } if(pos==0) { sb.add(el); for(int j=0;j<n;j++) { if(s[j][i] != el) { vis[j]=1; } } recursion(i+1,sb,a,s,vis); sb.remove(sb.size()-1); for(int j=0;j<n;j++) { if(s[j][i] != el && vis[j]==1) { vis[j]=0; } } } else { //out.println(el+" "+i+" "); } } } public static void main(String args[] ) throws NumberFormatException, IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); deb = new Debugger(); int T = in.nextInt(); while(T-->0){ n = in.nextInt(); m = in.nextInt(); char[][] s = new char[n][m]; for(int i=0;i<n;i++) { s[i] = in.readString().toCharArray(); } List<HashSet<Character>> a = new ArrayList(); for(int i=0;i<m;i++) { a.add(new HashSet<Character>()); } for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { a.get(i).add(s[j][i]); } } ArrayList<Character> sb = new ArrayList(); int[] vis = new int[n]; //out.print(a); recursion(0,sb,a,s,vis); out.println(ans); ans = "-1"; } out.close(); } /* TC space */ 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 ArrayList<Integer> nextArrayList(int n){ ArrayList<Integer> x = new ArrayList<Integer>(); for(int i=0;i<n;i++) { int v = in.nextInt(); x.add(v); } return x; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Debugger{ public void n(int x) { out.println(x); } public void a(int[] a) { StringBuilder sb = new StringBuilder(); for(int i=0;i<a.length;i++) { sb.append(a[i]+" "); } out.println(sb.toString()); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
ad8ce42341ab527cc6af3b9a62a0a77c
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; //Mann Shah [ DAIICT ]. public class Main { static long mod = (long) (1e9+7); static InputReader in; static PrintWriter out; static Debugger deb; public static int n,m; public static String ans="-1"; public static void recursion(int i, ArrayList<Character> sb, List<HashSet<Character>> a, char[][] s, int[] vis) { if(i==m) { StringBuilder aa = new StringBuilder(); for(int l=0;l<sb.size();l++) { aa.append(sb.get(l)); } ans = aa.toString(); return; } if(!ans.equals("-1")) { return; } for( char el : a.get(i)) { int pos =0; for(int j=0;j<n;j++) { if(s[j][i] != el && vis[j]==1) { pos =1; } } if(pos==0) { sb.add(el); for(int j=0;j<n;j++) { if(s[j][i] != el) { vis[j]=1; } } recursion(i+1,sb,a,s,vis); sb.remove(sb.size()-1); for(int j=0;j<n;j++) { if(s[j][i] != el && vis[j]==1) { vis[j]=0; } } } } } public static void main(String args[] ) throws NumberFormatException, IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); deb = new Debugger(); int T = in.nextInt(); while(T-->0){ n = in.nextInt(); m = in.nextInt(); char[][] s = new char[n][m]; for(int i=0;i<n;i++) { s[i] = in.readString().toCharArray(); } List<HashSet<Character>> a = new ArrayList(); for(int i=0;i<m;i++) { a.add(new HashSet<Character>()); } for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { a.get(i).add(s[j][i]); } } ArrayList<Character> sb = new ArrayList(); int[] vis = new int[n]; //out.print(a); recursion(0,sb,a,s,vis); out.println(ans); ans = "-1"; } out.close(); } /* TC space */ 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 ArrayList<Integer> nextArrayList(int n){ ArrayList<Integer> x = new ArrayList<Integer>(); for(int i=0;i<n;i++) { int v = in.nextInt(); x.add(v); } return x; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Debugger{ public void n(int x) { out.println(x); } public void a(int[] a) { StringBuilder sb = new StringBuilder(); for(int i=0;i<a.length;i++) { sb.append(a[i]+" "); } out.println(sb.toString()); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
9f9b36a88c8b7b3afda89d58ec535bcf
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { int t = sc.nextInt(); while(t-- > 0) solve(); out.close(); } private static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); String[] strs = new String[n]; for(int i = 0; i < n; i++) strs[i] = sc.next(); Set<Character>[] chs = new HashSet[m]; for(int i = 0; i < m; i++) { Set<Character> set = new HashSet<>(); for(int j = 0; j < n; j++) { set.add(strs[j].charAt(i)); } chs[i] = set; } Set<Integer> indice = new HashSet<>(); for(int i = 0; i < n; i++) indice.add(i); String res = dfs(strs, chs, indice, new StringBuilder(), m); out.println(res.length() == 0 ? -1 : res); } private static String dfs(String[] strs, Set<Character>[] chs, Set<Integer> indice, StringBuilder res, int m) { if(res.length() == m) return res.toString(); int curPos = res.length(); outerloop: for(char c : chs[curPos]) { Set<Integer> used = new HashSet<>(); for(int i = 0; i < strs.length; i++) { if(strs[i].charAt(curPos) == c) continue; if(!indice.contains(i)) continue outerloop; used.add(i); } for(int i : used) indice.remove(i); res.append(c); String r = dfs(strs, chs, indice, res, m); if(r.length() == m) return r; for(int i : used) indice.add(i); res.deleteCharAt(res.length() - 1); } return ""; } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static FastScanner sc = new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
f21ac5c139a14d1ac193e3cb045626dc
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Learning { public static void main(String[] args) throws Exception { FastInput in = new FastInput(); StringBuilder st = new StringBuilder(); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = in.next(); } String ans = solve(n, m, s); st.append(ans).append("\n"); } System.out.println(st.toString()); } private static String solve(int n, int m, String[] s) { char[] ans = s[0].toCharArray(); for (int i = 0; i < m; i++) { char curr = ans[i]; for (char c = 'a'; c <= 'z'; c++) { ans[i] = c; boolean f = true; for (int j = 0; j < n; j++) { if (!compare(String.valueOf(ans), s[j], m)) { f = false; } } if (f) { return String.valueOf(ans); } } ans[i] = curr; } return -1 + ""; } private static boolean compare(String ans, String s, int m) { int l = 0; // System.out.println(ans+" "+s+" "+m) for (int i = 0; i < m; i++) { if (ans.charAt(i) != s.charAt(i)) { l++; } if (l > 1) return false; } return true; } } class FastInput { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } Integer nextInt() throws IOException { return Integer.parseInt(next()); } Long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
4acc35d33ee51338acc12f51f019ee3c
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; 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; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); FSpyString solver = new FSpyString(); solver.solve(1, in, out); out.close(); } static class FSpyString { public void solve(int testNumber, ScanReader in, PrintWriter out) { int t = in.scanInt(); while (t-- > 0) { int n = in.scanInt(); int m = in.scanInt(); char arr[][] = new char[n][m]; for (int i = 0; i < n; i++) { arr[i] = in.scanString().toCharArray(); } boolean dp[][] = new boolean[m + 1][(1 << n)]; dp[0][0] = true; for (int i = 1; i <= m; i++) { for (int j = 0; j < 26; j++) { int c_mask = 0; for (int k = 0; k < n; k++) if (arr[k][i - 1] - 'a' != j) c_mask |= (1 << k); for (int mask = 0; mask < (1 << n); mask++) { if (dp[i - 1][mask] && ((mask & c_mask) == 0)) dp[i][mask | c_mask] |= dp[i - 1][mask]; } } } boolean flag = false; for (int i = 0; i < (1 << n); i++) { flag |= dp[m][i]; } if (flag) { int c_mask = 0; for (int i = 0; i < (1 << n); i++) { if (dp[m][i]) { c_mask = i; break; } } char ans[] = new char[m + 1]; for (int i = m; i >= 1; i--) { int index = -1; for (int j = 0; j < 26; j++) { int this_car = 0; for (int k = 0; k < n; k++) if (arr[k][i - 1] - 'a' != j) this_car |= (1 << k); int temp = -1; for (int mask = 0; mask < (1 << n); mask++) { if (dp[i - 1][mask] && ((this_car | mask) == c_mask) && ((mask & this_car) == 0)) { temp = mask; break; } } if (temp != -1) { index = j; c_mask = temp; break; } } ans[i] = (char) (index + 'a'); } for (int i = 1; i <= m; i++) out.print(ans[i]); out.println(); } else { out.println(-1); } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
4b08cce873df282474eae2e1c9a34de0
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Codechef { PrintWriter out; StringTokenizer st; BufferedReader br; class Pair implements Comparable<Pair> { int f; int s; Pair(int t, int r) { f = t; s = r; } public int compareTo(Pair p) { if(this.f!=p.f) return this.f-p.f; return this.s-p.s; } } // class Sort implements Comparator<String> // { // public int compare(String a, String b) // { // return (a+b).compareTo(b+a); // } // } String ns() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } int nextInt() { return Integer.parseInt(ns()); } long nextLong() { return Long.parseLong(ns()); } double nextDouble() { return Double.parseDouble(ns()); } // int upperBound(long a[],long key) // { // int l=0,r=a.length-1; // int i=a.length-1; // while(l<=r) // { // int mid=(l+r)/2; // if(a[mid]<key) // l=mid+1; // else{ // i=mid; // r=mid-1; // } // } // return i; // } int lowerBound(ArrayList<Integer> a,int key) { int l=0,r=a.size()-1; int i=-1; while(l<=r) { int mid=(l+r)/2; if(a.get(mid)<=key) { i=mid; l=mid+1; } else r=mid-1; } return i; } long power(long x,long y) { long ans=1; while(y!=0) { if(y%2==1) ans=(ans*x)%mod; x=(x*x)%mod; y/=2; } return ans%mod; } long mod= 1000000007; long gcd(long x ,long y) { if(y==0) return x; return gcd(y,x%y); } // ArrayList a[]; // int vis[],cnt=0; // void dfs(int ver) // { // ArrayList<Integer> l=a[ver]; // if(l.size()==1) // cnt++; // for(int v:l) // { // if(vis[v]==0){ // vis[v]=vis[ver]+1; // dfs(v); // } // } // } void solve() throws IOException{ int t=nextInt(); while(t-->0) { int n=nextInt(); int m=nextInt(); char a[][]= new char[n][m]; for(int i=0;i<n;i++) a[i]=ns().toCharArray(); boolean ok=true; char s[]=a[0]; vib: for( int k=0;k<m;k++) { s = a[0].clone(); for(char c='a';c<='z';c++) { s[k]=c; ok=true; for(int i=1;i<n;i++) { int cnt=0; for(int j=0;j<m;j++) { if(s[j]!=a[i][j]) cnt++; } if(cnt>1){ ok=false; break; } } if(ok==true) break vib; } } if(ok) out.println(s); else out.println(-1); } } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); out.close(); } public static void main(String args[]) throws IOException { new Codechef().run(); } } /* int n=nextInt(); long sum=nextLong(); Long a[]= new Long[n]; long pre[]= new long[n+1]; for(int i=0;i<n;i++) a[i]=nextLong(); Arrays.sort(a); for(int i=0;i<n;i++) { if(i==0) pre[i]=a[i]; else pre[i]=pre[i-1]+a[i]; } out.println(Arrays.toString(pre)); long total=pre[0]; long cnd=1; for(int i=1;i<n;i++) { if(a[i]>total) { long t=a[i]-total; out.println(((t-1)/pre[i-1])*pre[i-1]+" hey"); total+=((t-1)/pre[i-1])*pre[i-1]; cnd+=((t-1)/pre[i-1])*i; out.println(total+" "+cnd); t=a[i]-total; int j=upperBound(pre,t); cnd+=j+1; total+=pre[j]; } total+=a[i]; cnd++; out.println(total); } */ /* int n=nextInt(); int k=nextInt(); int a[]= new int[k+1]; ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) a[nextInt()]++; for(int i=0;i<k;i++) list.add(a[i+1]); Collections.sort(list); out.println(list); int l=list.get(list.size()-1),r=l*2; int min=Integer.MAX_VALUE; for(int i=l;i<=r;i++) { int j=lowerBound(list,i-list.get(0)); out.println("lowerBound "+j); if(j==-1) { min=Math.min(min,list.size()*i); out.println(list.size()*i); } else { min=Math.min(min,(list.size()-(j+1)/2)*i); out.println((list.size()-(j+1)/2)*i+" hey"); } } out.println(min); */
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
cffe71dbf6b9509d0d683f40f0859fa0
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; import java.util.List; public class Solution { static int n,m; static String[] s; static HashSet<Character> set[]; static String ans="0"; static char chk[]; public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0){ n=sc.nextInt();m=sc.nextInt(); s=new String[n]; for (int i=0;i<n;i++)s[i]=sc.next(); set=new HashSet[m]; for (int i=0;i<m;i++)set[i]=new HashSet<>(); for (int i=0;i<m;i++){ for (int j=0;j<n;j++){ set[i].add(s[j].charAt(i)); } } boolean ok=true; for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++){ int c=0; for (int k=0;k<m;k++){ if (s[i].charAt(k)!=s[j].charAt(k))c++; } if (c>=3)ok=false; } } if (!ok){ System.out.println(-1); continue; } chk=new char[m]; if (chk(0)){ System.out.println(ans); }else System.out.println(-1); } } static boolean chk(int i){ if (i==m){ for (int j=0;j<n;j++){ int c=0; for (int k=0;k<m;k++){ if (s[j].charAt(k)!=chk[k])c++; } if (c>1)return false; ans=String.valueOf(chk); } return true; } for (Character x:set[i]){ chk[i]=x; if (chk(i+1))return true; } return false; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
63cb8e598383685f7181ce37d1ffc4a5
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; // CODE JAM SHIT public class Q2 { static int diff(String a,String b){ int p=0; for(int i=0;i<a.length();i++){ if(a.charAt(i)!=b.charAt(i)) p++; } return p; } public static void main(String[] args) { InputReader in = new InputReader(true); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int cnt = in.nextInt(), N = in.nextInt(); int flag = 1; String arr[] = new String[cnt]; for (int j = 0; j < cnt; j++) arr[j] = in.next(); String ans=""; for(int i =0;i<N;i++){ for(int j=0;j<26;j++){ flag=1; String temp=arr[0].substring(0,i)+(char)('a'+j)+arr[0].substring(i+1); for(int k=0;k<cnt;k++){ if(diff(temp,arr[k])>1) { flag = 0; } } if(flag==1){ ans=temp; break; } } if(flag==1) break; } if (flag == 1) out.println(ans); else out.println(-1); } out.close(); } // public static void main(String[] args) { // // InputReader in = new InputReader(); // PrintWriter out = new PrintWriter(System.out); // // int t = in.nextInt(), l = 0; // // while (t-- > 0) { // // out.print("Case #" + (++l) + ": "); // // int N = in.nextInt(), x = in.nextInt(), max = 0; // HashMap<Double, Integer> map = new HashMap<>(); // double arr[] = new double[N]; // // for (int i = 0; i < N; i++) { // arr[i] = in.nextDouble(); // map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); // max = Math.max(max, map.get(arr[i])); // } // // if (max >= x) // out.println(0); // else if (x == 2) // out.println(1); // else { // // int flag = 0; // for (int i = 0; i < N; i++) { // if (arr[i] % 2 == 0) { // if (map.containsKey(arr[i] / 2)) // flag = 1; // } // } // // if (N == 1) // out.println(2); // else if (flag == 1) // out.println(1); // else{ // // double min = Integer.MAX_VALUE; // for (int i = 0; i < N; i++) { // if (map.get(arr[i]) == 2) { // min = Math.min(min, arr[i]); // } // } // // if (min < Integer.MAX_VALUE) { // for (int i = 0; i < N; i++) { // if (arr[i] > min) // flag = 1; // } // } // // if (flag == 1 && max!=1) // out.println(1); // else // out.println(2); // } // } // } // out.close(); // // } static class InputReader { InputStream is; public InputReader(boolean onlineJudge) { is = System.in; } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(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); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } void deepFillInt(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillInt(obj, val); } } } void deepFillLong(Object array, long val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] intArray = (long[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFillLong(obj, val); } } } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
b3c54820bc480850afa1c77c52ac07a0
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
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 Main { InputStream is; PrintWriter out; String INPUT = ""; void solve() { outer: for(int T = ni(); T > 0; T--) { int n = ni(), m = ni(); char[][] s = new char[n][]; for(int i = 0; i < n; i++) { s[i] = ns(m); } for(int pos = 0; pos < m; pos++) { char[] ans = Arrays.copyOf(s[0], m); for(char c = 'a'; c <= 'z'; c++) { ans[pos] = c; if(ok(ans, s)) { out.println(new String(ans)); continue outer; } } } out.println("-1"); } } public boolean ok(char[] s, char[][] t) { int m = s.length; int n = t.length; int[] check = new int[n]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(s[j] != t[i][j]) check[i]++; if(check[i] > 1) return false; } } return true; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
98b746fa9a37b342b3de4b2944075f1e
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Six { public static void main (String[] args) throws java.lang.Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int t=Integer.parseInt(br.readLine()); while(t-->0){ String A[]=br.readLine().split(" "); int n,m; n=Integer.parseInt(A[0]); m=Integer.parseInt(A[1]); String str[]=new String[n]; int i,j,k,l,ch; for(i=0;i<n;i++){ str[i]=br.readLine(); } int count=0; boolean flag=false; boolean found=false; String tans=str[0]; char ans[]; for(j=0;j<m;j++) { ans=tans.toCharArray(); for (ch = 1; ch <= 26; ch++) { ans[j]=(char)(ch+96); flag=false; for (k = 1; k < n; k++) { count=0; char temp[]=str[k].toCharArray(); for(l=0;l<m;l++){ if(temp[l]!=ans[l]) count++; if(count>1){ flag=true; break; } } if(count>1){ flag=true; break; } } if(k==n){ bw.write(new String(ans)+"\n"); found=true; break; } } if(found) break; } if(!found){ bw.write("-1\n"); } } bw.flush(); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
ddd18673d95006d9681dd58dbcd35b16
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); int t=sc.nextInt(); StringBuilder sb=new StringBuilder(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); String a[]=new String[n]; for( int i=0;i<n;i++) { a[i]=sc.next(); } boolean check=false; for( int i=0;i<n;i++) { String p=a[i]; for( int j=0;j<m;j++) { char s[]=p.toCharArray(); for( int d=0;d<26;d++ ) { s[j]=(char)('a'+d); //System.out.println(s); int k=0; for( k=0;k<n;k++) { int diff=0; char s1[]=a[k].toCharArray(); for( int l=0;l<m;l++) { if(s[l]!=s1[l]) diff++; } if(diff>1) { break; } } if(k==n) { check=true; sb.append(new String(s)+"\n"); break; } } if(check==true) break; } if(check==true) break; } if(check==false) sb.append("-1\n"); } System.out.println(sb.toString()); } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
2fa814fade206bf1b837c91378e113a1
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.*; import java.util.*; /** * Built using my Brain * Actual solution is at the bottom * * @author Lenard Hoffstader */ public class cfjava { public static void main(String[] args) { OutputStream outputStream = System.out; FastReader in = new FastReader(); PrintWriter out = new PrintWriter(outputStream); PROBLEM solver = new PROBLEM(); int t=1; t=in.nextInt(); for(int i=0;i<t;i++){ solver.solve(in, out); } out.close(); } static class PROBLEM { public void solve(FastReader in,PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); String []str = new String[n]; for(int i=0;i<n;i++){ str[i]=in.nextLine(); } for(int i=0;i<m;i++){ char curr[]=str[0].toCharArray(); for(char ch='a';ch<='z';ch++){ boolean poss = true; curr[i]=ch; for(int j=0;j<n;j++){ int nchange = 0; for(int k=0;k<m;k++){ if(curr[k]!=str[j].charAt(k)){nchange++;} } poss&=(nchange<=1); } if(poss){ for(char x:curr)out.print(x); out.println();return; } } } out.println(-1); } } 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());} boolean nextBoolean(){ if(nextInt()==1)return true; else return false; } // boolean nextBoolean(){return Boolean.parseBoolean(next());} String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e){e.printStackTrace();} return str; } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
5de72bf116f885bd02c44415bbc3c8df
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.util.*; import java.io.*; public class Spystring { // https://codeforces.com/contest/1360/problem/F public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("Spystring")); int t = Integer.parseInt(in.readLine()); for (int j=0; j<t; j++) { StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); String[] arr = new String[n]; for (int i=0; i<n; i++) arr[i] = in.readLine(); String f = arr[0]; ArrayList<String> poss = new ArrayList<>(); boolean works = true; for (int i=1; i<n; i++) { int num_differences = 0; for (int x=0; x<m; x++) { if (f.charAt(x) != arr[i].charAt(x)) num_differences++; } if (num_differences > 2) { works = false; break; } if (num_differences == 2) { for (int x=0; x<m; x++) { if (f.charAt(x) != arr[i].charAt(x)) { poss.add(f.substring(0,x) + arr[i].charAt(x) + f.substring(x+1)); } } break; } } boolean all_work_for_one = false; for (int p=0; p<poss.size(); p++) { boolean this_time = true; for (int i=1; i<n; i++) { int num_differences = 0; for (int x=0; x<m; x++) { if (poss.get(p).charAt(x) != arr[i].charAt(x)) num_differences++; } if (num_differences >= 2) { this_time = false; // no work break; } } if (this_time) { // actually passed all_work_for_one = true; f = poss.get(p); break; } } if (!all_work_for_one && poss.size() > 0) works = false; if (works) { System.out.println(f); } else System.out.println(-1); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output
PASSED
a897eb72438b757a5d41c2ead6a0659b
train_003.jsonl
1590327300
You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
256 megabytes
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author KIIT */ public class ContestDiv3_644 { public static void main(String[] args) throws IOException { // Reader sc = new Reader(); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { // int a = sc.nextInt(); // int b = sc.nextInt(); // if(a == b) // System.out.println((a+b)*(a+b)); // else if(2*b<=a || 2*a <=b) // { // System.out.println(Math.max(a, b)*Math.max(a, b)); // } // else // { // System.out.println(Math.min(2*a, 2*b)*Math.min(2*a,2* b)); // } // int N = sc.nextInt(); // int arr[] = new int[N]; // for(int i =0;i<N;i++) // arr[i] = sc.nextInt(); // Arrays.sort(arr); // int min = Integer.MAX_VALUE; // for(int i = 0;i<N-1;i++) // { // if(arr[i+1]-arr[i] < min) // { // min = arr[i+1] - arr[i]; // } // // } // System.out.println(min); // int N = sc.nextInt(); // int arr[] = new int[N]; // int countEven = 0; // int countOdd = 0; // Set<Integer> even = new HashSet<>(); // Set<Integer> odd = new HashSet<>(); // for (int i = 0; i < N; i++) { // arr[i] = sc.nextInt(); // if(arr[i]%2 == 0){ // even.add(arr[i]); // countEven++; // } // else{ // odd.add(arr[i]); // countOdd++; // } // } // if(countEven%2 == 0 && countOdd%2 == 0) // System.out.println("YES"); // else if((countEven%2==0 && countOdd%2!=0) || (countEven%2!=0 && countOdd%2==0) ) // { // System.out.println("NO"); // } // else // { // boolean b = false; // for(Integer num : even) // { // if(odd.contains(num-1) || odd.contains(num+1)) // { // b = true; // break; // } // } // if(b) // System.out.println("YES"); // else // System.out.println("NO"); // int n = sc.nextInt(); // int k = sc.nextInt(); // if(n<=k) // System.out.println(1); // else // { // int val = Math.min((int)(Math.sqrt(n)),k); // int i; // int min = Integer.MAX_VALUE; // // for(i = 1;i<=val;i++) // { // if(n%i == 0 ) // { // if(n/i <= k) // { // min = i; // break; // } // else // { // min = Math.min(min, n/i); // // } // } // } // System.out.println(min); // } // int n = sc.nextInt(); // char arr[][] = new char[n][n]; // for (int i = 0; i < n; i++) { // String s = sc.readLine(); // for (int j = 0; j < n; j++) { // arr[i][j] = s.charAt(j); // } // } // int i; // a: // for (i = 0; i < n; i++) { // for (int j = 0; j < n; j++) { // if (arr[i][j] == '1') { // if (i + 1 != n && j + 1 != n && arr[i + 1][j] != '1' && arr[i][j + 1] != '1') { // break a; // } // // } // // } // } // if (i < n) { // System.out.println("NO"); // } else { // System.out.println("YES"); // } int n = sc.nextInt(); int m = sc.nextInt(); String arr[] = new String[n]; sc.nextLine(); for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } boolean ans = false; a: for (char i = 'a'; i <= 'z'; i++) { for (int j = 0; j < m; j++) { char check[] = arr[0].toCharArray(); check[j] = i; boolean flag = true; b: for (int k = 0; k < n; k++) { int count = 0; for (int l = 0; l < m; l++) { if (check[l] != arr[k].charAt(l)) { count++; } if (count > 1) { flag = false; break b; } } } if (flag) { ans = true; System.out.println(check); break a; } } } if (!ans) { System.out.println(-1); } } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) { return; } din.close(); } } }
Java
["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"]
2 seconds
["abab\n-1\naaa\nab\nz"]
NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.
Java 11
standard input
[ "dp", "hashing", "constructive algorithms", "bitmasks", "brute force", "strings" ]
8d4cdf75f726b59a8fcc374e1417374a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$)Β β€” the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.
1,700
Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
standard output