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
747c553b8fa44c2d6dffdb6a39f36cdd
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.*; public class C { static int[] dr1 = {0,1}; static int[] dc1 = {1,0}; static int[] dr2 = {0,-1}; static int[] dc2 = {-1,0}; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder ans = new StringBuilder(); for(int tc = 1; tc <= t; ++tc) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] arr = new int[n][m]; for(int i = 0; i < n; ++i) { st = new StringTokenizer(br.readLine()); for(int j = 0; j < m; ++j) { arr[i][j] = Integer.parseInt(st.nextToken()); } } int totalCount = 0; ArrayList<ArrayList<Integer>> arrTop = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> arrBottom = new ArrayList<ArrayList<Integer>>(); int[] crc1 = {0,0}; int[] crc2 = {n-1,m-1}; Queue<int[]> q = new LinkedList<int[]>(); q.add(crc1); arrTop.add(new ArrayList<>()); arrTop.get(0).add(arr[crc1[0]][crc1[1]]); boolean[][] visited = new boolean[n][m]; while(!q.isEmpty()) { int size = q.size(); arrTop.add(new ArrayList<>()); for(int i = 0; i < size; ++i) { crc1 = q.poll(); // System.out.println(arr[crc1[0]][crc1[1]]); for(int j = 0; j < 2; ++j) { int nr = crc1[0] + dr1[j]; int nc = crc1[1] + dc1[j]; if(bdCheck(nr,nc,n,m) && !visited[nr][nc]) { visited[nr][nc] = true; arrTop.get(arrTop.size()-1).add(arr[nr][nc]); q.add(new int[] {nr,nc}); } } } } // for(int i = 0; i < arrTop.size()/2; ++i) { // System.out.println(arrTop.get(i)); // } q = new LinkedList<int[]>(); q.add(crc2); arrBottom.add(new ArrayList<>()); arrBottom.get(0).add(arr[crc2[0]][crc2[1]]); visited = new boolean[n][m]; while(!q.isEmpty()) { int size = q.size(); arrBottom.add(new ArrayList<>()); for(int i = 0; i < size; ++i) { crc2 = q.poll(); for(int j = 0; j < 2; ++j) { int nr = crc2[0] + dr2[j]; int nc = crc2[1] + dc2[j]; if(bdCheck(nr,nc,n,m) && !visited[nr][nc]) { visited[nr][nc] = true; arrBottom.get(arrBottom.size()-1).add(arr[nr][nc]); q.add(new int[] {nr,nc}); } } } } // System.out.println("사이즈 "+arrTop.size()); int size = (arrTop.size()-1)/2; for(int i = 0; i < size; ++i) { int topOneCount = 0; int topZeroCount = 0; int bottomOneCount = 0; int bottomZeroCount = 0; for(int j = 0; j < arrTop.get(i).size(); ++j) { if(arrTop.get(i).get(j) == 0) { topZeroCount++; }else { topOneCount++; } if(arrBottom.get(i).get(j) == 0) { bottomZeroCount++; }else { bottomOneCount++; } } int min = Math.min(topOneCount+bottomOneCount, topZeroCount+bottomZeroCount); totalCount += min; } ans.append(totalCount).append('\n'); } System.out.println(ans); } static boolean bdCheck(int r, int c, int n, int m) { return r >= 0 && r < n && c >= 0 && c < m; } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
383b6d4cebdee89839861430669f7b60
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.util.*; import java.io.*; public class C{ private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main (String[] args) throws java.lang.Exception { int t = Integer.parseInt(br.readLine()); while(t-- > 0){ StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int a[][] = new int[n][m]; for(int i=0;i<n;i++){ st = new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j] = Integer.parseInt(st.nextToken()); } } int moves = 0; if(m>=n){ for(int i=0;i<(n+m)/2;i++){ if((n+m)%2==0){ if(i==(n+m)/2 -1) break; } int o = 0, z = 0; int j = i, k = 0; while(j>=0 && k<n){ if(a[k][j]==1){ o++; }else{ z++; } if(a[n-k-1][m-1-j]==1){ o++; }else{ z++; } j--; k++; } if(o>z){ moves += z; }else{ moves += o; } } }else{ for(int i=0;i<(n+m)/2;i++){ if((n+m)%2==0){ if(i==(n+m)/2 -1) break; } int o = 0, z = 0; int j = 0, k = i; while(j<m && k>=0){ if(a[k][j]==1){ o++; }else{ z++; } if(a[n-k-1][m-1-j]==1){ o++; }else{ z++; } j++; k--; } if(o>z){ moves += z; }else{ moves += o; } } } bw.write(moves + ""); bw.newLine(); } bw.flush(); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
7f25cb4ec2109f00b7522054c4007903
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int[][] canExit; static int[][] vis; static class Pair{ int x, y; Pair(int i, int v){ x=i; y=v; } } static void solve() throws Exception { int n, m; n = sc.nextInt(); m = sc.nextInt(); int[][] mat = new int[n][m]; for (int i=0;i<n;i++){ mat[i] = sc.intArr(m); } Queue<Pair > q = new LinkedList<>(); q.add(new Pair(0,0)); q.add(new Pair(n-1,m-1)); int dist = 1; int[][] vis = new int[n][m]; vis[0][0] = 1; vis[n-1][m-1] = 1; int cost = 0; while(!q.isEmpty()){ int[] count = new int[2]; Queue<Pair > nq = new LinkedList<>(); dist++; while(!q.isEmpty()){ Pair p = q.poll(); count[ mat[p.x][p.y]]++; if ((m+n-1)%2==1){ if (dist==(m+n)/2)continue; } if (p.x!=n-1 && vis[p.x+1][p.y]==0){ vis[p.x+1][p.y]++; nq.add(new Pair(p.x+1, p.y)); } if (p.y!=m-1 && vis[p.x][p.y+1]==0) { vis[p.x][p.y + 1]++; nq.add(new Pair(p.x, p.y + 1)); } if (p.x!=0 && vis[p.x-1][p.y]==0){ vis[p.x-1][p.y]++; nq.add(new Pair(p.x-1, p.y)); } if (p.y!=0 && vis[p.x][p.y-1]==0) { vis[p.x][p.y - 1]++; nq.add(new Pair(p.x, p.y - 1)); } } q = nq; cost+= Math.min(count[0], count[1]); } System.out.println(cost); } static PrintWriter pw; static MScanner sc; public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new MScanner(System.in); int tests =sc.nextInt(); //int tests = 1; while (tests-- > 0){ solve(); pw.flush(); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } 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
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
e33a49239d6974fa33f57c32a44fb0fd
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
//package div2_646; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //static int[][] d = new int[][]{{0,1},{1,0},{-1,0},{0,-1}}; public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); int[][] a = new int[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ a[i][j] = sc.nextInt(); } } int changes = 0; if(m<n){ int[][] b = new int[m][n]; for(int i=0;i<b.length;i++){ for(int j=0;j<b[0].length;j++){ b[i][j] = a[j][i]; } } a = new int[m][n]; for(int i=0;i<b.length;i++){ for(int j=0;j<b[0].length;j++){ a[i][j] = b[i][j]; } } } n = a.length; m = a[0].length; int limit = (n+m-1)/2-1; for(int i=0;i<=limit;i++){ int j = m-1-i; //traversal 1; int r = 0; int c = i; int ones = 0; int zeros = 0; while(r<n&&c>=0){ ones+= (a[r][c]==1)?1:0; zeros+= (a[r][c]==0)?1:0; r++; c--; } //traversal2 r = n-1; c = j; while(r>=0&&c<m){ ones+= (a[r][c]==1)?1:0; zeros+= (a[r][c]==0)?1:0; r--; c++; } //System.out.println(ones + " "+zeros); changes += Math.min(ones,zeros); } System.out.println(changes); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
e7793a8e39eb55361f83d97ef2b527b2
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.util.Scanner; public class palindromePaths { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int T=sc.nextInt(); for(int t=0;t<T;t++){ int N=sc.nextInt(),M=sc.nextInt(); int[][] paths=new int[N][M]; for(int n=0;n<N;n++){ for(int m=0;m<M;m++) paths[n][m]=sc.nextInt(); } int count=0; for(int j=0;j<(N+M)/2;j++){ int n=0,zeros=0,ones=0,m=j; if(j>M-1){ m=M-1; n=j-m; } if((N+M)%2==0&&j==(N+M)/2-1) break; while(n<N&&m>=0){ if(paths[n][m]==0) zeros++; else ones++; if(paths[N-n-1][M-m-1]==0) zeros++; else ones++; n++; m--; } count+= Math.min(zeros, ones); } System.out.println(count); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
1363848468d1dc90e16f96cae8203f62
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t-- > 0) { int n = scan.nextInt(), m = scan.nextInt(); int[] zeros = new int[n+m-1], ones = new int[n+m-1]; int pointer = 0; for(int i=0;i<n;i++) { pointer = i; for(int j=0;j<m;j++) { if(scan.nextInt() == 0) { zeros[pointer]++; } else { ones[pointer]++; } pointer++; } } int answer = 0; int first = 0; for(int last = n+m-2;first < last;first++,last--) { int oneCnt = ones[first] + ones[last]; int zeroCnt = zeros[first] + zeros[last]; answer += Math.min(oneCnt,zeroCnt); } System.out.println(answer); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
40c1c92b4c6856755d1e48fda6f5c1a1
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class c { public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n][m]; for(int i = 0 ;i < n ;i++) { for(int j = 0 ;j < m ;j++) { arr[i][j] = sc.nextInt(); } } int [][] dp = new int[m+n-1][2]; for(int i = 0 ;i < n ;i++) { for(int j = 0 ;j < m ;j++) { if(arr[i][j]==0) { dp[i+j][0]++; }else { dp[i+j][1]++; } } } int lo = 0 ; int hi = m+n-2; int ans = 0 ; while(lo<hi) { ans += Math.min(dp[lo][0]+dp[hi][0], dp[lo][1]+dp[hi][1]); lo++; hi--; } System.out.println(ans); } out.flush(); } static BufferedReader in; static FastScanner sc; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } } } // long temp = a.remove(); // long temp2 = b.remove(); // //System.out.println(temp + " "+temp2 + " "+a +" "+b); // int r1 = (int) (temp/m); // int c1 = (int) (temp%m); // int r2 = (int) (temp2/m); // int c2 = (int) (temp2%m); // if(arr[r1][c1]!=arr[r2][c2]) { // count++; // } // // long row = (long)(r1)*(long)m +(long)c1+1L; // if(!ss.contains(row) && c1+1<m ) { // a.add(row); // ss.add(row); // } // // row = (long)(r1+1)*(long)m +(long)c1; // if(!ss.contains(row) && r1+1<n) { // a.add(row); // ss.add(row); // } // // row = (long)(r2-1)*(long)m +(long)c2; // if(!ss.contains(row) && r2-1>=0) { // b.add(row); // ss.add(row); // } // // row = (long)(r2)*(long)m +(long)c2-1; // if(!ss.contains(row) && c2-1>=0) { // b.add(row); // ss.add(row); // } //}
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
01035f4c1bc7744537043722dd1961a1
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import javax.sound.sampled.ReverbType; import java.util.*; import java.io.*; public class Main { static ArrayList<Integer> adj[]; // static PrintWriter out = new PrintWriter(System.out); static int[][] notmemo; static int k; static int[] a; static int b[]; static int m; static class Pair implements Comparable<Pair> { int x; int y; int val; public Pair(int b, int l,int v) { x = b; y = l; val=v; } @Override public int compareTo(Pair o) { return o.val-this.val; } } static Pair s1[]; static ArrayList<Pair> adjlist[]; // static char c[]; public static long mod = (long) (1e9 + 7); static int V; static long INF = (long) 1E16; static int n; static char c[]; static int d[]; static int z; static Pair p[]; static int R; static int C; static int K; static long grid[][]; static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String args[]) throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int group[][]=new int[n+m][2]; int a[][]=new int[n][m]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < m; j++) { a[i][j]=sc.nextInt(); } } for (int i = 0; i <n; i++) { for (int j = 0; j < m; j++) { group[i+j][a[i][j]]++; } } int cost=0; for (int i = 0; i <n+m-1; i++) { int j=(n+m)-2-i; if(i<=j) continue; cost+=Math.min(group[i][1]+group[j][1],group[i][0]+group[j][0]); } System.out.println(cost); } } static int centroid[]; static void centdfs(int u,int e) { for(int v:adj[u]) { if(v==e) { centroid[u]=Math.max(n-countnodes[u],centroid[u]); continue; } else centroid[u]=Math.max(countnodes[v],centroid[u]); centdfs(v,u); } } static void Nodesdfs(int u, int e) { countnodes[u] =1; for(int v: adj[u]) { if(v == e) continue; Nodesdfs(v,u); countnodes[u] += countnodes[v]; } } static int countnodes[]; static int max=0; static int node; static int tar; static void dfs1(int u,int count) { vis[u]=true; for(int v:adj[u]) { if(!vis[v]) { if(count>max) { max=count; node=v; } dfs1(v,count+1); } } } static class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n+1]; } int rsq(int b) //O(log n) { int sum = 0; while(b > 0) { sum += ft[b]; b -= b & -b;} //min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a-1); } void point_update(int k, int val) //O(log n), update = increment { while(k <= n) { ft[k] += val; k += k & -k; } //min? } } static ArrayList<Integer> euler=new ArrayList<>(); static ArrayList<Integer> arr; static int total; static TreeMap<Integer,Integer> map1; static int zz; //static int dp(int idx,int left,int state) { //if(idx>=k-((zz-left)*2)||idx+1==n) { // return 0; //} //if(memo[idx][left][state]!=-1) { // return memo[idx][left][state]; //} //int ans=a[idx+1]+dp(idx+1,left,0); //if(left>0&&state==0&&idx>0) { // ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1)); //} //return memo[idx][left][state]=ans; //}21 static HashMap<Integer,Integer> map; static int maxa=0; static int ff=123123; static int[][][] memo; static long modmod=998244353; static int dx[]= {1,-1,0,0}; static int dy[]= {0,0,1,-1}; static class BBOOK implements Comparable<BBOOK>{ int t; int alice; int bob; public BBOOK(int x,int y,int z) { t=x; alice=y; bob=z; } @Override public int compareTo(BBOOK o) { return this.t-o.t; } } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static class Edge implements Comparable<Edge> { int node;long cost ; long time; Edge(int a, long b,long c) { node = a; cost = b; time=c; } public int compareTo(Edge e){ return Long.compare(time,e.time); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public int chunion(int i,int j, int x2) { if (isSameSet(i, j)) return 0; numSets--; int x = findSet(i), y = findSet(j); int z=findSet(x2); p[x]=z;; p[y]=z; return x; } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static boolean vis[]; static HashSet<Integer> set = new HashSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long l, long o) { if (o == 0) { return l; } return gcd(o, l % o); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } public static int[] readarray(int n) throws IOException { int a[]=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); } return a; } public static long[] readlarray(int n) throws IOException { long a[]=new long[n]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextLong(); } return a; } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
7dab0f84f88256c2ccc8acc5a3695ba7
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.*; public class Palinpath { static int count=0; public static void run(int arr[][], int n, int m) { for(int i=0;i<(n+m-1)/2;i++) { int count0=0,count1=0; for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { if(k+j==i||k+j==n+m-2-i) { if(arr[j][k]==0) count0++; else count1++; } } } count +=(int)Math.min(count0,count1); } } public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int arr[][]= new int[n][m]; for(int i=0;i<n;i++) { st = new StringTokenizer(br.readLine()); for(int j=0;j<m;j++) arr[i][j] = Integer.parseInt(st.nextToken()); } run(arr,n,m); System.out.println(count); count=0; } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
4c76d095ea49ee6188dd94b441e2cf30
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
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.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nikita Mikhailov */ 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); CPalindromniePuti solver = new CPalindromniePuti(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CPalindromniePuti { int testNumber; InputReader in; OutputWriter out; public void solve() { int n = in.readInt(); int m = in.readInt(); int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = in.readInt(); } } int[][] ak1 = new int[2][n + m]; int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i + j >= (n + m - 2 + 1) / 2) { continue; } int i1 = n - 1 - i; int j1 = m - 1 - j; ak1[matrix[i][j]][i + j]++; ak1[matrix[i1][j1]][i + j]++; } } for (int i = 0; i < n + m; i++) { res += Math.min(ak1[0][i], ak1[1][i]); } out.println(res); } public void solve(int testNumber, InputReader in, OutputWriter out) { this.testNumber = testNumber; this.in = in; this.out = out; solve(); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
6c787b2fa7339335218a575f9ab9a3df
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class practice { static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int 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 String next() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public void close() throws IOException { if(stream==null) { return; } stream.close(); } } public static void debug(int[] ...var) { for(int[] row : var) { debug(row); } } public static void debug(long[] ...var) { for(long[] row : var) { debug(row); } } public static void debug(String[] ...var) { for(String[] row : var) { debug(row); } } public static void debug(double[] ...var) { for(double[] row : var) { debug(row); } } public static void debug(int ...var) { for(int i:var) System.err.print(i+" "); System.err.println(); } public static void debug(String ...var) { for(String i:var) System.err.print(i+" "); System.err.println(); } public static void debug(double ...var) { for(double i:var) System.err.print(i+" "); System.err.println(); } public static void debug(long ...var) { for(long i:var) System.err.print(i+" "); System.err.println(); } /* public static <T> void debug(T ...varargs) { // Warning // Heap Pollution might occur // this overrides even 1d and 2d array methods as it is an object... // + i am not using object based array like Integer[] // I am using int[] so that is a problem as i need Wrapper class as an argument for(T val:varargs) System.err.printf("%s ",val); System.err.println(); } */ private static InputReader scan = new InputReader(System.in); static class ij { int i,j; ij( int i,int j) { this.i = i; this.j = j; } } private static boolean isBounds(final int i,final int j, final int rows, final int cols) { return (i>=1 && i<= rows) && (j>=1 && j <= cols); } public static void main(String args[]) throws Exception { //Faster Output... PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringBuilder sb = new StringBuilder(); //Scanner scan = new Scanner(System.in); //scan.useDelimiter(""); // for reading character by character //be careful of readLine() -- length of string; int t = scan.nextInt(); while(t-->0) { int rows = scan.nextInt(); int cols = scan.nextInt(); int[][] matrix = new int[rows+1][cols+1]; for(int i=1;i<=rows;++i) { for(int j=1;j<=cols;++j) { matrix[i][j]=scan.nextInt(); } } // rep = rows+cols-1 >> 1 Queue<ij> starts = new LinkedList<>(); Queue<ij> ends= new LinkedList<>(); starts.add(new ij(1,1)); Set<Integer> vis1 = new HashSet<>(); vis1.add(1*1000+1); Set<Integer> vis2 = new HashSet<>(); vis2.add(rows*1000+cols); ends.add(new ij(rows,cols)); int rep = (rows+cols-1)>>1; int toChange = 0; while(rep-->0) { int ones = 0; int zeros = 0; int sizeStart = starts.size(); for(int r = 0; r<sizeStart;++r) { ij temp = starts.poll(); int i = temp.i,j = temp.j; if(matrix[i][j]==1) { ++ones; } else { ++zeros; } if(isBounds(i+1,j,rows,cols) && !vis1.contains((i+1)*1000+j)) { starts.add(new ij(i+1,j)); vis1.add((i+1)*1000+j); } if(isBounds(i,j+1,rows,cols) && !vis1.contains((i)*1000+j+1)) { starts.add(new ij(i,j+1)); vis1.add((i)*1000+j+1); } } int sizeEnd = ends.size(); assert sizeEnd == sizeStart : "oops"; for(int r = 0; r<sizeEnd;++r) { ij temp = ends.poll(); int i = temp.i,j = temp.j; if(matrix[i][j]==1) { ++ones; } else { ++zeros; } if(isBounds(i-1,j,rows,cols) && !vis2.contains((i-1)*1000+j)) { ends.add(new ij(i-1,j)); vis2.add((i-1)*1000+j); } if(isBounds(i,j-1,rows,cols) && !vis2.contains((i)*1000+j-1)) { ends.add(new ij(i,j-1)); vis2.add(i*1000+j-1); } } toChange+=Math.min(ones,zeros); } out.println(toChange); } scan.close(); out.close(); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
87b69a9891b2fdc9a22f442a54a0c432
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; 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(); }void main() throws IOException { // StringBuilder sb = new StringBuilder(); PrintWriter out = new PrintWriter(System.out); String[] s1=s(); int t=i(s1[0]); while(t-->0){ String[] s2=s(); int n=i(s2[0]);int m=i(s2[1]); char[][] a=new char[n][m]; for(int i=0;i<n;i++){ String[] s3=s(); for(int j=0;j<m;j++){ a[i][j]=s3[j].charAt(0); } } // System.out.println(a[1][1]); int[] c0=new int[n+m];int []c1=new int[n+m];int ans=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(a[i][j]=='0'){ c0[Math.min(n+m-2-(i+j),i+j)]++; }else{ c1[Math.min(n+m-2-(i+j),i+j)]++; } } } for(int i=0;i<n+m;i++){ if(i==(n+m-1)/2&&(n+m-1)%2!=0) continue; // System.out.println(c0[i]+" "+c1[i]); ans+=Math.min(c0[i],c1[i]); } System.out.println(ans); } } 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); } } class node implements Comparator<node>{ int ver,val; public node(){} public node(int ver,int val) { this.ver=ver;this.val=val; }public int compare(node n1,node n2){ return n1.val-n2.val; } } class Student12 { int l;int r; public Student12(int l, int 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(a.r<b.r) return 1;else if(a.r==b.r) return 0;else return -1;// a.r-b.r; /* 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; */} } class Node1 implements Comparator<Node1>{ int node;long val; public Node1(){} public Node1(int node,long val){ this.node=node;this.val=val; } @Override public int compare(Node1 a,Node1 b){ if(a.val<b.val) return -1; if(a.val==b.val) return 0; { return 1; } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
ac92bd3246c6f4a2bd925cf867c6f780
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class TestClass { static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final int readInt() throws IOException { return (int) readLong(); } public final long readLong() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new IOException(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public final long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static long mulmod(long a, long b, long mod) { long res = 0; // Initialize result a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) { res = (res + a) % mod; } // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } static long pow(long a, long b, long MOD) { long x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y); if (x > MOD) x %= MOD; } y = (y * y); if (y > MOD) y %= MOD; b /= 2; } return x; } static long[] f = new long[100001]; static long InverseEuler(long n, long MOD) { return pow(n, MOD - 2, MOD); } static long C(int n, int r, long MOD) { return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD; } public static class SegmentTree { long[] tree; long[] lazy; int n; public SegmentTree(long[] arr) { n = arr.length; tree = new long[arr.length * 5]; lazy = new long[arr.length * 5]; build(arr, 0, arr.length - 1, 0); } private void build(long[] arr, int s, int e, int pos) { if (s == e) { tree[pos] = arr[s]; return; } int m = (s + e) / 2; build(arr, s, m, 2 * pos + 1); build(arr, m + 1, e, 2 * pos + 2); tree[pos] = Math.max(tree[2 * pos + 1], tree[2 * pos + 2]); } public void update(int s, int e, long val) { updateUtil(s, e, val, 0, n - 1, 0); } public long get(int s, int e) { return getUtil(s, e, 0, n - 1, 0); } private long getUtil(int gs, int ge, int s, int e, int pos) { if (s > e || s > ge || e < gs) return Long.MIN_VALUE; if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (s != e) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (s >= gs && e <= ge) { return tree[pos]; } int m = (s + e) / 2; return Math.max(getUtil(gs, ge, s, m, 2 * pos + 1), getUtil(gs, ge, m + 1, e, 2 * pos + 2)); } private void updateUtil(int us, int ue, long val, int s, int e, int pos) { if (s > e || s > ue || e < us) return; if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (s != e) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (s >= us && e <= ue) { tree[pos] += val; if (s != e) { lazy[2 * pos + 1] += val; lazy[2 * pos + 2] += val; } return; } int m = (s + e) / 2; updateUtil(us, ue, val, s, m, 2 * pos + 1); updateUtil(us, ue, val, m + 1, e, 2 * pos + 2); tree[pos] = Math.max(tree[2 * pos + 1], tree[2 * pos + 2]); } } static int[] h = {0, 0, -1, 1}; static int[] v = {1, -1, 0, 0}; public static class Pair { public int x, y, p; public Pair(int d, int y) { this.x = d; this.y = y; } } static long compute_hash(String s) { int p = 31; int m = 1000000007; long hash_value = 0; long p_pow = 1; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } public static void main(String[] args) throws Exception { //https://i...content-available-to-author-only...e.com/ebRGa6 InputReader in = new InputReader(System.in); long t = in.readLong(); while (t-- > 0) { int n = in.readInt(); int m = in.readInt(); int[][] arr = new int[n][m]; int farGo = (n+m-1)/2; Map<Integer, Integer> mm0 = new HashMap<>(); Map<Integer, Integer> mm1 = new HashMap<>(); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i][j] = in.readInt(); if (i+j < farGo) { if (arr[i][j] == 0) mm0.put(i+j, mm0.getOrDefault(i+j, 0) + 1); else mm1.put(i+j, mm1.getOrDefault(i+j, 0) + 1); } else { if ((n+m-1) % 2 == 1 && i+j == farGo) { } else { if (arr[i][j] == 0) mm0.put(n-1-i + m-1-j, mm0.getOrDefault(n-1-i + m-1-j, 0) + 1); else mm1.put(n-1-i + m-1-j, mm1.getOrDefault(n-1-i + m-1-j, 0) + 1); } } } } int answer = 0; for (int i = 0; i <= farGo; ++i) { int zero = mm0.getOrDefault(i, 0); int one = mm1.getOrDefault(i, 0); answer += Math.min(zero, one); } System.out.println(answer); } } private static long solve(long[][] dp, int n, int r) { if (n == 0) { if (r == 0) return 1; else return 0; } if (r <= 0) return 0; if (dp[n][r] != -1) return dp[n][r]; long answer = 0; for (int i = 1; i < n; ++i) { answer += solve(dp, n - 1, r - i); } dp[n][r] = answer; return answer; } static int gcd(int a, int b) { while (b != 0) { int t = a; a = b; b = t % b; } return a; } class Solution { public int maxProduct(int[] nums) { PriorityQueue<Integer> p = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer integer, Integer t1) { return Integer.compare(t1, integer); } }); for (int i = 0; i < nums.length; ++i) { p.add(nums[i]); } int f = p.remove(); int s = p.remove(); return (f - 1) * (s - 1); } } static boolean submit = true; static void debug(String s) { if (!submit) System.out.println(s); } static void debug(int s) { if (!submit) System.out.println(s); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
554453034c67a1f1813df8af78b4dd16
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.io.*; import java.util.HashSet; public class STRING{ public static void main(final String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); PrintWriter writer = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); int [][] arr = new int[n][m]; int [] arr1 = new int[n+m-1]; int [] arr2 = new int[n+m-1]; int ans=0; for(int i = 0;i<n;i++){ for (int j=0;j<m;j++) arr[i][j]=sc.nextInt(); } for(int i=0;i<n+m-1;i++){ int k=0; for(int j = Math.max(0,i-m+1);j<=Math.min(i,n-1);j++){ arr1[i] += arr[j][Math.min(i,m-1)-1*k]; // System.out.print(arr[j][Math.min(i,m-1)-1*k]+" "+(Math.min(i,m-1)-1*k)+" "+j+" "); arr2[i] +=1; k++; } System.out.println(); } for(int i=0;i<arr1.length/2;i++){ ans += Math.min(arr2[i]-arr1[i]+arr2[n+m-2-i]-arr1[n+m-2-i],arr1[i]+arr1[n+m-2-i]); // System.out.println(ans); } writer.println(ans); writer.flush(); } } public static String replace(String str, int index, char replace){ if(str==null){ return str; }else if(index<0 || index>=str.length()){ return str; } char[] chars = str.toCharArray(); chars[index] = replace; return String.valueOf(chars); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
a89950a6196f8ff61cec2de5b218c781
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.io.*; import java.util.HashSet; public class STRING{ public static void main(final String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); PrintWriter writer = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); int [][] arr = new int[n][m]; int [] arr1 = new int[n+m-1]; int [] arr2 = new int[n+m-1]; int ans=0; for(int i = 0;i<n;i++){ for (int j=0;j<m;j++) arr[i][j]=sc.nextInt(); } for(int i=0;i<n+m-1;i++){ int k=0; for(int j = Math.max(0,i-m+1);j<=Math.min(i,n-1);j++){ arr1[i] += arr[j][Math.min(i,m-1)-1*k]; // System.out.print(arr[j][Math.min(i,m-1)-1*k]+" "+(Math.min(i,m-1)-1*k)+" "+j+" "); arr2[i] +=1; k++; } } for(int i=0;i<arr1.length/2;i++){ ans += Math.min(arr2[i]-arr1[i]+arr2[n+m-2-i]-arr1[n+m-2-i],arr1[i]+arr1[n+m-2-i]); // System.out.println(ans); } writer.println(ans); writer.flush(); } } public static String replace(String str, int index, char replace){ if(str==null){ return str; }else if(index<0 || index>=str.length()){ return str; } char[] chars = str.toCharArray(); chars[index] = replace; return String.valueOf(chars); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
b85ba74e6e2460428b97c6bb5688f020
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public final class C { public static void main(String[] args) { final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); final int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { final int n = in.nextInt(); final int m = in.nextInt(); final int total = n + m - 1; final int[] a = new int[total]; final int[] b = new int[total]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { final int x = in.nextInt(); if (x == 1) { a[i + j]++; } else { b[i + j]++; } } } int ans = 0; for (int i = 0; i < total / 2; i++) { ans += Math.min(a[i] + a[total - i - 1], b[i] + b[total - i - 1]); } System.out.println(ans); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
3e038e2339ab8008c91b7939bc92d192
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class C_ { static Scanner sc; static PrintWriter out; static int[][] a; static boolean[][] done; static int ans; static void main()throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); a = new int[n][m]; done = new boolean[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt(); ans = 0; for(int p=0;p<m;p++) { int q = m-1 - p; int[] res = check(0,p,n-1,q); int len=res[0],ones = res[1]; if(len==0) { out.println(ans); return; } if(ones > len/2) { ans+= (len-ones); } else { ans+= ones; } } for(int row1=1;row1<n;row1++) { int row2 = n-1 - row1; int[] res = check(row1,m-1,row2,0); int len=res[0],ones = res[1]; if(len==0) { out.println(ans); return; } if(ones > len/2) { ans+= (len-ones); } else { ans+= ones; } } } static int[] check(int row1,int p,int row2,int q) { if(done[row1][p] || willMeet(row2,q,row1,p)) return new int[] {0,0}; int len = 0,ones =0; int r=row1,c=p; while(r<a.length && c >=0) { len++; done[r][c]=true; if(a[r][c] == 1) ones++; r++; c--; } r=row2;c=q; while(r>=0 && c<a[0].length) { len++; done[r][c]=true; if(a[r][c]==1) ones++; r--; c++; } return new int[] {len,ones}; } static boolean willMeet(int x1,int y1,int x2,int y2) { return x2-x1 == y1-y2; } public static void main(String[] args) throws Exception{ sc = new Scanner(System.in); out = new PrintWriter(System.out); int TC = sc.nextInt(); while(TC-->0) { main(); } out.flush(); out.close(); } static class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(FileReader file) { br = new BufferedReader(file); } public String next() throws IOException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } 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(5000); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
4baaf7fc45e5c7d47f590fa66fc7b251
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int tc = 1; tc =cinI(); while (tc-- > 0) { // int n = cinI(); String[] arr =cinA(); //int[] n = new int[n]; int n =getI(arr[0]); int m =getI(arr[1]); int[][] mat= new int[n][m]; for(int i = 0; i< n;i++){ String[] d = cinA(); for(int j=0;j<m;j++){ mat[i][j]=getI(d[j]); } } long ans=0; ArrayList<Diag> dia =new ArrayList<Diag>(); for(int i=0;i<n;i++){ int j=0; int c0=0; int c1=0; int x=i; while (x>=0 &&j<m){ if(mat[x][j]==1){ c1+=1; j+=1; x-=1; continue; } c0+=1; x-=1; j+=1; } dia.add(new Diag(c0,c1)); } for(int j=1;j<m;j++){ int c1=0; int c0=0; int i=n-1; int x=j; while (i>=0 && x<m){ if(mat[i][x]==1){ c1+=1; i-=1; x+=1; continue; } c0+=1; i-=1; x+=1; continue; } dia.add(new Diag(c0,c1)); } int x=dia.size()-1; for(int u=0;u<dia.size()/2;u++){ Diag a = dia.get(u); Diag b = dia.get(x); if(x!=u){ int c0=a.c0+b.c0; int c1=a.c1+b.c1; ans= ans+Math.min(c0,c1); x-=1; } } System.out.println(ans); } } 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 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 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]); } } } class range { int l; int r; int diff; public range(int l, int r, int diff) { this.l = l; this.r = r; this.diff = diff; } } class sortRange implements Comparator<range> { @Override public int compare(range range, range t1) { if (range.diff != t1.diff) return t1.diff - range.diff; return range.l - t1.l; }} class Diag{ int c0; int c1; public Diag(int c0,int c1){ this.c0=c0; this.c1=c1; } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
93ff16ed605fef3cc0885ceea627d04e
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeMap; public class c { static FastReader fs = new FastReader(); public static void main(String[] args) { int t = fs.readInt(); while(t-- > 0){ solve(); } } public static void solve(){ int n = fs.readInt(), m = fs.readInt(); int[][] mat = new int[n][m]; TreeMap<Integer, ArrayList<Integer>> mp = new TreeMap<>(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ mat[i][j] = fs.readInt(); int d = i+j; int d2 = n-1 -i + m-1-j; if(d==d2)continue; d = Math.min(d,d2); if(mp.containsKey(d)){ ArrayList<Integer> temp = mp.get(d); if(mat[i][j]==1){ temp.set(1,temp.get(1)+1); } else{ temp.set(0,temp.get(0)+1); } } else{ Integer[] a = new Integer[]{0,0}; ArrayList<Integer> temp = new ArrayList<Integer>(Arrays.asList(a)); temp.set(mat[i][j],temp.get(mat[i][j])+1); mp.put(d,temp); } } } int ans =0 ; for(ArrayList<Integer> temp:mp.values()){ ans += Math.min(temp.get(0),temp.get(1)); } System.out.println(ans); } static class FastReader{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreElements()){ try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int readInt(){ return Integer.parseInt(next()); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
5563cccf6314b288fe8f5cf175c17d0f
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class C { public static void main(String[] args) throws Exception { new C().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); while(asdf-->0) { int r = f.nextInt(), c = f.nextInt(); int[] cnt = new int[r+c-1]; int[] tot = new int[r+c-1]; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { int a = f.nextInt(); cnt[i+j] += a; tot[i+j]++; } } int ans = 0; for(int i = 0; i < cnt.length/2; i++) ans += Math.min(cnt[i]+cnt[cnt.length-i-1], tot[i]+tot[cnt.length-i-1]-cnt[i]-cnt[cnt.length-i-1]); out.println(ans); } out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
1cbbb1bdca15c789c0cf293ab2e462c7
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
// package cp; import java.io.*; import java.util.*; public class Cf_three { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Readers.init(System.in); int t=Readers.nextInt(); for (int ii = 0; ii < t; ii++) { int n=Readers.nextInt(); int m=Readers.nextInt(); int[][] a=new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j]=Readers.nextInt(); } } int[][] cnt=new int[(n+m-2)+1][2];//see +1 for (int i = 0; i <n; i++) { for (int j = 0; j < m; j++) { int dist1=i+j; int dist2=(n-i-1) + (m-j-1); // System.out.println(dist1+" oh "+dist2); if(dist1==(n+m-2)/2 && ((n+m)%2==0))continue; else { // System.out.println("a"); cnt[Math.min(dist1,dist2)][a[i][j]]++; // System.out.println("b"); } } } int ans=0; for (int i = 0; i < cnt.length; i++) { ans+=Math.min(cnt[i][0], cnt[i][1]); } System.out.println(ans); } out.flush(); } } class Readers { 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()); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
4846139baa8ca730be692ab3b6b87de9
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.StringTokenizer; public class Task3 { public static void main(String[] args) throws IOException { new Task3().solve(); } public void solve() throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); for (int t1 = 0; t1 < t; t1++) { StringTokenizer tokenizer = new StringTokenizer(f.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { tokenizer = new StringTokenizer(f.readLine()); for (int j = 0; j < m; j++) { matrix[i][j] = Integer.parseInt(tokenizer.nextToken()); } } int upTo = (n + m - 1) / 2; upTo--; int[][] atDistance = new int[upTo + 1][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int path1 = i + j; int path2 = n - 1 - i + m - 1 - j; if (path1 <= upTo) { atDistance[path1][matrix[i][j]]++; } if (path2 <= upTo) { atDistance[path2][matrix[i][j]]++; } } } int toChange = 0; for (int i = 0; i <= upTo; i++) { //System.out.println(i + " " + atDistance[i][0] + " " + atDistance[i][1]); toChange += Math.min(atDistance[i][0], atDistance[i][1]); } //System.out.println(); out.println(toChange); } out.close(); } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
8cf00966f43e4e36af43a59aae56cd4d
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
// package com.company.codeforces; import java.util.HashMap; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner input=new Scanner(System.in); int t=input.nextInt(); while (t-->0){ int n=input.nextInt()-1; int m=input.nextInt()-1; int cent=-1; if ((n+m)%2==0){ cent=(n+m)/2; } int a[][]=new int[n+1][m+1]; HashMap<Integer,int[]> map=new HashMap<>(); for (int i = 0; i <=n ; i++) { for (int j = 0; j <=m ; j++) { a[i][j]=input.nextInt(); if (i+j==cent){ continue; } int cont=(n+m)-i-j; int min=Math.min(cont,i+j); if (map.containsKey(min)){ int te[]=map.get(min); if (a[i][j]==0) te[0]++; else te[1]++; }else { int te[]=new int[2]; if (a[i][j]==0) te[0]++; else te[1]++; map.put(min,te); } } } int res=0; for (int sum:map.keySet()) { int te[]=map.get(sum); res+=Math.min(te[0],te[1]); } System.out.println(res); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
67c1dc6bab2f264cbd5e67636e5a4d93
train_001.jsonl
1591886100
You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.
256 megabytes
import java.io.BufferedReader; import java.io.EOFException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Main { public void exec() { int t = stdin.nextInt(); for (int i = 0; i < t; i++) { int n = stdin.nextInt(); int m = stdin.nextInt(); int[][] a = new int[n][m]; for (int x = 0; x < n; x++) { for (int y = 0; y < m; y++) { a[x][y] = stdin.nextInt(); } } stdout.println(solve(n, m, a)); } } private int solve(int n, int m, int[][] a) { Set<List<Integer>> p = Set.of(List.of(0, 0)); Set<List<Integer>> q = Set.of(List.of(n - 1, m - 1)); List<List<Integer>> dp = List.of(List.of(1, 0), List.of(0, 1)); List<List<Integer>> dq = List.of(List.of(-1, 0), List.of(0, -1)); int ans = 0; for (int time = 0; time < (n+m-1)/2; time++) { int[] count = new int[2]; for (List<Integer> r : p) { int x = r.get(0); int y = r.get(1); count[a[x][y]]++; } for (List<Integer> r : q) { int x = r.get(0); int y = r.get(1); count[a[x][y]]++; } ans += Math.min(count[0], count[1]); Set<List<Integer>> np = new HashSet<>(); Set<List<Integer>> nq = new HashSet<>(); for (List<Integer> r : p) { for (List<Integer> d : dp) { int dx = r.get(0) + d.get(0); int dy = r.get(1) + d.get(1); if (0 <= dx && dx < n && 0 <= dy && dy < m) { np.add(List.of(dx, dy)); } } } for (List<Integer> r : q) { for (List<Integer> d : dq) { int dx = r.get(0) + d.get(0); int dy = r.get(1) + d.get(1); if (0 <= dx && dx < n && 0 <= dy && dy < m) { nq.add(List.of(dx, dy)); } } } p = np; q = nq; } return ans; } private static final Stdin stdin = new Stdin(); private static final Stdout stdout = new Stdout(); public static void main(String[] args) { try { new Main().exec(); } finally { stdout.flush(); } } public static class Stdin { private BufferedReader stdin; private Deque<String> tokens; private Pattern delim; public Stdin() { stdin = new BufferedReader(new InputStreamReader(System.in)); tokens = new ArrayDeque<>(); delim = Pattern.compile(" "); } public String nextString() { try { if (tokens.isEmpty()) { String line = stdin.readLine(); if (line == null) { throw new UncheckedIOException(new EOFException()); } delim.splitAsStream(line).forEach(tokens::addLast); } return tokens.pollFirst(); } catch (IOException e) { throw new UncheckedIOException(e); } } public int nextInt() { return Integer.parseInt(nextString()); } public double nextDouble() { return Double.parseDouble(nextString()); } public long nextLong() { return Long.parseLong(nextString()); } public String[] nextStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = nextString(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); 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 static class Stdout { private PrintWriter stdout; public Stdout() { stdout = new PrintWriter(System.out, false); } public void printf(String format, Object ... args) { String line = String.format(format, args); if (line.endsWith(System.lineSeparator())) { stdout.print(line); } else { stdout.println(line); } } public void println(Object ... o) { String line = Arrays.stream(o).map(Objects::toString).collect(Collectors.joining(" ")); stdout.println(line); } public void debug(Object ... objs) { String line = Arrays.stream(objs).map(this::deepToString).collect(Collectors.joining(" ")); stdout.printf("DEBUG: %s%n", line); } private String deepToString(Object o) { if (o == null) { return "null"; } Class<?> clazz = o.getClass(); // 配列の場合 if (clazz.isArray()) { int len = Array.getLength(o); String[] tokens = new String[len]; for (int i = 0; i < len; i++) { tokens[i] = deepToString(Array.get(o, i)); } return "{" + String.join(",", tokens) + "}"; } // toStringがOverrideされている場合 if (Arrays.stream(clazz.getDeclaredMethods()).anyMatch(method -> method.getName().equals("toString") && method.getParameterCount() == 0)) { return Objects.toString(o); } // Tupleの場合 (フィールドがすべてpublicのJava Beans) try { List<String> tokens = new ArrayList<>(); for (Field field : clazz.getFields()) { String token = String.format("%s=%s", field.getName(), deepToString(field.get(o))); tokens.add(token); } return String.format("%s:[%s]", clazz.getName(), String.join(",", tokens)); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } public void flush() { stdout.flush(); } } }
Java
["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"]
1.5 seconds
["0\n3\n4\n4"]
NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 &amp; 1\\ 0 &amp; 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \end{pmatrix}$$$
Java 11
standard input
[ "greedy", "math" ]
b62586b55bcfbd616d936459c30579a6
The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).
1,500
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
standard output
PASSED
891bfb65be27f0c753351a90dfb9e419
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; public class Test4 { public static void main(String [] args)throws Exception { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); String line = read.readLine(); int n = line.length(); boolean flag = true; for(int i=0;i<n/2-1;i++) { if(line.charAt(i) != line.charAt(i+1)) { flag = false; } } if(flag) { System.out.println("Impossible"); return; } for(int i=1;i<line.length();i++){ String s2=line.substring(i,line.length())+line.substring(0,i); if(!line.equals(s2) && checkPalindrome(s2)){ System.out.println("1"); return; } } System.out.println("2"); } static boolean checkPalindrome(String s){ for(int i=0,j=s.length()-1;i<j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
2a4cd1fc0cf680c51ab5923a8572a32e
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; import java.io.*; public class P1113D { private static void solve() { String s = next(); char[] c = s.toCharArray(); int[] cnt = new int[26]; for (int i = 0; i < c.length; i++) { cnt[c[i] - 'a']++; } boolean good = true; for (int i = 0; i < 26; i++) { if (cnt[i] == c.length || cnt[i] == c.length - 1) { good = false; } } if (!good) { System.out.println("Impossible"); return; } for (int i = 0; i < c.length - 1; i++) { String first = s.substring(0, i + 1); String second = s.substring(i + 1); String target = second + first; StringBuilder sb = new StringBuilder(target); if (sb.reverse().toString().equals(target) && !s.equals(target)) { System.out.println(1); return; } } System.out.println(2); } private static void run() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } private static StringTokenizer st; private static BufferedReader br; private static PrintWriter out; private static String next() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return null; } st = new StringTokenizer(s); } return st.nextToken(); } private static int nextInt() { return Integer.parseInt(next()); } private static long nextLong() { return Long.parseLong(next()); } public static void main(String[] args) { run(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
9915588fdcbec0ae7c50570c073313ca
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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; ReaderFastIO in = new ReaderFastIO(inputStream); PrintWriter out = new PrintWriter(outputStream); DSashaAndOneMoreName solver = new DSashaAndOneMoreName(); solver.solve(1, in, out); out.close(); } static class DSashaAndOneMoreName { public void solve(int testNumber, ReaderFastIO in, PrintWriter out) { char[] line = in.nextLine().toCharArray(); int n = line.length; if (isImpossible(line, n)) { out.println("Impossible"); return; } boolean only1 = false; for (int i = 1; i < n; i++) { char[] newline = new char[n]; int index = 0; for (int j = i; j < n; j++) { newline[index] = line[j]; index++; } for (int j = 0; j < i; j++) { newline[index] = line[j]; index++; } boolean igualArray = Arrays.equals(line, newline); boolean palindrome = isPalindrome(0, n - 1, newline); if (igualArray == false && palindrome == true) { only1 = true; break; } } out.println(only1 == true ? "1" : "2"); } public boolean isPalindrome(int i, int j, char[] line) { while (i < j) { if (line[i] != line[j]) return false; i++; j--; } return true; } public boolean isImpossible(char[] line, int n) { if (n % 2 == 0) { boolean igual = true; for (int i = 1; i < n; i++) { if (line[0] != line[i]) { igual = false; break; } } return igual; } else { boolean igual = true; for (int i = 1; i < n; i++) { if (i == n / 2) continue; if (line[0] != line[i]) { igual = false; break; } } return igual; } } } static class ReaderFastIO { BufferedReader br; public ReaderFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } public ReaderFastIO(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
551ae711214f2ec6fe7b5fd6ca5da7c8
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { System.out.println(new Solution().solve()); } private String solve() { Scanner in = new Scanner(System.in); String s = in.next(); int n = s.length(); if (n == 1) return "Impossible"; int[] c = new int[26]; for (int i = 0; i < s.length() / 2; ++i) ++c[s.charAt(i) - 'a']; int count = 0; for (int i = 0; i < 26; ++i) if (c[i] > 0) ++count; if (count == 1) return "Impossible"; for (int i = 1; i <= n; ++i) { String ns = s.substring(i) + s.substring(0, i); if (verify(n, ns, s)) return "1"; } return "2"; } private boolean verify(int n, String ns, String s) { if (ns.equals(s)) return false; for (int i = 0; i < n / 2; ++i) { if (ns.charAt(i) != ns.charAt(n - 1- i)) return false; } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
e7e5ffd0bcde3221d5f3b9ba806ab531
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; import java.lang.StringBuilder; public class Main { public static void main(String[] args) { MyScanner myScanner = new MyScanner(); PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out)); new Solver().solve(myScanner, printWriter); printWriter.close(); } private static class Solver { public int getNumberOfDiff(String s){ int diff = 0; boolean[] exists = new boolean[350]; Arrays.fill(exists, false); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(!exists[c]){ diff++; exists[c] = true; } } return diff; } public void solveOdd(String s, PrintWriter out){ if(getNumberOfDiff(s.substring(0, s.length() / 2)) <= 1){ out.println("Impossible"); return; } out.println(2); } public void solveEven(String s, PrintWriter out){ if(getNumberOfDiff(s) <= 1){ out.println("Impossible"); return; } while(s.length() % 2 == 0){ int half = s.length() / 2; String leftString = s.substring(0, half); String rightString = s.substring(half); if(leftString.compareTo(rightString) != 0){ out.println(1); return; } s = leftString; } out.println(2); } public void solve(MyScanner in, PrintWriter out) { String s = in.nextLine(); if(s.length() <= 3) { out.println("Impossible"); return; } if(s.length() % 2 != 0){ solveOdd(s, out); } else{ solveEven(s, out); } } } private 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
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
e19792dd4547b4ebda1be3e0cb73f41d
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.function.Function; public class MainD { static String S; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); S = sc.next(); System.out.println(solve()); } static String IMP = "Impossible"; static String solve() { // a, aa if( S.length() == 1 || S.length() == 2 ) return IMP; int cnt = 0; for (int i = 0; i < S.length(); i++) { if( S.charAt(i) == S.charAt(0) ) cnt++; } if( S.length()%2 == 1 ) { // aba, aaa if( cnt >= S.length()-1 ) return IMP; // ab|a|ba return "2"; } else { // aaaa if( cnt == S.length() ) return IMP; while(true) { // S = T + T String T = S.substring(0, S.length()/2); if( isPalindrome(T) ) { if( T.length() % 2 == 1 ) { // ab|a|aba return "2"; } else { S = T; continue; } } else { // abc|cba return "1"; } } } } static boolean isPalindrome(String s) { int n = s.length(); for (int i = 0; i < n/2; i++) { if( s.charAt(i) != s.charAt(n-i-1) ) return false; } return true; } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
4b6f96d884f952aa439401f46670422e
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { String s; int n; boolean checkPoly(int from, int to) { for (int i = 0; i < (to - from + 1) / 2; i++) { if (s.charAt(from + i) != s.charAt(to - i)) return false; } return true; } boolean sim(int from, int len) { for (int i = 0; i < len; i++) { if (s.charAt(from + i) != s.charAt(from + len + i)) return false; } return true; } public void solve(int testNumber, FastScanner in, PrintWriter out) { s = in.ns(); n = s.length(); boolean impossible = true; for (int i = 1; i < n / 2; i++) { if (s.charAt(i) != s.charAt(0)) { impossible = false; break; } } if (impossible) { out.println("Impossible"); return; } for (int i = 1; i <= n / 2; i++) { if (checkPoly(0, i * 2 - 1) && !sim(0, i) && (i * 2 >= n - 1 || checkPoly(i * 2, n - 1))) { //System.out.println("i = " + i); out.println(1); return; } } out.println(2); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
c25238872ef6f3d55acf44377e7ce5fd
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
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.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; 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 Gabriel Carrillo */ 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); DSashaAndOneMoreName solver = new DSashaAndOneMoreName(); solver.solve(1, in, out); out.close(); } static class DSashaAndOneMoreName { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.next(); if (!possible(s, 0, s.length())) { out.println("Impossible"); return; } out.println(find(s)); } boolean possible(String s, int l, int r) { if (l == r || r - l == 1) return false; String sub = s.substring(l, l + (r - l) / 2); Set<Character> set = new HashSet<>(); for (int i = 0; i < sub.length(); i++) set.add(sub.charAt(i)); return set.size() != 1; } int find(String s) { for (int i = 1; i < s.length(); i++) { String s1 = s.substring(0, i); String s2 = s.substring(i); String s3 = s2 + s1; if (isPalindrome(s3) && !s3.equals(s)) return 1; } return 2; } boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) if (s.charAt(left++) != s.charAt(right--)) return false; return true; } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
ff5f11b034e1136cfbb6de00629efa2b
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.HashSet; import java.util.Set; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Arrays; import java.util.HashMap; public class nnnn { /*static boolean f; static int inf=(int)1e9; static long x, y, d; public static long gcd(long a,long b) { if (b==0) return a; return gcd(b,a%b); } static void extendedEuclid(long a, long b) { if(b == 0) { x = 1; y = 0; d = a; return; } extendedEuclid(b, a % b); long x1 = y; long y1 = x - a / b * y; x = x1; y = y1; }*/ public static boolean isp(StringBuilder s) { for(int i=0;i<s.length()/2;i++) { if(s.charAt(i)!=s.charAt(s.length()-1-i)) { return false; } } return true; } public static void main(String[] args) throws IOException { MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); StringBuilder s=new StringBuilder(sc.nextLine()); boolean no=true;int ans=0;int c=0; while(s.length()>2) { StringBuilder l=new StringBuilder();StringBuilder r=new StringBuilder(); int mid=(int)Math.ceil(s.length()/2.0); for(int i=0;i<s.length()/2;i++) { l.append(s.charAt(i)); r.append(s.charAt(i+mid)); } if(s.length()%2==0) { ans=1; } else { ans=2; } if(!l.toString().equals(r.toString())) { no=false;pw.println(ans);break; } else { char midl=s.charAt(s.length()/2); StringBuilder c1=new StringBuilder(midl+""); c1.append(r); StringBuilder c2=new StringBuilder(l); c2.append(midl); if(c!=0 && s.length()>1 && s.length()%2==1 && !c1.toString().equals(c2.toString())) { pw.println(2);no=false;break; } else { s=new StringBuilder(l); } } c++; } if(no) { pw.println("Impossible"); } pw.close(); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(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
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
94c94b4d432b9e818aef3820360ad524
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; public class div539D { BufferedReader in; PrintWriter ob; StringTokenizer st; public static void main(String[] args) throws IOException { new div539D().run(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); ob = new PrintWriter(System.out); solve(); ob.flush(); } void solve() throws IOException { String s = ns(); int length = s.length(); if( isAnswerPossible( s ) ) ob.println( isOneCyclicShift( s ) ? 1 : 2 ); else ob.println("Impossible"); } boolean isAnswerPossible( String s ) { int count = 0; for(int i=1 ; i<s.length() ; i++) { count += ( s.charAt(0)!=s.charAt(i) )?1:0; } return (count>1)?true:false; } boolean isOneCyclicShift( String s ) { int l = s.length(); for(int i=0 ; i<l ; i++) { String cyclicShift = s.substring(i) + s.substring(0,i); if( !s.equals( cyclicShift ) && isPalindrome( cyclicShift ) ) return true; } return false; } boolean isPalindrome( String s ) { int l = s.length(); for(int i = 0 ; i<l ; i++) { if( s.charAt(i) != s.charAt( l-i-1 ) ) return false; } return true; } String ns() throws IOException { return nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } String nextToken() throws IOException { if( st == null || !st.hasMoreTokens() ) st = new StringTokenizer(in.readLine()); return st.nextToken(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
a6bdc311d6eca2a995eff4d0b6ba927f
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String S=sc.next(); char[] arr=S.toCharArray(); int n=arr.length; int ans=0; char ch=arr[0]; for(int i=0;i<n/2;i++) if(arr[i]!=ch) ans=-1; if(ans==0) { System.out.println("Impossible"); return; } else { for(int i=1;i<n;i++) { String str=S.substring(i+1,n)+S.substring(0,i+1); if(str.compareTo(S)!=0) { if(solve(str)) { ans=1; break; } } } if(ans==-1) ans=2; } System.out.println(ans); } public static boolean solve(String str) { int n=str.length(); int j=n-1; for(int i=0;i<j;i++,j--) { if(str.charAt(i)!=str.charAt(j)) return false; } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
acfd473c081a28ee6a61e2c269f48c22
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); if(s.length() < 3) System.out.println("Impossible"); else { int[] alpha = new int[26]; int max = 0; for(int i = 0; i < s.length(); i++) { int c = s.charAt(i); alpha[c-97]++; max = Math.max(max, alpha[c-97]); } if(max >= s.length() - 1) System.out.println("Impossible"); else System.out.println(s.length() % 2 == 0 ? solveEven(s) : 2); } } static int solveEven(String s) { if(s.length() % 2 == 1) return 2; String l = s.substring(0, s.length()/2); String r = s.substring(s.length()/2); if(!l.equals(r)) return 1; return solveEven(l); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
bb283fcc8ba97608992d4082a51f8370
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class D implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { String str = scn.next(); char[] arr = str.toCharArray(); int n = arr.length; RollingHashFactory rhf = new RollingHashFactory(2, n, new Random()); RollingHash rh = new RollingHash(n, rhf); for (char ch : arr) { rh.add(ch); } arr = (str + str).toCharArray(); int ans = -1; if (n % 2 == 0) { for (int i = 0; i < n / 2; i++) { int l = 0, r = i + 1; long h1 = rh.queryTwin(l, r); l = n - i - 1; r = n; long h2 = rh.queryTwin(l, r); if (h1 != h2) { if(i + 1 == n / 2) { ans = 1; } else { ans = 2; } break; } } if(ans != 1) { for(int i = 1; i < n; i++) { int l = i, r = n + i - 1; int l1 = 0, r1 = n - 1; boolean diff = false; while(l <= r) { if(arr[l] != arr[r]) { l = -1; break; } if(arr[l] != arr[l1] || arr[r] != arr[r1]) { diff = true; } l++; r--; l1++; r1--; } if(l != -1 && diff) { ans = 1; break; } } } } else { for (int i = 0; i < n / 2; i++) { int l = 0, r = i + 1; long h1 = rh.queryTwin(l, r); l = n - i - 1; r = n; long h2 = rh.queryTwin(l, r); if (h1 != h2) { ans = 2; break; } } if(ans != 1) { for(int i = 1; i < n; i++) { int l = i, r = n + i - 1; int l1 = 0, r1 = n - 1; boolean diff = false; while(l <= r) { if(arr[l] != arr[r]) { l = -1; break; } if(arr[l] != arr[l1] || arr[r] != arr[r1]) { diff = true; } l++; r--; l1++; r1--; } if(l != -1 && diff) { ans = 1; break; } } } } if (ans == -1) { out.println("Impossible"); } else { out.println(ans); } } public class RollingHash { public RollingHashFactory rhf; public long[][] buf; public int p; public RollingHash(int bufsize, RollingHashFactory rhf) { buf = new long[rhf.deg][bufsize + 1]; this.rhf = rhf; this.p = 1; } public void add(int c) { for (int i = 0; i < rhf.deg; i++) buf[i][p] = (buf[i][p - 1] * rhf.muls[i] + c) % rhf.mods[i]; p++; } public void addr(int c) { for (int i = 0; i < rhf.deg; i++) buf[i][p] = (buf[i][p - 1] + rhf.powers[i][p - 1] * c) % rhf.mods[i]; p++; } public long queryTwin(int r) { return buf[0][r] << 32 | buf[1][r]; } public long queryTwin(int l, int r) { assert l <= r; assert rhf.deg == 2; long h = 0; for (int i = 0; i < rhf.deg; i++) { long v = (buf[i][r] - buf[i][l] * rhf.powers[i][r - l]) % rhf.mods[i]; if (v < 0) v += rhf.mods[i]; h = h << 32 | v; } return h; } public long[] query(int l, int r) { assert l <= r; long[] h = new long[rhf.deg]; for (int i = 0; i < rhf.deg; i++) { h[i] = (buf[i][r] - buf[i][l] * rhf.powers[i][r - l]) % rhf.mods[i]; if (h[i] < 0) h[i] += rhf.mods[i]; } return h; } public long add(long a, long b, int w, RollingHashFactory rhf) { assert rhf.deg == 2; long high = ((a >>> 32) * rhf.powers[0][w] + (b >>> 32)) % rhf.mods[0]; long low = ((long) (int) a * rhf.powers[1][w] + (int) b) % rhf.mods[1]; return high << 32 | low; } } public class RollingHashFactory { public int[] mods; public int[] muls; public long[][] powers; public int deg; public RollingHashFactory(int deg, int n, Random gen) { this.deg = deg; mods = new int[deg]; muls = new int[deg]; for (int i = 0; i < deg; i++) { mods[i] = BigInteger.probablePrime(30, gen).intValue(); muls[i] = BigInteger.probablePrime(30, gen).intValue(); } muls[0] = 100; mods[0] = 1000000007; powers = new long[deg][n + 1]; for (int i = 0; i < deg; i++) { powers[i][0] = 1; for (int j = 1; j <= n; j++) { powers[i][j] = powers[i][j - 1] * muls[i] % mods[i]; } } } } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new D(), "1", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } 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); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } 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); } 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; } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
6669690b53f04fe97eb848b4ce4f7c12
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class D{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int divide(int l,String s) { boolean pal = true; for (int i = 0; i < l / 2; i++) { if (s.charAt(i) != s.charAt(l - i - 1)) { pal = false; break; } } if (!pal) { return 1; } else if (l % 2 == 1) { return 2; } else { return divide(l / 2,s); } } public static void main(String[] args) { OutputStream outputStream = System.out; FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(outputStream); String s = sc.nextLine(); boolean same = true; for(int i = 1; i < s.length()/2; i++) { if(s.charAt(i) != s.charAt(i-1)) { same = false; break; } } if(same == true) { out.println("Impossible"); out.close(); return; } out.println(divide(s.length(),s)); out.close(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
7da929b97037d24d92471caca721532c
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ 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); DSashaAndOneMoreName solver = new DSashaAndOneMoreName(); solver.solve(1, in, out); out.close(); } static class DSashaAndOneMoreName { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.nextString(); int cnt = 0; int[] cntt = new int[200]; for (int i = 0; i < s.length(); i++) { if (cntt[s.charAt(i)] == 0) { cnt++; } cntt[s.charAt(i)]++; } if (cnt == 1) { out.println("Impossible"); return; } if (cnt == 2) { if (cntt[s.charAt(s.length() / 2)] == 1) { out.println("Impossible"); return; } } for (int i = 1; i < s.length(); i++) { String newS = s.substring(i) + s.substring(0, i); if (ch(newS) && !s.equals(newS)) { out.println(1); return; } } out.println(2); } private boolean ch(String newS) { for (int i = 0; i < newS.length(); i++) { if (newS.charAt(i) != newS.charAt(newS.length() - i - 1)) return false; } return true; } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextString() { int c; while (isSpaceChar(c = read())) ; StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = read())) result.appendCodePoint(c); return result.toString(); } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
6402a8ef50cb8904ac878ee3c9cd453b
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.next(); boolean[][] pal = new boolean[s.length()][s.length()]; for (int i = 0; i < s.length(); i++) { pal[i][i] = true; } for (int i = 1; i < s.length(); i++) { if (s.charAt(i - 1) == s.charAt(i)) { pal[i - 1][i] = true; } } for (int len = 3; len < s.length(); len++) { for (int first = 0; first < s.length(); first++) { int last = first + len - 1; if (last >= s.length()) break; if (s.charAt(first) == s.charAt(last) && pal[first + 1][last - 1]) { pal[first][last] = true; } } } if (check1(s)) { out.println(1); return; } if (check2(s, pal)) { out.println(2); return; } out.println("Impossible"); } boolean check1(String s) { if (s.length() % 2 == 1) return false; for (int i = 0; i < s.length(); i++) { loop: { for (int j = 0; j < s.length(); j++) { if (s.charAt((j - i + s.length()) % s.length()) != s.charAt((s.length() - 1 - j - i + s.length()) % s.length())) { break loop; } } for (int j = 0; j < s.length(); j++) { if (s.charAt(j) != s.charAt((j - i + s.length()) % s.length())) { return true; } } } } return false; } boolean check2(String s, boolean[][] pal) { for (int i = 0; i < s.length() / 2; i++) { if (!pal[0][i]) { return true; } } return false; } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
2d230b03bea8402649ff33b2d3ab0b76
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; public class Solution{ private static boolean isPalindrome(StringBuffer buffer){ for(int i=0, j=buffer.length()-1; i<j; i++, j--){ if(buffer.charAt(i) != buffer.charAt(j)) return false; } return true; } private static boolean check(StringBuffer buffer, String str){ //System.out.println(buffer); return !buffer.toString().equals(str) && isPalindrome(buffer); //System.out.println(buffer); } public static void main(String args[]){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); StringBuffer buffer = new StringBuffer(s); int n = s.length(); for(int i=0; i<n-1; i++){ char k = buffer.charAt(0); buffer.deleteCharAt(0); buffer.append(k); if(check(buffer, s)){ System.out.println(1); System.exit(0); } } for(int i=1, j=n-2; i<j; i++, j--){ if(s.charAt(i) != s.charAt(i-1)){ System.out.println(2); System.exit(0); } } System.out.println("Impossible"); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
bf4c30f15b1bde070e60801ad91c4a0a
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); String s = reader.next(); if(anyAnswer(s)){ System.out.println(process(new StringBuilder(s)) ? 1 : 2); } else { System.out.println("Impossible"); } } private static boolean anyAnswer(String s){ int diffChs = 0; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) != s.charAt(0)){ diffChs++; } } return diffChs > 1; } private static boolean process(StringBuilder s){ int n = s.length(); StringBuilder t = new StringBuilder(s); char ch; for(int i = 0; i < n; i++) { ch = t.charAt(n - 1); t.insert(0, ch); t.deleteCharAt(n); if (!checkSB(s,t) && isPalindrome(t)) { return true; } } return false; } private static boolean checkSB(StringBuilder s, StringBuilder t){ if(s.length() != t.length()){ return false; } for(int i = 0; i < s.length(); i++){ if(s.charAt(i) != t.charAt(i)){ return false; } } return true; } private static boolean isPalindrome(StringBuilder s){ for(int i = 0, j = s.length() - 1; i <= j; i++, j--){ if(s.charAt(i) != s.charAt(j)){ return false; } } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
07b635d193e6dbfcc2c6fd4d5fea1cb7
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; public class SashaAndOneMoreName { public static void main (String [] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); if (possible(line)) { StringBuffer sb = new StringBuffer(line); for (int i = 1; i < line.length(); i++) { sb.insert(0, sb.charAt(sb.length() - 1)); sb.deleteCharAt(sb.length() - 1); if (pallindrome(sb.toString()) && !sb.toString().equals(line)) { System.out.println(1); return; } } if (line.length() % 2 == 0 && !pallindrome(line.substring(0, line.length() /2))) System.out.println(1); else System.out.println(2); }else { System.out.println("Impossible"); } } public static boolean possible (String line) { char c = line.charAt(0); for (int i = 1; i < line.length(); i++) { if (line.charAt(i) != c && !(line.length() % 2 == 1 && i == line.length() /2)) return true; } return false; } public static boolean pallindrome (String line) { for (int i = 0; i < line.length() / 2; i++) { if (line.charAt(i) != line.charAt((line.length() - 1) - i)) return false; } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
d1aed896a718d28819bf4c6cb583ddb5
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; public class ACM { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); if (s.length() == 1) { System.out.print("Impossible"); } else { if (checkSame(s.substring((s.length() + 1) / 2))) { System.out.print("Impossible"); } else { System.out.print(cal(s)); } } } private static long cal(String s) { int sLen = s.length(); if (sLen % 2 == 0) { return cal2(s) + 1; } else { return 2; } } private static long cal2(String s) { if (s.length() == 1) { return 0; } String pre = s.substring(0, s.length() / 2); String suf = s.substring(s.length() / 2); if (pre.equals(suf)) { if (suf.length() % 2 == 0) { return cal2(suf); } else { return 1; } } else { return 0; } } private static boolean checkSame(String s) { for (int i = 1; i < s.length(); ++i) { if (s.charAt(i) != s.charAt(i - 1)) { return false; } } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
4d7cac2f039225a67918c0672e6ff2ba
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; 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.util.regex.Pattern; 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); DSashaAndOneMoreName solver = new DSashaAndOneMoreName(); solver.solve(1, in, out); out.close(); } static class DSashaAndOneMoreName { private static final String NO = "Impossible"; public void solve(int testNumber, LightScanner in, LightWriter out) { Debug.enable("src"); String s = in.string(); int n = s.length(); if (n % 2 == 0) { for (int i = 1; i < n; i++) { String low = s.substring(i, n), high = s.substring(0, i); String t = low + high; //System.out.println("Testing2(" + i + "): " + low + "-" + high); if (!s.equals(t)) { String r = new StringBuilder(t.substring(0, n / 2)).reverse().toString(); if (r.equals(t.substring(n / 2, n))) { out.ans(1).ln(); return; } } } } for (int i = 1; i <= n / 2; i++) { String t = s.substring(n - i, n) + s.substring(i, n - i) + s.substring(0, i); //System.out.println("Testing("+i+"): " + t); if (!s.equals(t)) { out.ans(2).ln(); return; } } out.ans(NO).ln(); } } static class LightScanner { 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(); } } static class Debug { private static final String DEBUG_CALL_PATTERN = "^.+\\.debug\\((.+)\\);.*$"; private static Pattern debugRegex; private static boolean enabled = false; private static String src; public static void enable(String s) { enabled = true; src = s; if (debugRegex == null) { debugRegex = Pattern.compile(DEBUG_CALL_PATTERN); } } } 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 BufferedWriter(new OutputStreamWriter(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); } } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
cc35d6d902274abd8a74b346d2283cf6
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); Integer.parseInt(st.nextToken()); Long.parseLong(st.nextToken()); Scanner sc = new Scanner(System.in); */ public class issam3{ public static class Palindrome { int[] p; int n; Palindrome(String str) { char[] s = preProcess(str).toCharArray(); n = s.length; p = new int[n]; LongestPalindrome(s); } String preProcess(String str) { int len = str.length(); if (len == 0) return "^$"; StringBuilder s = new StringBuilder("^"); for (int i = 0; i < len; i++) { s.append("#" + str.charAt(i)); } s.append("#$"); return s.toString(); } void LongestPalindrome(char[] s) { int id = 0, mx = 0; for (int i = 1; i < n - 1; i++) { p[i] = (mx > i) ? Math.min(p[2 * id - i], mx - i) : 0; while (s[i + 1 + p[i]] == s[i - 1 - p[i]]) p[i]++; if (i + p[i] > mx) { mx = i + p[i]; id = i; } } } int getOdd(int i) { return p[(i + 1) * 2]; } int getEven(int i) { return p[(i + 1) * 2 + 1]; } } public static boolean not(char[] c,int k){ for(int i=k;i<n;i++){ if(c[i]!=c[i-k]) return true; } for(int i=0;i<k;i++){ if(c[i]!=c[n-k+i]) return true; } return false; } public static int n; public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); String s = sc.next(); n = s.length(); if(n==1){ System.out.println("Impossible"); }else{ char[] c = s.toCharArray(); boolean ok = true; char d = c[0]; for(int i=1;i<n;i++){ if(n%2==1&&i==n/2) continue; if(c[i]!=c[0]){ ok = false; break; } } if(ok) System.out.println("Impossible"); else{ int k = 2; if(n%2==0){ Palindrome p = new Palindrome(s); for(int i=0;i<n/2-1;i++){ int r = i+i+2; if(p.getEven(i)==r&&p.getEven(r+(n-r-1)/2)==n-r&&not(c,r+(n-r)/2)){ k = 1; break; } } if(!s.substring(0,n/2).equals(s.substring(n/2,n))) k =1; } System.out.println(k); } } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
8c23b660e7821d625ed378d1cfbb023b
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C1113D { private static BufferedReader in; private static BufferedWriter out; private static List<Integer>[] list; private static int[] arr; private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static boolean[] used; public static void main(String[] args) throws IOException { open(); String s = readString(); char c = s.charAt(0); boolean all = true; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != c) { all = false; break; } } if (all) { out.write("Impossible\n"); } else { int n = s.length(); if (n % 2 == 0) { String sub1 = s.substring(0, n / 2); if (isReverse(sub1)) { if (check(s)) { out.write("1\n"); } else { out.write("2\n"); } } else { out.write("1\n"); } } else { if (check(s)) { out.write("1\n"); } else { char cc = s.charAt(0); boolean al = true; for (int i = 0; i < n; i++) { if (i != n / 2) { if (s.charAt(i) != cc) { al = false; break; } } } if (al) { out.write("Impossible\n"); } else { out.write("2\n"); } } } } close(); } private static boolean check(String s) { int n = s.length(); for (int i = 0; i < n - 1; i++) { boolean yes = true; for (int k = 0; k <= n / 2; k++) { int left = i - k; int right = i + 1 + k; if (left < 0) { left = n + left; } if (right >= n) { right = right - n; } if (s.charAt(left) != s.charAt(right)) { yes = false; break; } } if (yes) { String sb1 = s.substring(i + 1); String sb2 = s.substring(0, i + 1); if (!s.equals(sb1 + sb2)) { return true; } } } return false; } private static boolean isReverse(String s) { int n = s.length(); for (int i = 0; i < n; i++) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException { List<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int[] e = readInts(); list[e[0]].add(e[1]); list[e[1]].add(e[0]); } return list; } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
a2e6323b05c9f607dd90fe60ca2c1cbf
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; import java.io.*; public class Main { static int n, numDist = 0; static String in; static char[] arr; static int[] freq = new int[26]; public static void main (String[] args){ Scanner sc = new Scanner(System.in); in = sc.next(); arr = in.toCharArray(); n = arr.length; for(int i = 0; i < n; ++i){ int idx = (int)(arr[i] - 'a'); if(++freq[idx] == 1) ++numDist; } int one = -1; for(int i = 0; i < 26; ++i){ if(freq[i] == 1) one = i; } if(numDist == 1 || (numDist == 2 && n % 2 == 1 && (int)(arr[n / 2] - 'a') == one)){ System.out.println("Impossible"); return; } if(check()) System.out.println(1); else System.out.println(2); if(n > -1) return; //if even and first half isnt palindrome if(n % 2 == 0){ String a = in.substring(0, n / 2); boolean palin = true; for(int i = 0; i < a.length(); ++i){ if(a.charAt(i) != a.charAt(a.length() - 1 - i)) palin = false; } if(!palin){ System.out.println(1); return; } } //if first half is palindrome and is even, then you can cut off the first 1/4 and put it at the back if(n % 4 == 0){ System.out.println(1); return; } System.out.println(2); } static boolean check(){ //try every break point for(int i = 1; i < n; ++i){ String s = in.substring(i, n) + in.substring(0, i); if(palin(s) && !s.equals(in)) return true; } return false; } static boolean palin(String s){ for(int i = 0; i < s.length() / 2; ++i){ if(s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true; } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
016548929fc13e36535a330b6d7d8906
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); Integer.parseInt(st.nextToken()); Long.parseLong(st.nextToken()); Scanner sc = new Scanner(System.in); */ public class issam3{ public static class Palindrome { int[] p; int n; Palindrome(String str) { char[] s = preProcess(str).toCharArray(); n = s.length; p = new int[n]; LongestPalindrome(s); } String preProcess(String str) { int len = str.length(); if (len == 0) return "^$"; StringBuilder s = new StringBuilder("^"); for (int i = 0; i < len; i++) { s.append("#" + str.charAt(i)); } s.append("#$"); return s.toString(); } void LongestPalindrome(char[] s) { int id = 0, mx = 0; for (int i = 1; i < n - 1; i++) { p[i] = (mx > i) ? Math.min(p[2 * id - i], mx - i) : 0; while (s[i + 1 + p[i]] == s[i - 1 - p[i]]) p[i]++; if (i + p[i] > mx) { mx = i + p[i]; id = i; } } } int getOdd(int i) { return p[(i + 1) * 2]; } int getEven(int i) { return p[(i + 1) * 2 + 1]; } } public static boolean not(char[] c,int k){ for(int i=k;i<n;i++){ if(c[i]!=c[i-k]) return true; } for(int i=0;i<k;i++){ if(c[i]!=c[n-k+i]) return true; } return false; } public static int n; public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); String s = sc.next(); n = s.length(); if(n==1){ System.out.println("Impossible"); }else{ char[] c = s.toCharArray(); boolean ok = true; char d = c[0]; for(int i=1;i<n;i++){ if(n%2==1&&i==n/2) continue; if(c[i]!=c[0]){ ok = false; break; } } if(ok) System.out.println("Impossible"); else{ int k = 2; if(n%2==0){ Palindrome p = new Palindrome(s); for(int i=0;i<n/2-1;i++){ int r = i+i+2; if(p.getEven(i)==r&&p.getEven(r+(n-r-1)/2)==n-r&&not(c,r+(n-r)/2)){ k = 1; break; } } if(!s.substring(0,n/2).equals(s.substring(n/2,n))) k =1; } System.out.println(k); } } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
2f1ebb430b2895b10bc84b93c80b863c
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.Scanner; public class oneMore { public static void main(String[] args) { Scanner scan=new Scanner(System.in); String s=scan.next(); //ewwwwwwwwwww no please no hashing :( //1 cut try all cutting places //2 cuts try removing prefix/suffix, it will work iff they are not palindromes //else answer is impossible (?) n=s.length(); char[] c=s.toCharArray(); for(int i=1;i<n;i++) { if(go(c,i)) { System.out.println(1); return; } } int prev=-1, x=0; while(x<n/2) { if(prev!=-1&&prev!=s.charAt(x)-'a') { System.out.println(2); return; } prev=s.charAt(x)-'a'; x++; } System.out.println("Impossible"); } static int n; public static boolean go(char[] c, int x) { boolean go=false, dif=false, good=false; int prev=-1; int ct=0; for(int i=x,j=(x-1+n)%n;;i=(i+1)%n,j=(j-1+n)%n) { if(c[i]!=c[j]) return false; if(c[i]!=c[ct]) good=true; if(ct==n/2) break; go=true; if(prev!=-1&&c[i]-'a'!=prev) dif=true; prev=c[i]-'a'; ct++; } return dif&good; } } /* abaaba print 1 answer 2 */
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
684a17b6d5c2195877da66c2ba14e3a1
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.Scanner; public class SashaAndOneMoreName { public static void main(String[] args) { //answer is always at most 2 (or inf) Scanner sc = new Scanner(System.in); char[] str = sc.nextLine().toCharArray(); int n = str.length; sc.close(); //check if impossible if (n == 1) { System.out.println("Impossible"); return; } boolean possible = false; int first = str[(n + 1) / 2]; for (int i = 0; i < n / 2; i++) { if (str[i] != first) { possible = true; } } if (!possible) { System.out.println("Impossible"); return; } // split the string, then glue it back together such that the new // middle is at newMid for (int newMid = 0; newMid < n; newMid++) { // check that this string is different boolean isDiff = false; for (int i = 0; i < n; i++) { if (str[(i + n / 2) % n] != str[(newMid + i) % n]) { isDiff = true; } } if (!isDiff) { continue; } boolean works = true; if (n % 2 == 1) { for (int i = 1; i <= n / 2; i++) { if (str[(newMid + i) % n] != str[(n + newMid - i) % n]) { works = false; break; } } } else { for (int i = 0; i < str.length / 2; i++) { if (str[(newMid + i) % n] != str[(n + newMid - i - 1) % n]) { works = false; break; } } } if (works) { System.out.println(1); return; } } System.out.println(2); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
9e50fc7641020cedb6367ae4b7377985
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.util.*; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(); boolean pos = false; for (int i = 0; 2*(i+1) <= n; i++) { if (s.charAt(i) != s.charAt(0)) { pos = true; break; } } if (!pos) { System.out.println("Impossible"); } else { for (int i = 1; i < n; i++) { if (pos(s, i)) { System.out.println(1); return; } } System.out.println(2); } } static boolean pos(String s, int i) { for (int j = 0; 2*j < s.length(); j++) { if (c(s, i, j) != c(s, i, s.length()-j-1)) { return false; } } for (int j = 0; j <= s.length()/2; j++) { if (c(s, i, j) != s.charAt(j)) { return true; } } return false; } static char c(String s, int i, int j) { return s.charAt((j+i)%s.length()); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
c2fcf8113f859ec695f092ee0bfd5496
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code29 { public static boolean ispalindrome(String s) { int len = s.length(); int i = 0; int j = len - 1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } public static int solve(String s) { if(!ispalindrome(s)) return 1; if(s.length()%2==1) return 2; return solve(s.substring(0,s.length()/2)); } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); String s = in.nextLine(); int n = s.length(); int[] a = new int[26]; for(int i=0;i<s.length();i++) { a[s.charAt(i)-'a']++; } int max = Integer.MIN_VALUE; for(int i=0;i<26;i++) { max = Math.max(max,a[i]); } if(max>(n-2)) pw.print("Impossible"); else pw.print(solve(s)); pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return (Math.abs(p.x-x)==0 && Math.abs(p.y-y)==0); } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
f4e3124b67260307e96e539d488cdf71
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
//package baobab; import java.io.*; import java.util.*; public class D { public static void main(String[] args) { Solver solver = new Solver(); } static class Solver { IO io; public Solver() { this.io = new IO(); try { solve(); } catch (RuntimeException e) { if (!e.getMessage().equals("Clean exit")) { throw e; } } finally { io.close(); } } /****************************** START READING HERE ********************************/ String s; int n; void solve() { s = io.next(); n = s.length(); if (impossible()) { io.println("Impossible"); return; } if (n%2 != 0) { io.println(2); return; } for (int cut=0; cut<n/2; cut++) { if (okCut(cut)) { io.println(1); return; } } io.println(2); } boolean impossible() { char prev = s.charAt(0); int i=0; int j=n-1; while (i < j) { char c = s.charAt(i); if (c != prev) return false; c = s.charAt(j); if (c != prev) return false; i++; j--; } return true; } boolean okCut(int cut) { int i=cut+1; int j=cut; for (int comparison=0; comparison<n/2; comparison++) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; if (j < 0) j += n; } i=0; j=cut+1; for (int comparison=0; comparison<n; comparison++) { if (s.charAt(i) != s.charAt(j)) return true; i++; j++; j%=n; } return false; } /************************** UTILITY CODE BELOW THIS LINE **************************/ long MOD = (long)1e9 + 7; boolean closeToZero(double v) { // Check if double is close to zero, considering precision issues. return Math.abs(v) <= 0.0000000001; } void draw(boolean[][] d) { System.out.print(" "); for (int x=0; x<d[0].length; x++) { System.out.print(" " + x + " "); } System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print((d[y][x] ? "[x]" : "[ ]")); } System.out.println(""); } } void draw(int[][] d) { int max = 1; for (int y=0; y<d.length; y++) { for (int x=0; x<d[0].length; x++) { max = Math.max(max, ("" + d[y][x]).length()); } } System.out.print(" "); String format = "%" + (max+2) + "s"; for (int x=0; x<d[0].length; x++) { System.out.print(String.format(format, x) + " "); } format = "%" + (max) + "s"; System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print(" [" + String.format(format, (d[y][x])) + "]"); } System.out.println(""); } } void draw(long[][] d) { int max = 1; for (int y=0; y<d.length; y++) { for (int x=0; x<d[0].length; x++) { max = Math.max(max, ("" + d[y][x]).length()); } } System.out.print(" "); String format = "%" + (max+2) + "s"; for (int x=0; x<d[0].length; x++) { System.out.print(String.format(format, x) + " "); } format = "%" + (max) + "s"; System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print(" [" + String.format(format, (d[y][x])) + "]"); } System.out.println(""); } } class IDval implements Comparable<IDval> { int id; long val; public IDval(int id, long val) { this.val = val; this.id = id; } @Override public int compareTo(IDval o) { if (this.val < o.val) return -1; if (this.val > o.val) return 1; return this.id - o.id; } } private class ElementCounter { private HashMap<Long, Integer> elements; public ElementCounter() { elements = new HashMap<>(); } public void add(long element) { int count = 1; Integer prev = elements.get(element); if (prev != null) count += prev; elements.put(element, count); } public void remove(long element) { int count = elements.remove(element); count--; if (count > 0) elements.put(element, count); } public int get(long element) { Integer val = elements.get(element); if (val == null) return 0; return val; } public int size() { return elements.size(); } } class StringCounter { HashMap<String, Integer> elements; public StringCounter() { elements = new HashMap<>(); } public void add(String identifier) { int count = 1; Integer prev = elements.get(identifier); if (prev != null) count += prev; elements.put(identifier, count); } public void remove(String identifier) { int count = elements.remove(identifier); count--; if (count > 0) elements.put(identifier, count); } public long get(String identifier) { Integer val = elements.get(identifier); if (val == null) return 0; return val; } public int size() { return elements.size(); } } class DisjointSet { /** Union Find / Disjoint Set data structure. */ int[] size; int[] parent; int componentCount; public DisjointSet(int n) { componentCount = n; size = new int[n]; parent = new int[n]; for (int i=0; i<n; i++) parent[i] = i; for (int i=0; i<n; i++) size[i] = 1; } public void join(int a, int b) { /* Find roots */ int rootA = parent[a]; int rootB = parent[b]; while (rootA != parent[rootA]) rootA = parent[rootA]; while (rootB != parent[rootB]) rootB = parent[rootB]; if (rootA == rootB) { /* Already in the same set */ return; } /* Merge smaller set into larger set. */ if (size[rootA] > size[rootB]) { size[rootA] += size[rootB]; parent[rootB] = rootA; } else { size[rootB] += size[rootA]; parent[rootA] = rootB; } componentCount--; } } class Trie { int N; int Z; int nextFreeId; int[][] pointers; boolean[] end; /** maxLenSum = maximum possible sum of length of words */ public Trie(int maxLenSum, int alphabetSize) { this.N = maxLenSum; this.Z = alphabetSize; this.nextFreeId = 1; pointers = new int[N+1][alphabetSize]; end = new boolean[N+1]; } public void addWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) { next = nextFreeId++; pointers[curr][c] = next; } curr = next; } end[curr] = true; } public boolean hasWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) return false; curr = next; } return end[curr]; } } private static class Prob { /** For heavy calculations on probabilities, this class * provides more accuracy & efficiency than doubles. * Math explained: https://en.wikipedia.org/wiki/Log_probability * Quick start: * - Instantiate probabilities, eg. Prob a = new Prob(0.75) * - add(), multiply() return new objects, can perform on nulls & NaNs. * - get() returns probability as a readable double */ /** Logarithmized probability. Note: 0% represented by logP NaN. */ private double logP; /** Construct instance with real probability. */ public Prob(double real) { if (real > 0) this.logP = Math.log(real); else this.logP = Double.NaN; } /** Construct instance with already logarithmized value. */ static boolean dontLogAgain = true; public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) { this.logP = logP; } /** Returns real probability as a double. */ public double get() { return Math.exp(logP); } @Override public String toString() { return ""+get(); } /***************** STATIC METHODS BELOW ********************/ /** Note: returns NaN only when a && b are both NaN/null. */ public static Prob add(Prob a, Prob b) { if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); if (nullOrNaN(a)) return copy(b); if (nullOrNaN(b)) return copy(a); double x = Math.max(a.logP, b.logP); double y = Math.min(a.logP, b.logP); double sum = x + Math.log(1 + Math.exp(y - x)); return new Prob(sum, dontLogAgain); } /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */ public static Prob multiply(Prob a, Prob b) { if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); return new Prob(a.logP + b.logP, dontLogAgain); } /** Returns true if p is null or NaN. */ private static boolean nullOrNaN(Prob p) { return (p == null || Double.isNaN(p.logP)); } /** Returns a new instance with the same value as original. */ private static Prob copy(Prob original) { return new Prob(original.logP, dontLogAgain); } } class Binary implements Comparable<Binary> { /** * Use example: Binary b = new Binary(Long.toBinaryString(53249834L)); * * When manipulating small binary strings, instantiate new Binary(string) * When just reading large binary strings, instantiate new Binary(string,true) * get(int i) returns a character '1' or '0', not an int. */ private boolean[] d; private int first; // Starting from left, the first (most remarkable) '1' public int length; public Binary(String binaryString) { this(binaryString, false); } public Binary(String binaryString, boolean initWithMinArraySize) { length = binaryString.length(); int size = Math.max(2*length, 1); first = length/4; if (initWithMinArraySize) { first = 0; size = Math.max(length, 1); } d = new boolean[size]; for (int i=0; i<length; i++) { if (binaryString.charAt(i) == '1') d[i+first] = true; } } public void addFirst(char c) { if (first-1 < 0) doubleArraySize(); first--; d[first] = (c == '1' ? true : false); length++; } public void addLast(char c) { if (first+length >= d.length) doubleArraySize(); d[first+length] = (c == '1' ? true : false); length++; } private void doubleArraySize() { boolean[] bigArray = new boolean[(d.length+1) * 2]; int newFirst = bigArray.length / 4; for (int i=0; i<length; i++) { bigArray[i + newFirst] = d[i + first]; } first = newFirst; d = bigArray; } public boolean flip(int i) { boolean value = (this.d[first+i] ? false : true); this.d[first+i] = value; return value; } public void set(int i, char c) { boolean value = (c == '1' ? true : false); this.d[first+i] = value; } public char get(int i) { return (this.d[first+i] ? '1' : '0'); } @Override public int compareTo(Binary o) { if (this.length != o.length) return this.length - o.length; int len = this.length; for (int i=0; i<len; i++) { int diff = this.get(i) - o.get(i); if (diff != 0) return diff; } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append(d[i+first] ? '1' : '0'); } return sb.toString(); } } /************************** Range queries **************************/ class FenwickMin { long n; long[] original; long[] bottomUp; long[] topDown; public FenwickMin(int n) { this.n = n; original = new long[n+2]; bottomUp = new long[n+2]; topDown = new long[n+2]; } public void set(int modifiedNode, long value) { long replaced = original[modifiedNode]; original[modifiedNode] = value; // Update left tree int i = modifiedNode; long v = value; while (i <= n) { if (v > bottomUp[i]) { if (replaced == bottomUp[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i-x; v = Math.min(v, bottomUp[child]); } } else break; } if (v == bottomUp[i]) break; bottomUp[i] = v; i += (i&-i); } // Update right tree i = modifiedNode; v = value; while (i > 0) { if (v > topDown[i]) { if (replaced == topDown[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i+x; if (child > n+1) break; v = Math.min(v, topDown[child]); } } else break; } if (v == topDown[i]) break; topDown[i] = v; i -= (i&-i); } } public long getMin(int a, int b) { long min = original[a]; int prev = a; int curr = prev + (prev&-prev); // parent right hand side while (curr <= b) { min = Math.min(min, topDown[prev]); // value from the other tree prev = curr; curr = prev + (prev&-prev);; } min = Math.min(min, original[prev]); prev = b; curr = prev - (prev&-prev); // parent left hand side while (curr >= a) { min = Math.min(min,bottomUp[prev]); // value from the other tree prev = curr; curr = prev - (prev&-prev); } return min; } } class FenwickSum { public long[] d; public FenwickSum(int n) { d=new long[n+1]; } /** a[0] must be unused. */ public FenwickSum(long[] a) { d=new long[a.length]; for (int i=1; i<a.length; i++) { modify(i, a[i]); } } /** Do not modify i=0. */ void modify(int i, long v) { while (i<d.length) { d[i] += v; // Move to next uplink on the RIGHT side of i i += (i&-i); } } /** Returns sum from a to b, *BOTH* inclusive. */ long getSum(int a, int b) { return getSum(b) - getSum(a-1); } private long getSum(int i) { long sum = 0; while (i>0) { sum += d[i]; // Move to next uplink on the LEFT side of i i -= (i&-i); } return sum; } } class SegmentTree { /* Provides log(n) operations for: * - Range query (sum, min or max) * - Range update ("+8 to all values between indexes 4 and 94") */ int N; long[] lazy; long[] sum; long[] min; long[] max; boolean supportSum; boolean supportMin; boolean supportMax; public SegmentTree(int n) { this(n, true, true, true); } public SegmentTree(int n, boolean supportSum, boolean supportMin, boolean supportMax) { for (N=2; N<n;) N*=2; this.lazy = new long[2*N]; this.supportSum = supportSum; this.supportMin = supportMin; this.supportMax = supportMax; if (this.supportSum) this.sum = new long[2*N]; if (this.supportMin) this.min = new long[2*N]; if (this.supportMax) this.max = new long[2*N]; } void modifyRange(long x, int a, int b) { modifyRec(a, b, 1, 0, N-1, x); } void setRange() { //TODO } long getSum(int a, int b) { return querySum(a, b, 1, 0, N-1); } long getMin(int a, int b) { return queryMin(a, b, 1, 0, N-1); } long getMax(int a, int b) { return queryMax(a, b, 1, 0, N-1); } private long querySum(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return 0; } if (wantedLeft == actualLeft && wantedRight == actualRight) { int count = wantedRight - wantedLeft + 1; return sum[i] + count * lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = querySum(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = querySum(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return left + right; } private long queryMin(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return Long.MAX_VALUE; } if (wantedLeft == actualLeft && wantedRight == actualRight) { return min[i] + lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = queryMin(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = queryMin(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return min(left, right); } private long queryMax(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return Long.MIN_VALUE; } if (wantedLeft == actualLeft && wantedRight == actualRight) { return max[i] + lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = queryMax(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = queryMax(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return max(left, right); } private void modifyRec(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight, long value) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return; } if (wantedLeft == actualLeft && wantedRight == actualRight) { lazy[i] += value; return; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; modifyRec(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1, value); modifyRec(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight, value); if (supportSum) sum[i] += value * (min(actualRight, wantedRight) - max(actualLeft, wantedLeft) + 1); if (supportMin) min[i] = min(min[2*i] + lazy[2*i], min[2*i+1] + lazy[2*i+1]); if (supportMax) max[i] = max(max[2*i] + lazy[2*i], max[2*i+1] + lazy[2*i+1]); } private void propagate(int i, int actualLeft, int actualRight) { lazy[2*i] += lazy[i]; lazy[2*i+1] += lazy[i]; if (supportSum) sum[i] += lazy[i] * (actualRight - actualLeft + 1); if (supportMin) min[i] += lazy[i]; if (supportMax) max[i] += lazy[i]; lazy[i] = 0; } } /***************************** Graphs *****************************/ List<Integer>[] toGraph(IO io, int n) { /* Trees only. */ List<Integer>[] g = new ArrayList[n+1]; for (int i=1; i<=n; i++) g[i] = new ArrayList<>(); for (int i=1; i<=n-1; i++) { int a = io.nextInt(); int b = io.nextInt(); g[a].add(b); g[b].add(a); } return g; } class Graph { int n; List<Integer>[] edges; public Graph(int n) { this.n = n; edges = new ArrayList[n+1]; for (int i=1; i<=n; i++) edges[i] = new ArrayList<>(); } void addBiEdge(int a, int b) { addEdge(a, b); addEdge(b, a); } void addEdge(int from, int to) { edges[from].add(to); } /*********** Strongly Connected Components (Kosaraju) ****************/ ArrayList<Integer>[] bacw; public int getCount() { bacw = new ArrayList[n+1]; for (int i=1; i<=n; i++) { bacw[i] = new ArrayList<Integer>(); } for (int a=1; a<=n; a++) { for (int b : edges[a]) { bacw[b].add(a); } } int count = 0; List<Integer> list = new ArrayList<Integer>(); boolean[] visited = new boolean[n+1]; for (int i=1; i<=n; i++) { dfsForward(i, visited, list); } visited = new boolean[n+1]; for (int i=n-1; i>=0; i--) { int node = list.get(i); if (visited[node]) continue; count++; dfsBackward(node, visited); } return count; } void dfsForward(int i, boolean[] visited, List<Integer> list) { if (visited[i]) return; visited[i] = true; for (int neighbor : edges[i]) { dfsForward(neighbor, visited, list); } list.add(i); } void dfsBackward(int i, boolean[] visited) { if (visited[i]) return; visited[i] = true; for (int neighbor : bacw[i]) { dfsBackward(neighbor, visited); } } /************************* Topological Order **********************/ int UNTOUCHED = 0; int FINISHED = 2; int INPROGRESS = 1; int[] vis; List<Integer> topoAns; // Returns nodes in topological order or null if cycle was found public List<Integer> topoSort() { topoAns = new ArrayList<>(); vis = new int[n+1]; for (int i=1; i<=n; i++) { if (!topoDFS(i)) return null; } Collections.reverse(topoAns); return topoAns; } boolean topoDFS(int curr) { Integer status = vis[curr]; if (status == null) status = UNTOUCHED; if (status == FINISHED) return true; if (status == INPROGRESS) { return false; } vis[curr] = INPROGRESS; for (int next : edges[curr]) { if (!topoDFS(next)) return false; } vis[curr] = FINISHED; topoAns.add(curr); return true; } } class LCAFinder { /* O(n log n) Initialize: new LCAFinder(graph) * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */ int[] nodes; int[] depths; int[] entries; int pointer; FenwickMin fenwick; public LCAFinder(List<Integer>[] graph) { this.nodes = new int[(int)10e6]; this.depths = new int[(int)10e6]; this.entries = new int[graph.length]; this.pointer = 1; boolean[] visited = new boolean[graph.length+1]; dfs(1, 0, graph, visited); fenwick = new FenwickMin(pointer-1); for (int i=1; i<pointer; i++) { fenwick.set(i, depths[i] * 1000000L + i); } } private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) { visited[node] = true; entries[node] = pointer; nodes[pointer] = node; depths[pointer] = depth; pointer++; for (int neighbor : graph[node]) { if (visited[neighbor]) continue; dfs(neighbor, depth+1, graph, visited); nodes[pointer] = node; depths[pointer] = depth; pointer++; } } public int find(int a, int b) { int left = entries[a]; int right = entries[b]; if (left > right) { int temp = left; left = right; right = temp; } long mixedBag = fenwick.getMin(left, right); int index = (int) (mixedBag % 1000000L); return nodes[index]; } } /**************************** Geometry ****************************/ class Point { int y; int x; public Point(int y, int x) { this.y = y; this.x = x; } } boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { // Returns true if segment 1-2 intersects segment 3-4 if (x1 == x2 && x3 == x4) { // Both segments are vertical if (x1 != x3) return false; if (min(y1,y2) < min(y3,y4)) { return max(y1,y2) >= min(y3,y4); } else { return max(y3,y4) >= min(y1,y2); } } if (x1 == x2) { // Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b double a34 = (y4-y3)/(x4-x3); double b34 = y3 - a34*x3; double y = a34 * x1 + b34; return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4); } if (x3 == x4) { // Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b double a12 = (y2-y1)/(x2-x1); double b12 = y1 - a12*x1; double y = a12 * x3 + b12; return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2); } double a12 = (y2-y1)/(x2-x1); double b12 = y1 - a12*x1; double a34 = (y4-y3)/(x4-x3); double b34 = y3 - a34*x3; if (closeToZero(a12 - a34)) { // Parallel lines return closeToZero(b12 - b34); } // Non parallel non vertical lines intersect at x. Is x part of both segments? double x = -(b12-b34)/(a12-a34); return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4); } boolean pointInsideRectangle(Point p, List<Point> r, boolean countBorderAsInside) { Point a = r.get(0); Point b = r.get(1); Point c = r.get(2); Point d = r.get(3); double apd = areaOfTriangle(a, p, d); double dpc = areaOfTriangle(d, p, c); double cpb = areaOfTriangle(c, p, b); double pba = areaOfTriangle(p, b, a); double sumOfAreas = apd + dpc + cpb + pba; if (closeToZero(sumOfAreas - areaOfRectangle(r))) { if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) { return countBorderAsInside; } return true; } return false; } double areaOfTriangle(Point a, Point b, Point c) { return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y)); } double areaOfRectangle(List<Point> r) { double side1xDiff = r.get(0).x - r.get(1).x; double side1yDiff = r.get(0).y - r.get(1).y; double side2xDiff = r.get(1).x - r.get(2).x; double side2yDiff = r.get(1).y - r.get(2).y; double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff); double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff); return side1 * side2; } boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) { double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return (closeToZero(areaTimes2)); } class PointToLineSegmentDistanceCalculator { // Just call this double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) { return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2)); } private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) { double l2 = dist2(x1,y1,x2,y2); if (l2 == 0) return dist2(point_x, point_y, x1, y1); double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2; if (t < 0) return dist2(point_x, point_y, x1, y1); if (t > 1) return dist2(point_x, point_y, x2, y2); double com_x = x1 + t * (x2 - x1); double com_y = y1 + t * (y2 - y1); return dist2(point_x, point_y, com_x, com_y); } private double dist2(double x1, double y1, double x2, double y2) { return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2); } } /****************************** Math ******************************/ long pow(long base, int exp) { if (exp == 0) return 1L; long x = pow(base, exp/2); long ans = x * x; if (exp % 2 != 0) ans *= base; return ans; } long gcd(long... v) { /** Chained calls to Euclidean algorithm. */ if (v.length == 1) return v[0]; long ans = gcd(v[1], v[0]); for (int i=2; i<v.length; i++) { ans = gcd(ans, v[i]); } return ans; } long gcd(long a, long b) { /** Euclidean algorithm. */ if (b == 0) return a; return gcd(b, a%b); } int[] generatePrimesUpTo(int last) { /* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */ int[] div = new int[last+1]; for (int x=2; x<=last; x++) { if (div[x] > 0) continue; for (int u=2*x; u<=last; u+=x) { div[u] = x; } } return div; } long lcm(long a, long b) { /** Least common multiple */ return a * b / gcd(a,b); } class BaseConverter { /* Palauttaa luvun esityksen kannassa base */ public String convert(Long number, int base) { return Long.toString(number, base); } /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */ public String convert(String number, int baseFrom, int baseTo) { return Long.toString(Long.parseLong(number, baseFrom), baseTo); } /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */ public long longify(String number, int baseFrom) { return Long.parseLong(number, baseFrom); } } class BinomialCoefficients { /** Total number of K sized unique combinations from pool of size N (unordered) N! / ( K! (N - K)! ) */ /** For simple queries where output fits in long. */ public long biCo(long n, long k) { long r = 1; if (k > n) return 0; for (long d = 1; d <= k; d++) { r *= n--; r /= d; } return r; } /** For multiple queries with same n, different k. */ public long[] precalcBinomialCoefficientsK(int n, int maxK) { long v[] = new long[maxK+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,maxK); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle } } return v; } /** When output needs % MOD. */ public long[] precalcBinomialCoefficientsK(int n, int k, long M) { long v[] = new long[k+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,k); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle v[j] %= M; } } return v; } } int invertNumber(int a, int k) { // Inverts the binary representation of a, using only k last bits e.g. 01101 -> 10010 int inv32k = ~a; int mask = 1; for (int i = 1; i < k; ++i) mask |= mask << 1; return inv32k & mask; } /**************************** Strings ****************************/ class Zalgo { public int pisinEsiintyma(String haku, String kohde) { char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); int max = 0; for (int i=haku.length(); i<z.length; i++) { max = Math.max(max, z[i]); } return max; } public int[] toZarray(char[] s) { int n = s.length; int[] z = new int[n]; int a = 0, b = 0; for (int i = 1; i < n; i++) { if (i > b) { for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++; } else { z[i] = z[i - a]; if (i + z[i - a] > b) { for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++; a = i; b = i + z[i] - 1; } } } return z; } public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) { // this is alternative use case char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); List<Integer> indexes = new ArrayList<>(); for (int i=haku.length(); i<z.length; i++) { if (z[i] < haku.length()) continue; indexes.add(i); } return indexes; } } class StringHasher { class HashedString { long[] hashes; long[] modifiers; public HashedString(long[] hashes, long[] modifiers) { this.hashes = hashes; this.modifiers = modifiers; } } long P; long M; public StringHasher() { initializePandM(); } HashedString hashString(String s) { int n = s.length(); long[] hashes = new long[n]; long[] modifiers = new long[n]; hashes[0] = s.charAt(0); modifiers[0] = 1; for (int i=1; i<n; i++) { hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; modifiers[i] = (modifiers[i-1] * P) % M; } return new HashedString(hashes, modifiers); } /** * Indices are inclusive. */ long getHash(HashedString hashedString, int startIndex, int endIndex) { long[] hashes = hashedString.hashes; long[] modifiers = hashedString.modifiers; long result = hashes[endIndex]; if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M; if (result < 0) result += M; return result; } // Less interesting methods below /** * Efficient for 2 input parameter strings in particular. */ HashedString[] hashString(String first, String second) { HashedString[] array = new HashedString[2]; int n = first.length(); long[] modifiers = new long[n]; modifiers[0] = 1; long[] firstHashes = new long[n]; firstHashes[0] = first.charAt(0); array[0] = new HashedString(firstHashes, modifiers); long[] secondHashes = new long[n]; secondHashes[0] = second.charAt(0); array[1] = new HashedString(secondHashes, modifiers); for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M; secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M; } return array; } /** * Efficient for 3+ strings * More efficient than multiple hashString calls IF strings are same length. */ HashedString[] hashString(String... strings) { HashedString[] array = new HashedString[strings.length]; int n = strings[0].length(); long[] modifiers = new long[n]; modifiers[0] = 1; for (int j=0; j<strings.length; j++) { // if all strings are not same length, defer work to another method if (strings[j].length() != n) { for (int i=0; i<n; i++) { array[i] = hashString(strings[i]); } return array; } // otherwise initialize stuff long[] hashes = new long[n]; hashes[0] = strings[j].charAt(0); array[j] = new HashedString(hashes, modifiers); } for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; for (int j=0; j<strings.length; j++) { String s = strings[j]; long[] hashes = array[j].hashes; hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; } } return array; } void initializePandM() { ArrayList<Long> modOptions = new ArrayList<>(20); modOptions.add(353873237L); modOptions.add(353875897L); modOptions.add(353878703L); modOptions.add(353882671L); modOptions.add(353885303L); modOptions.add(353888377L); modOptions.add(353893457L); P = modOptions.get(new Random().nextInt(modOptions.size())); modOptions.clear(); modOptions.add(452940277L); modOptions.add(452947687L); modOptions.add(464478431L); modOptions.add(468098221L); modOptions.add(470374601L); modOptions.add(472879717L); modOptions.add(472881973L); M = modOptions.get(new Random().nextInt(modOptions.size())); } } int editDistance(String a, String b) { a = "#"+a; b = "#"+b; int n = a.length(); int m = b.length(); int[][] dp = new int[n+1][m+1]; for (int y=0; y<=n; y++) { for (int x=0; x<=m; x++) { if (y == 0) dp[y][x] = x; else if (x == 0) dp[y][x] = y; else { int e1 = dp[y-1][x] + 1; int e2 = dp[y][x-1] + 1; int e3 = dp[y-1][x-1] + (a.charAt(y-1) != b.charAt(x-1) ? 1 : 0); dp[y][x] = min(e1, e2, e3); } } } return dp[n][m]; } /*************************** Technical ***************************/ private class IO extends PrintWriter { private InputStreamReader r; private static final int BUFSIZE = 1 << 15; private char[] buf; private int bufc; private int bufi; private StringBuilder sb; public IO() { super(new BufferedOutputStream(System.out)); r = new InputStreamReader(System.in); buf = new char[BUFSIZE]; bufc = 0; bufi = 0; sb = new StringBuilder(); } /** Print, flush, return nextInt. */ private int queryInt(String s) { io.println(s); io.flush(); return nextInt(); } /** Print, flush, return nextLong. */ private long queryLong(String s) { io.println(s); io.flush(); return nextLong(); } /** Print, flush, return next word. */ private String queryNext(String s) { io.println(s); io.flush(); return next(); } private void fillBuf() throws IOException { bufi = 0; bufc = 0; while(bufc == 0) { bufc = r.read(buf, 0, BUFSIZE); if(bufc == -1) { bufc = 0; return; } } } private boolean pumpBuf() throws IOException { if(bufi == bufc) { fillBuf(); } return bufc != 0; } private boolean isDelimiter(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; } private void eatDelimiters() throws IOException { while(true) { if(bufi == bufc) { fillBuf(); if(bufc == 0) throw new RuntimeException("IO: Out of input."); } if(!isDelimiter(buf[bufi])) break; ++bufi; } } public String next() { try { sb.setLength(0); eatDelimiters(); int start = bufi; while(true) { if(bufi == bufc) { sb.append(buf, start, bufi - start); fillBuf(); start = 0; if(bufc == 0) break; } if(isDelimiter(buf[bufi])) break; ++bufi; } sb.append(buf, start, bufi - start); return sb.toString(); } catch(IOException e) { throw new RuntimeException("IO.next: Caught IOException."); } } public int nextInt() { try { int ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextInt: Invalid int."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int."); ret *= 10; ret -= (int)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int."); } else { throw new RuntimeException("IO.nextInt: Invalid int."); } ++bufi; } if(positive) { if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextInt: Caught IOException."); } } public long nextLong() { try { long ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextLong: Invalid long."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long."); ret *= 10; ret -= (long)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long."); } else { throw new RuntimeException("IO.nextLong: Invalid long."); } ++bufi; } if(positive) { if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextLong: Caught IOException."); } } public double nextDouble() { return Double.parseDouble(next()); } } void print(Object output) { io.println(output); } void done(Object output) { print(output); done(); } void done() { io.close(); throw new RuntimeException("Clean exit"); } long min(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } double min(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } int min(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } long max(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } double max(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } int max(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
e507fbf2fc02bb028ff6c6c33481515d
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
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 * * @author JENISH */ 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); DSashaAndOneMoreName solver = new DSashaAndOneMoreName(); solver.solve(1, in, out); out.close(); } static class DSashaAndOneMoreName { public void solve(int testNumber, ScanReader in, PrintWriter out) { String str = in.scanString(); int n = str.length(); for (int i = 1; i <= n - 1; i++) { String s1 = str.substring(0, i); String s2 = str.substring(i); String t = s2 + s1; if (peli(t) && !t.equals(str)) { out.println(1); return; } } if (n >= 3) { String sq = str.substring(0, n / 2); char c = sq.charAt(0); for (int i = 0; i < sq.length(); i++) { if (sq.charAt(i) != c) { out.println(2); return; } } } out.println("Impossible"); } boolean peli(String str) { for (int i = 0, j = str.length() - 1; i <= j; i++, j--) { if (str.charAt(i) != str.charAt(j)) return false; } return true; } } 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 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
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
69c226bb0fc2287e34b70f1d53b9c4d5
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.*; public class tr2 { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); String h=sc.nextLine(); int le=h.length(); HashSet <Character> hs=new HashSet(); int i=0; int j=le-1; // System.out.println(le); while(i<le) { hs.add(h.charAt(i)); i++; } if(le%2==0 &&hs.size()==1) { out.println("Impossible"); } else if(le%2==1&&hs.size()<2) { out.println("Impossible"); } else if(le%2==1) { char ss=h.charAt(le/2); int cc=0; for(int jj=0;jj<le;jj++) if(h.charAt(jj)==ss) cc++; if(cc==1 && hs.size()==2) out.print("Impossible"); else out.println(2); } else { StringBuilder sb=new StringBuilder(); StringBuilder sb2=new StringBuilder(); //StringBuilder hu=new StringBuilder(); sb2.append(h); //hu.append(h); boolean can=false; for(i=0;i<le;i++) { if(sb2.length()>0) sb2.deleteCharAt(0); sb.append(h.charAt(i)); StringBuilder sb3=new StringBuilder(); sb3.append(sb2); sb3.append(sb); //System.out.println(sb3); String l=sb3.substring(0,le/2); String hg=sb3.substring(le/2, le); String r=""; StringBuilder hu=new StringBuilder(); hu.append(hg); hu.reverse(); r+=hu; String z1=""; z1+=sb3; if(l.equals(r) && !z1.equals(h)) { can=true; //System.out.println(sb3.equals(hu)); //System.out.println(sb3+" "+hu); } } if(can) out.println(1); else out.print(2); } out.flush(); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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); } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
798fab5aeaa3b487dcc6f6594488c564
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.round; import static java.lang.Math.sqrt; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverse; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; import static java.util.Comparator.comparing; import static java.util.Comparator.comparingInt; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { // solveA(); // solveB(); // solveC(); solveD(); // solveE(); // solveF(); } private void solveA() throws IOException { int n = in.nextInt(), v = in.nextInt(); out.println(n <= v ? n - 1 : v + (n - 1 - v + 3) * (n - 1 - v) / 2); } private void solveB() throws IOException { int n = in.nextInt(); long[] a = new long[n]; long sum = 0, min = Long.MAX_VALUE; for (int i = 0; i < n; i++) { sum += a[i] = in.nextLong(); min = min(min, a[i]); } long ans = sum; for (int i = 0; i < n; i++) { for (long j = 1; j * j <= a[i]; j++) { if (a[i] % j == 0) { long d = j; ans = min(ans, sum - a[i] + a[i] / d - min + min * d); d = a[i] / j; ans = min(ans, sum - a[i] + a[i] / d - min + min * d); } } } out.println(ans); } private void solveC() throws IOException { int n = in.nextInt(); long[] a = new long[n]; long[] xor = new long[n]; long[][] xor2 = new long[2][]; xor2[0] = new long[(n + 1) / 2]; xor2[1] = new long[(n + 2) / 2]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); xor[i] = a[i] ^ (i == 0 ? 0 : xor[i - 1]); xor2[i % 2][(i + 1) / 2] = xor[i]; } long ans = 0; for (int i = 0; i < 2; i++) { shuffle(xor2[i]); sort(xor2[i]); for (int l = 0, r = 0; l < xor2[i].length; l = r) { while (r < xor2[i].length && xor2[i][r] == xor2[i][l]) r++; ans += (long) (r - l - 1) * (r - l) / 2; } } out.println(ans); } void shuffle(long[] a) { long b; Random r = new Random(); for (int i = a.length - 1, j; i > 0; i--) { j = r.nextInt(i + 1); b = a[j]; a[j] = a[i]; a[i] = b; } } private void solveD() throws IOException { char[] s = in.next().toCharArray(); int n = s.length; int[][] d = new int[2][n]; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r ? 1 : min(d[1][l + r - i], r - i)); while (i + k < n && i - k >= 0 && s[i + k] == s[i - k]) k++; d[1][i] = k--; if (i + k > r) { l = i - k; r = i + k; } } for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r ? 0 : min(d[0][l + r - i + 1], r - i + 1)); while (i + k < n && i - k - 1 >= 0 && s[i + k] == s[i - k - 1]) k++; d[0][i] = k; if (i + k - 1 > r) { l = i - k; r = i + k - 1; } } for (int i = 0; i < 2; i++) for (int j = 0; j < n; j++) d[i][j] = d[i][j] * 2 - i; boolean[] prefPal = new boolean[n]; for (int i = 0; i < n; i++) prefPal[i] = d[(i + 1) % 2][(i + 1) / 2] == i + 1; boolean[] suffPal = new boolean[n]; for (int i = 0; i < n; i++) suffPal[i] = d[(i + 1) % 2][n - 1 - i / 2] == i + 1; boolean ok = false; for (int i = 1; i < n / 2; i++) ok |= s[i - 1] != s[i]; if (!ok) { out.println("Impossible"); return; } char[] t = new char[n]; for (int i = 1; i < n; i += 2) { if (ok && prefPal[i] && (i == n - 1 || suffPal[n - i - 2])) { for (int j = 0; j < n; j++) t[j] = s[((i + 1) / 2 + j) % n]; ok = true; for (int j = 0; j < n / 2; j++) ok &= t[j] == t[n - 1 - j]; if (ok && !Arrays.equals(s, t)) { out.println(1); return; } } } out.println(2); } private void solveE() throws IOException { } private void solveF() throws IOException { } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } 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(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
ae852d3776343367531239ba838db68a
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.round; import static java.lang.Math.sqrt; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverse; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; import static java.util.Comparator.comparing; import static java.util.Comparator.comparingInt; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { char[] s = in.next().toCharArray(); int n = s.length; boolean ok = false; for (int i = 1; i < n / 2; i++) ok |= s[i - 1] != s[i]; if (!ok) { out.println("Impossible"); return; } char[] t = new char[n]; for (int i = 0; i < n; i ++) { for (int j = 0; j < n; j++) t[j] = s[(i + j) % n]; ok = true; for (int j = 0; j < n / 2; j++) ok &= t[j] == t[n - 1 - j]; if (ok && !Arrays.equals(s, t)) { out.println(1); return; } } out.println(2); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } 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(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
e04f4b90776132009cf0767a13428764
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.*; import java.util.InputMismatchException; import java.util.Random; /** * @author tainic on Feb 16, 2019 */ public class D { private static boolean LOCAL; static { try { LOCAL = "aurel".equalsIgnoreCase(System.getenv().get("USER")); } catch (Exception e){} } private static final String TEST = //"abcbaabcbaabcbaabcba"; "abbaabbaabbaabba"; void solve(InputReader in, PrintWriter out) { char[] a = in.next().toCharArray(); int n = a.length; String ans; if (n % 2 == 0) { if (!isPali(a, n / 2 - 1)) { ans = "1"; } else if (same(a, n / 2 - 1)) { ans = "Impossible"; } else { while (n % 2 == 0 && isPali(a, n / 2 - 1)) { n /= 2; } ans = (n % 2 == 0 ? "1" : "2"); } } else if (same(a, n / 2 - 1)) { ans = "Impossible"; } else { ans = "2"; } out.println(ans); } private boolean isPali(char[] a, int j) { for (int k = 0, r = j; k < r; k++, r--) { if (a[k] != a[r]) return false; } return true; } private boolean same(char[] a, int j) { for (int k = 1; k <= j; k++) { if (a[k] != a[0]) return false; } return true; } //region util static class Util { private static final Random R = new Random(); public static void sort(int[] a) { sort(a, 0, a.length - 1); } private static void sort(int[] a, int from, int to) { if (from >= to) { return; } // partition int pivotIndex = R.nextInt(to - from + 1) + from; int pivot = a[pivotIndex]; // maintain this invariant, at each step i: // a[j] < pivot, for j = fromIndex to lt - 1 // a[j] == pivot, for j = lt to i - 1 // a[j] > pivot, for j = gt + 1 to toIndex int lt = from; int gt = to; int i = lt; while (i <= gt) { int cmp = a[i] - pivot; if (cmp < 0) { swap(a, i, lt); i++; lt++; } else if (cmp > 0) { swap(a, i, gt); gt--; } else { i++; } } // sort left and right sort(a, from, lt - 1); sort(a, gt + 1, to); } public static int findFirst(int[] a, int key) { return findFirstOrLast(a, key, 0, a.length - 1, -1); } public static int findLast(int[] a, int key) { return findFirstOrLast(a, key, 0, a.length - 1, 1); } public static int findFirstOrLast(int[] a, int key, int fromIndex, int toIndex, int dir) { int left = fromIndex; int right = toIndex; while (left <= right) { int mid = (left + right) >>> 1; int cmp = key - a[mid]; if (cmp > 0) { left = mid + 1; } else if (cmp < 0) { right = mid - 1; } else if (dir == -1 && mid > fromIndex && a[mid - 1] == key) { right = mid - 1; } else if (dir == 1 && mid < toIndex && a[mid + 1] == key) { left = mid + 1; } else { return mid; } } return -left - 1; } public static void swap(int[] a, int i, int j) { if (i != j) { int ai = a[i]; a[i] = a[j]; a[j] = ai; } } public static int[] readInts(InputReader in, int k) { int[] a = new int[k]; for (int i = 0; i < k; i++) { a[i] = in.nextInt(); } return a; } } //endregion //region main public static void main(String[] args) throws Exception { long t = System.currentTimeMillis(); try ( InputReader in = new StreamInputReader(!LOCAL ? System.in : new ByteArrayInputStream(TEST.getBytes())); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out, 2048), false) ) { new D().solve(in, out); } System.err.println("time: " + (System.currentTimeMillis() - t) + "ms"); } //endregion //region fast io abstract static class InputReader implements AutoCloseable { public abstract int read(); public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf; private int curChar, numChars; public StreamInputReader(InputStream stream) { this(stream, 2048); } public StreamInputReader(InputStream stream, int bufSize) { this.stream = stream; this.buf = new byte[bufSize]; } @Override public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } @Override public void close() throws Exception { stream.close(); } } //endregion //region imports //endregion }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
bbfca9fd99ce6e48dfe2ff0bf058c18f
train_001.jsonl
1550334900
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class D_Round_539_Div2 { public static long MOD = 998244353; static long[][][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); String v = in.next(); int n = v.length(); boolean[][] dp = new boolean[n][n]; for (int i = n - 1; i >= 0; i--) { dp[i][i] = true; for (int j = i + 1; j < n; j++) { if (v.charAt(i) == v.charAt(j)) { dp[i][j] = (i + 1 < j) ? dp[i + 1][j - 1] : true; } } } int result = -1; for (int i = 0; i < n / 2; i++) { String a = v.substring(0, i + 1); String b = v.substring(i + 1); StringBuilder builder = new StringBuilder(b); builder.append(a); String tmp = builder.toString(); boolean ok = true; for (int j = 0; j < n / 2 && ok; j++) { ok &= tmp.charAt(j) == tmp.charAt(n - j - 1); } if (ok && !v.equals(tmp)) { //System.out.println(tmp + " " + a + " " + b); result = 1; break; } } for (int i = 0; i < n / 2; i++) { for (int j = i + 1; j < n / 2; j++) { if (!dp[i][j]) { int tmp = 0; if (i != 0) { tmp += 2; } if (j + 1 != n / 2 || n % 2 != 0) { tmp += 2; } else { tmp++; } if (result == -1 || result > tmp) { result = tmp; } } } } if (result == -1) { out.println("Impossible"); } else { out.println(result); } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["nolon", "otto", "qqqq", "kinnikkinnik"]
1 second
["2", "1", "Impossible", "1"]
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Java 8
standard input
[ "constructive algorithms", "brute force", "strings" ]
ffdef277d0ff8e8579b113f5bd30f52a
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
1,800
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
standard output
PASSED
43236566189c39bf27ce1d1cc4e53fe7
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] arg) { FastScanner scan = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); String in = scan.next(); for(int i = 0; i < n; i++){ if(n - i == 3){ out.print(in.substring(i)); i += 3; } else { out.print(in.substring(i, i + 2)); i += 1; } if(i < n - 1) out.print("-"); } 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(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.valueOf(next()); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
af1e48a55ed1a37909bf6b53b2600206
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Phone { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int x = Integer.parseInt(br.readLine()); String p = br.readLine(); String s=""; while(p.length()!=0){ if(p.length()%3==0){ //System.out.println(p + " 3"); s+=p.substring(0, 3); if(p.length()!=3){ s+="-"; p=p.substring(3,p.length()); }else{ p=""; } }else{ //System.out.println(p + " 2"); s+=p.substring(0, 2); if(p.length()!=2){ s+="-"; p=p.substring(2,p.length()); }else{ p=""; } } } System.out.println(s); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
4e50cdebae7e387c7cf37cddf44ee7a5
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class B_25_Phone_Numbers { public static void main(String[] args){ Scanner input=new Scanner(System.in); @SuppressWarnings("unused") int n=input.nextInt(); String s=input.next(); String news=""; while(s.length()>3){ news=news+s.substring(0, 2)+"-"; s=s.substring(2); } news=news+s; System.out.println(news); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
814f071b795f4fd33fcd265767d41658
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; import java.util.*; public class b25 { public static void main(String args[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); String s; // System.out.println("Enter"); int i,l,j,k,m,c=0,a=0,b=0; l=Integer.parseInt(in.readLine()); s=in.readLine(); if(l%2==0) { for(i=0;i<l;i+=2) { if(i==0) System.out.print(""+s.charAt(i)+s.charAt(i+1)); else if(l>2 && i>0) { System.out.print("-"+s.charAt(i)+s.charAt(i+1)); } } System.exit(0); } else if(l%3==0) { for(i=0;i<l;i+=3) { if(l>3 && i>0) { System.out.print("-"+s.charAt(i)+s.charAt(i+1)+s.charAt(i+2)); } else if(i==0) System.out.print(""+s.charAt(i)+s.charAt(i+1)+s.charAt(i+2)); } System.exit(0); } else { k=1; m=1; while(true) { m=1; while(true) { if(2*k+3*m==l) { c++; break; } else if(2*k + 3*m>l) break; else m++; } if(c>0) break; else k++; } for(i=0;i<k;i++) { if(i==0) { System.out.print(""+s.charAt(a)+s.charAt(a+1)); a+=2; } else { System.out.print("-"+s.charAt(a)+s.charAt(a+1)); a+=2; } } for(i=0;i<m;i++) { System.out.print("-"+s.charAt(a)+s.charAt(a+1)+s.charAt(a+2)); a+=3; } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
ed161a4db7c5e45eac57f92be3c1ea85
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class Main { /** * @param args */ static int N; public static void main(String[] args) { BufferedReader read = new BufferedReader( new InputStreamReader(System.in) ); try{ String str = read.readLine(); N = Integer.parseInt( str ); str = read.readLine(); char ch[] = str.toCharArray(); int siz = str.length(); boolean fl = false; int i = 0; while( siz > 0 ){ if( fl ) System.out.print("-"); fl = true; if( siz == 3 ){ System.out.print("" + ch[i] + ch[i+1] + ch[i+2]); siz -= 3; i += 3; } else{ System.out.print("" + ch[i] + ch[i+1]); siz -= 2; i += 2; } } } catch( Exception e ){ } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
3ace29b16acbd3c4a732c0d391119b9f
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class Phones { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int c = 0, n = sc.nextInt(); StringBuilder sb = new StringBuilder(sc.next()); int sz = sb.length(); if (n % 2 == 0) { for (int i = 0; i < sb.length(); i += 2) { System.out.print(sb.substring(i, i + 2)); if (i != sb.length() - 2) System.out.print("-"); } } else { if (sb.length() > 3) { System.out.print(sb.substring(0, 2)); sb.replace(0, 2, ""); } else if (sb.length() <= 3) { System.out.print(sb.toString()); c = 1; } if (c != 1) { for (int i = 0; i < sz && sb.length()>0; i++) { if (sb.length() > 2 && i % 2 == 0) { System.out.print("-" + sb.substring(0, 3)); sb.replace(0, 3, ""); } else if (sb.length() > 2) { System.out.print("-" + sb.substring(0, 2)); sb.replace(0, 2, ""); } else{ System.out.print("-" + sb.substring(0,sb.length())); sb.replace(0, sb.length(), "");} } } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
6c88108509c9d93c63a686816fd6f46c
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; import java.util.*; public class phone { static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static void main(String[] args) throws IOException { InputStream input = System.in; //InputStream input = new FileInputStream("fileIn.in"); OutputStream output = System.out; //OutputStream output = new FileOutputStream("fileOut.out"); br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); int n = Integer.parseInt(br.readLine()); String number = br.readLine(); String result = ""; while (n != 2 && n != 3 && n != 4 && n != 5 && n != 6) { int len; if (Math.random() < 0.5) len = 2; else len = 3; result += number.substring(0,len) + "-"; number = number.substring(len,number.length()); n -= len; } if (n == 2 || n == 3) result += number; else if (n == 4) result += number.substring(0,2) + "-" + number.substring(2,4); else if (n == 5) result += number.substring(0,3) + "-" + number.substring(3,5); else if (n == 6) result += number.substring(0,3) + "-" + number.substring(3,6); out.println(result); out.close(); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
179286a89a541a571de8331f7d1b0999
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; /** * * @author 11x256 */ public class Phonenumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String temp = sc.nextLine(); if (temp.length() % 2 == 0) { for (int i = 0; i < temp.length(); i += 2) { if (i != temp.length() - 2) { System.out.print(temp.charAt(i) + "" + temp.charAt(i + 1) + "-"); } else { System.out.print(temp.charAt(i) + "" + temp.charAt(i + 1)); } } } else { System.out.print(temp.charAt(0)); for (int i = 1; i < temp.length(); i += 2) { if (i != temp.length() - 2) { System.out.print(temp.charAt(i) + "" + temp.charAt(i + 1) + "-"); } else { System.out.print(temp.charAt(i) + "" + temp.charAt(i + 1)); } } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
6ab0044f2e3e49e29d9e8ff31d0575a7
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
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; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; /** * Built using CHelper plug-in * Actual solution is at the top * @author Erasyl Abenov * * */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream)) { TaskB solver = new TaskB(); solver.solve(1, in, out); } } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{ int n = in.nextInt(); String number = in.next(); int cntThree = n/3; n %= 3; int cntTwo = 0; if(n == 2) cntTwo++; if(n == 1){ cntThree--; cntTwo += 2; } String ans = ""; while(cntThree > 0){ cntThree--; ans = ans + "-" + number.substring(0, 3); number = number.substring(3); } while(cntTwo > 0){ cntTwo--; ans = ans + "-" + number.substring(0, 2); number = number.substring(2); } out.println(ans.substring(1)); } } class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public BigInteger nextBigInteger(){ return new BigInteger(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
4a60a6b8df575cb35ec11e50f1a6a7b2
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Reader.init(System.in); int n = Reader.nextInt() ; String s = Reader.next(); char [] c = s.toCharArray() ; StringBuilder res = new StringBuilder () ; if (n<=3) { System.out.println(s); return ; } if (n%2==0) { res.append(c[0]); for (int i=1 ; i<c.length ; i++) { if (i%2==0) res.append("-"+c[i]); else res.append(c[i]); } } else { res.append(c[0]+""+c[1]+""+c[2]); for (int i=3 ; i<c.length ; i++) { if (i%2!=0) res.append("-"+c[i]); else res.append(c[i]); } } System.out.println(res); } public static int BS(int[] a, int key) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (mid == key ) { return a[mid]; } else if (mid < key) { low = mid + 1; } else { high = mid - 1; } } return -1; } public static boolean isSorted(int[] a) { int i; for (i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { continue; } else { return false; } } return true; } public static void fill(int[] a) throws Exception { for (int i = 0; i < a.length; i++) { a[i] = Reader.nextInt(); } } static void s(int[] cc) { for (int e = 0; e < cc.length; e++) { for (int q = e + 1; q < cc.length; q++) { if (cc[e] < cc[q]) { int g = cc[e]; cc[e] = cc[q]; cc[q] = g; } } } } static boolean isPalindrome(String s) { int n = s.length(); for (int i = 0; i < (n / 2) + 1; ++i) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } } class MyPair { String s ; int x; int y; public MyPair(String s,int x, int y) { this.s = s; this.x = x; this.y = y; } } 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()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
0ced827607f6f9c4553d4f32b20d2d26
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class PhoneNumbers { public static void main(String[] args) { Scanner inp = new Scanner(System.in); inp.nextLine(); String x = inp.nextLine(); String x2 = ""; if(x.length()%2!=0&&x.length()>=3){ x2=x.substring(x.length()-3); x=x.substring(0,x.length()-3); } StringBuilder t = new StringBuilder(); int c = 0; for (int i = 0; i < x.length(); i++) { t.append(x.charAt(i)); c++; if(c==2){ t.append("-"); c=0; } } if(x2=="") t.deleteCharAt(t.length()-1); t.append(x2); System.out.println(t.toString()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
9a305a6708ac7ab864e9043a04c867f1
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class PhoneNumber { public static void main(String[] args) { Scanner inp = new Scanner(System.in); inp.nextLine(); String x = inp.nextLine(); String x2 = ""; if(x.length()%2!=0&&x.length()>=3){ x2=x.substring(x.length()-3); x=x.substring(0,x.length()-3); } StringBuilder t = new StringBuilder(); int c = 0; for (int i = 0; i < x.length(); i++) { t.append(x.charAt(i)); c++; if(c==2){ t.append("-"); c=0; } } if(x2=="") t.deleteCharAt(t.length()-1); t.append(x2); System.out.println(t.toString()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
e2ec382c63e24a963fef7225033e79f5
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Main { public static StringTokenizer st; public static BufferedReader scan; public static PrintWriter out; public static int gcd(int a, int b){ if(a < b)return gcd(b, a); else if(b == 0)return a; else return gcd(b, a % b); } public static void main(String[] args) throws IOException{ scan = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); String s = next(); if(n == 2)out.println(s); else{ if(n == 3){ out.println(s); }else{ if((n&1) == 0){ out.print(s.charAt(0) + "" + s.charAt(1)); for(int i = 2; i < n; i += 2){ out.print("-" + s.charAt(i) + "" + s.charAt(i + 1)); } }else{ out.print(s.charAt(0) + "" + s.charAt(1) + s.charAt(2)); for(int i = 3; i < n; i += 2){ out.print("-" + s.charAt(i) + "" + s.charAt(i + 1)); } } } } scan.close(); out.close(); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(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
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
0230da445fccd9c13ccf335327091fd3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF { static InputReader in = new InputReader(System.in); public static void main(String[] args) throws IOException { int n = in.nextInt(); String s = in.next(); if (s.length()==1) { System.out.println(s); return; } int groupTwo = n/2; if (n%2==1) { groupTwo--; } StringBuilder sb = new StringBuilder(); for(int i=0;i<groupTwo;i++) { sb.append(s.substring(i*2, i*2+2)+"-"); } if (n>2 && n%2==1) sb.append(s.substring(n-3, n)); if (n>=2 && sb.charAt(sb.length()-1)=='-') sb.deleteCharAt(sb.length()-1); System.out.println(sb); } } class InputReader { private BufferedReader reader; private 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 String readLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
f0c445056f881adea1922ef7848e1c72
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; import sun.nio.cs.Surrogate; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author youniesmahmoud */ public class phone { public static void main(String[] args) { Scanner inp = new Scanner(System.in); inp.nextLine(); String x = inp.nextLine(); String x2 = ""; if(x.length()%2!=0&&x.length()>=3){ x2=x.substring(x.length()-3); x=x.substring(0,x.length()-3); } StringBuilder t = new StringBuilder(); int c = 0; for (int i = 0; i < x.length(); i++) { t.append(x.charAt(i)); c++; if(c==2){ t.append("-"); c=0; } } if(x2=="") t.deleteCharAt(t.length()-1); t.append(x2); System.out.println(t.toString()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
62c71f1e38eddad785240a6cbec5506d
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.awt.Point; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Solution(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution void solve() throws IOException { int n = readInt(); String s = readString(); int p = 0; if(n % 2 > 0){ for(p = 0; p<3; p++) out.print(s.charAt(p)); } for(;p<n;p+=2){ if(p>0) out.print("-"); out.print(s.charAt(p)); out.print(s.charAt(p+1)); } out.println(); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
de2a8068f2827dd7da6fe87cf6ad5dc3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class P25B { public P25B() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String phone = sc.next(); sc.close(); int i = 0; for (; i < n - 3; i+= 2){ System.out.print(phone.substring(i, i+2) + "-"); } System.out.print(phone.substring(i)); } public static void main (String []args){ new P25B(); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
142f9f346fadeb0ef31187d366a63ae3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String res =""; int n =sc.nextInt(); String numbers = sc.next(); if(n==2||n==3)System.out.println(numbers); else { int count =2; if((n&1)==0) { int i=0; for(;count<=numbers.length();count+=2) { res +=numbers.substring(i,count); if(count!=numbers.length())res +='-'; i=count; } } else { count =2; int i=0; for(;count<=numbers.length()-3;count+=2) { res +=numbers.substring(i,count); if(count!=numbers.length()-3)res +='-'; i=count; } res +='-'; res +=numbers.substring(i,numbers.length()); } } System.out.println(res); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
938517b178fb030106a2db312b4040d3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * 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(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); char[] a = in.next().toCharArray(); for (int i = 0; i < n; i++) { if(i != 0 && i % 2 == 0 && !(n % 2 == 1 && i == n-1)){ out.print("-"); out.print(a[i]); } else { out.print(a[i]); } } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
ce198aa6dc72cd01097f4f1456ef543f
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String s = sc.next(); sc.close(); for(int i = 0 ; i < N ; i++){ System.out.print(s.charAt(i)); if(i % 2 != 0 && i < N - (N % 2) - 2) System.out.print("-"); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
30634e756ecb0c54dc9cf95cfc4d8f7a
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; import java.util.*; public class j { public static void main(String a[])throws IOException { BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); int n=0,i=0; n=Integer.parseInt(b.readLine()); String s; s=b.readLine(); if(n%2==0) { for(i=0;i<n;i+=2) { if(i!=0) System.out.print("-"); System.out.print(s.substring(i,i+2)); } } else { for(i=0;i<n-3;i+=2) { if(i!=0) System.out.print("-"); System.out.print(s.substring(i,i+2)); } if(n!=3) System.out.print("-"); System.out.print(s.substring(i)); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
c10fae5dc69202e4bb75c43c2c049ae5
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) ) ; int A = Integer.parseInt(input.readLine()) ; String X = input.readLine() ; if ( A % 2 == 0 ) for ( int i = 0 ; i < X.length() ; i ++ ) { System.out.print(X.charAt(i) ); System.out.print(((i+1)%2 == 0)&& i != X.length() - 1 ? "-" : ""); } else { System.out.print(X.charAt(0) ) ; System.out.print(X.charAt(1) ) ; System.out.print(X.charAt(2) ) ; for ( int i = 3 ; i < X.length() ; i ++ ) { if ( i == 3 ) System.out.print("-"); System.out.print(X.charAt(i) ); System.out.print((i%2 == 0)&& i != X.length() - 1 ? "-" : ""); } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
850e0753ee9e0192d8732ec319ca8f3f
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class _25B { static Scanner scanner = new Scanner(System.in); static int n; static String s; public static void main(String[] args) { n = scanner.nextInt(); s = scanner.next(); for (int i=0;i<s.length();) { if (i + 3 == n) { System.out.println(s.substring(i)); i += 3; } else { if (i + 2 == n) { System.out.println(s.substring(i)); } else { System.out.print(s.substring(i, i+2) + "-"); } i += 2; } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
2e321dd52aee4bb524908d72a32b7bd3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.*; public class Test_Project_0001 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); String number = sc.nextLine(); String number_s = sc.nextLine(); int i = 0; if(count%2 != 0) { System.out.print(number_s.substring(0, 3)); i = 3; } else { System.out.print(number_s.substring(0, 2)); i = 2; } while(i < count) { System.out.print("-" + number_s.substring(i, i + 2)); i+=2; } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
2421325eb84c595dfe05ccdd5a60e789
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class PhoneNumber { public static void main(String[] args) { Scanner input=new Scanner(System.in); int i=0, a=0; int number=input.nextInt(); String phnumber=input.next(); if(number%2==0) { System.out.print( phnumber.substring(0, 2)); i=2; } else { System.out.printf( phnumber.substring(0, 3)); i=3; } for(;i<number;i+=2) { System.out.printf( "-"+phnumber.substring(i, i+2)); } System.out.println(); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
b73dafe981127e80cc4434d8b29287fc
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); String str = s.next(); if (n == 3 || n == 2) System.out.println(str); else if (n % 2 == 0) { for (int i = 1;i < n;i++) { System.out.print(str.charAt(i-1)); if (i % 2 == 0) System.out.print("-"); } System.out.print(str.charAt(n-1)); }// even else if(n%2==1) { for (int i = 1;i <= n-3;i++) { System.out.print(str.charAt(i-1)); if (i % 2 == 0) System.out.print("-"); } System.out.println( str.substring(n-3) ); }// odd }//main }//class
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
7a5d4b6b3f2433389c61390641defb68
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.util.ArrayDeque; 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) { int n = in.nextInt(); ArrayDeque<Character> q = new ArrayDeque<>(); for (char c: in.next().toCharArray()) { q.add(c); } StringBuffer res = new StringBuffer(); res.append(q.poll()); res.append(q.poll()); while (!q.isEmpty()) { if (q.size() < 2) { res.append(q.poll()); break; } res.append('-'); res.append(q.poll()); res.append(q.poll()); } 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(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
1d15a8a484aa010ec55242ccd5bc54c0
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author KHALED */ public class PhoneNumbers { public static void main(String[] args) { MyScanner scan=new MyScanner(); int n=scan.nextInt(); String s=scan.next(); if(n%2==0) { for (int i = 0; i < n; i=i+2) { if(i!=n-2) System.out.print(s.charAt(i)+""+s.charAt(i+1)+"-"); else System.out.print(s.charAt(i)+""+s.charAt(i+1)); } } else { if(n>3) { System.out.print(s.charAt(0)+""+s.charAt(1)+""+s.charAt(2)+"-"); for (int i = 3; i < n; i+=2) { if(i!=n-2) System.out.print(s.charAt(i)+""+s.charAt(i+1)+"-"); else System.out.print(s.charAt(i)+""+s.charAt(i+1)); } } else System.out.print(s.charAt(0)+""+s.charAt(1)+""+s.charAt(2)); } } } class MyScanner { static BufferedReader br; static 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()); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
721e63ea0b841b23a82981468b8616f3
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.*; import java.io.*; public class Main { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder out = new StringBuilder(); public static void main(String[] args){ solve(); return; } // the followings are methods to take care of inputs. static int nextInt(){ return Integer.parseInt(nextLine()); } static long nextLong(){ return Long.parseLong(nextLine()); } static int[] nextIntArray(){ String[] inp = nextLine().split("\\s+"); int[] ary = new int[inp.length]; for (int i = 0; i < ary.length; i++){ ary[i] = Integer.parseInt(inp[i]); } return ary; } static int[] nextIntArrayFrom1(){ String[] inp = nextLine().split("\\s+"); int[] ary = new int[inp.length + 1]; for (int i = 0; i < inp.length; i++){ ary[i+1] = Integer.parseInt(inp[i]); } return ary; } static long[] nextLongArray(){ String[] inp = nextLine().split("\\s+"); long[] ary = new long[inp.length]; for (int i = 0; i < inp.length; i++){ ary[i] = Long.parseLong(inp[i]); } return ary; } static long[] nextLongArrayFrom1(){ String[] inp = nextLine().split("\\s+"); long[] ary = new long[inp.length + 1]; for (int i = 0; i < inp.length; i++){ ary[i+1] = Long.parseLong(inp[i]); } return ary; } static String nextLine(){ try { return reader.readLine().trim(); } catch (Exception e){} return null; } static void solve(){ int n = nextInt(); String str = nextLine(); String ret =""; int count=0; if(n%2==1) count--; for(int i=0;i<str.length();i++){ if(count==2){ count=0; ret+="-"; i--; } else{ ret+=str.charAt(i); count++; } } System.out.println(ret); return; } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
7c7222a2c19a81bec919c7ddb8f28b69
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader cin=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(cin.readLine()); char a[]=cin.readLine().toCharArray(); if(n<=3) System.out.println(new String(a)); else if(n%2==0) { for(int i=0;i<n;i++) System.out.print(i!=0 && i%2==0?"-"+a[i]:a[i]); System.out.println(); } else { System.out.print(a[0]+""+a[1]+"-"+a[2]+""+a[3]+""+a[4]+(n>5?"-":"")); for(int i=5;i<n;i++) System.out.print(i!=5 && i%2==1?"-"+a[i]:a[i]); System.out.println(); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
ed9788d5a0d3e6c87319d4d7a3a040e8
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class Main { static String s; public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.nextInt(); s = sc.next(); printGroups(0); } static void printGroups(int i) { if (s.length() - i == 2 || s.length() - i == 3) { for (int j = i; j < s.length(); j++) System.out.print(s.charAt(j)); return; } System.out.print(s.charAt(i + 0)); System.out.print(s.charAt(i + 1)); System.out.print('-'); printGroups(i + 2); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
bbc663346dcbc0cf365a041e6243872f
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.*; public class b25 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String s=sc.next(); for(int i=0;i<s.length();i++) { System.out.print(s.charAt(i)); if(i%2!=0 && n-i!=2 && n-1!=i) System.out.print("-"); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
ea9a99080484321cc9df05d92ea98886
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class main { public static void main(String[] args) { try{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int digit,in=0; String numz; digit= Integer.parseInt(reader.readLine()); numz=reader.readLine(); String[] splited=new String[digit]; while(numz.length()>3){ splited[in++]= numz.substring(0,2); numz= numz.substring(2,numz.length()); } splited[in++]=numz; if(in>0){ System.out.print(splited[0]); for(int i = 1;i<in;i++){ System.out.print("-" + splited[i]); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
04d141f6f51d9c2de0bada91850c60b9
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
//package codeforce; import java.util.Scanner; /* @author Kbk*/ public class PhoneNumber { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int N=sc.nextInt(); String str=sc.next(); String temp=""; if(str.length()%2==0){ for(int i=0;i<str.length();i++){ if(i!=0 && i%2==0) temp+='-'; temp+=str.charAt(i); } } else if(str.length()%3==0){ for(int i=0;i<str.length();i++){ if(i!=0 && i%3==0) temp+='-'; temp+=str.charAt(i); } } else{ boolean isTrue=true; for(int i=0;i<str.length();i++){ if(str.length()-i==3){ temp+='-'; isTrue=false; } if(i!=0 && i%2==0 && isTrue) temp+='-'; temp+=str.charAt(i); } } System.out.println(temp); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
526d8646636c256546b3740323030108
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class other { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String str = scan.next(); for(int i=0; i<n; i++ ) { System.out.print(str.charAt(i)); if( i%2 != 0 && i<n-(n%2)-2 ) System.out.print('-'); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
19e6967cd2245bc431987aae8973f4dc
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import java.util.Vector; public class first { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int n; n=sc.nextInt(); String numb=sc.next(); boolean two=true; if (numb.length()%2==1) two=false; if (two) for (int i=0; i<numb.length(); i++) { if (i!=0 && i!=numb.length()) if (i%2==0) System.out.print("-"); System.out.print(numb.charAt(i)); } else for (int i=0; i<numb.length(); i++ ) { if (i>=2 && i!=numb.length()) if (i%2==1) System.out.print("-"); System.out.print(numb.charAt(i)); } System.out.flush(); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
9e0334ecbad81f68b189c305db943d00
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class PhoneNumberDivisions { public static void main(String args[]){ Scanner input=new Scanner (System.in); int n=input.nextInt(); String s=input.next(); int a[]=new int[n]; for (int i=0;i<=n-1;i++){ a[i]=s.charAt(i); } for (int i=0; i<=n-1;i++){ a[i]=a[i]-48; } // for (int element: a){ // System.out.print(element); // } if (n%2==0){ for (int i=0;i<=n-4;i+=2){ System.out.print(a[i]); System.out.print(a[i+1]+"-"); if (i==n-4){ System.out.print(a[i+2]); System.out.print(a[i+3]); } } } if (n%2!=0){ for (int i=0;i<=n-5;i+=2){ System.out.print(a[i]); System.out.print(a[i+1]+"-"); if (i==n-5){ System.out.print(a[i+2]); System.out.print(a[i+3]); System.out.print(a[i+4]); } } } if (n==2 | n==3){ for (int element:a){ System.out.print(element); } } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
784dcc1401e5c3876720d6857e91e56b
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.util.Scanner; public class B25 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); char[] next = in.next().toCharArray(); StringBuilder str = new StringBuilder(); int index = 0; if ((n & 1) == 0) { str.append(next[index++]); str.append(next[index++]); } else { str.append(next[index++]); str.append(next[index++]); str.append(next[index++]); } for (; index < n;) { str.append('-'); str.append(next[index++]); str.append(next[index++]); } System.out.println(str); } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
d6a50edff806ff455df0c0ab2251d229
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class solver implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Thread(null, new solver(), "", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException { int n = readInt(); char[] a = readString().toCharArray(); ArrayList<String> list = new ArrayList<>(); if (n % 2 == 1) { for (int i=0;i<n-3;i+=2) { list.add(a[i] + "" + a[i + 1]); } list.add(a[n-3]+""+a[n-2]+""+a[n-1]); } else { for (int i=0;i<n;i+=2) { list.add(a[i] + "" + a[i + 1]); } } for (int i=0;i<list.size();i++) { if (i != 0) out.print('-'); out.print(list.get(i)); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output
PASSED
f06338e7c4f341eb0b585043a4c6837f
train_001.jsonl
1280761200
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class main { public static void main(String[] args) { try{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int digit,in=0; String numz; digit= Integer.parseInt(reader.readLine()); numz=reader.readLine(); String[] splited=new String[digit]; while(numz.length()>3){ splited[in++]= numz.substring(0,2); numz= numz.substring(2,numz.length()); } splited[in++]=numz; if(in>0){ System.out.print(splited[0]); for(int i = 1;i<in;i++){ System.out.print("-" + splited[i]); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } } }
Java
["6\n549871", "7\n1198733"]
2 seconds
["54-98-71", "11-987-33"]
null
Java 7
standard input
[ "implementation" ]
6f6859aabc1c9cbb9ee0d910064d87c2
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
1,100
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
standard output