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
aeb344b1871afa54ff19a0bbb231d9bf
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out =new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int num = (n * m) / k; int rem = (n * m) % k; int q = 1; int t = 0; int a = 1; int b = 1; int size = 0;// tedade khoonehaye har donbale dar hal lahze! for (int i = a; a <= n; i++) { if (q > k) break; if (q != k)// hanooz be donbale akhari naresidim! out.print(num); else out.print(num + rem); if (q != k) t = num; else t = num + rem; while (size < t) { if (a % 2 == 1) out.print(" " + a + " " + (b++)); else out.print(" " + a + " " + (--b)); size++; if (b == m + 1) a++; if (b == 1) a++; } q++; size = 0; out.println(); } out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
b8d507394bef10c03f6a9b1eec9f01e8
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int num = (n * m) / k; int rem = (n * m) % k; int q = 1; int t = 0; int a = 1; int b = 1; int size = 0;// tedade khoonehaye har donbale dar hal lahze! for (int i = a; a <= n; i++) { if (q > k) break; if (q != k)// hanooz be donbale akhari naresidim! System.out.print(num); else System.out.print(num + rem); if (q != k) t = num; else t = num + rem; while (size < t) { if (a % 2 == 1) System.out.print(" " + a + " " + (b++)); else System.out.print(" " + a + " " + (--b)); size++; if (b == m + 1) a++; if (b == 1) a++; } q++; size = 0; System.out.println(); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
08828aac84017c03680921322c020725
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.*; import java.io.*; public class Tubes { public static void main(String[] args) throws IOException { //long t1 = System.currentTimeMillis(); Scanner keyboard = new Scanner(System.in); int n = Integer.parseInt(keyboard.next()); int m = Integer.parseInt(keyboard.next()); int k = Integer.parseInt(keyboard.next()); LinkedList<Cell> a = new LinkedList<Cell>(); //long t2 = System.currentTimeMillis(); //System.out.println(t2-t1); for(int i=1;i<=n;i+=2) { for(int j=1;j<=m;j++) a.add(new Cell(i,j)); if(i<n) for(int j=m;j>0;j--) a.add(new Cell(i+1, j)); } //long t3 = System.currentTimeMillis(); //System.out.println(t3-t2); Object[] array = new Object[k]; array[0]=a; for(int i=1;i<k;i++) { LinkedList<Cell> ar = new LinkedList<Cell>(); ar.addFirst(a.getFirst()); a.removeFirst(); ar.addFirst(a.getFirst()); a.removeFirst(); array[i]=ar; } //long t4 = System.currentTimeMillis(); //System.out.println(t4-t3); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out"))); for(int i=0;i<k;i++) { System.out.print(((LinkedList<Cell>) array[i]).size()); for(Cell c : ((LinkedList<Cell>) array[i])) { System.out.print(" " + c.x + " " + c.y); //out.print(" " + ((ArrayList<Cell>) array[i]).get(j).x + " " + ((ArrayList<Cell>) array[i]).get(j).y); } System.out.println(); } //long t5 = System.currentTimeMillis(); //System.out.println(t5-t4); } } class Cell { public int x; public int y; public Cell(int a, int b) { x=a; y=b; } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
c7ad98a98ce8b3ad854ffd0465ba9e3e
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Collection; import java.util.Locale; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Object o = solve(); if (o != null) out.println(o); out.close(); in.close(); } int[] dr = { 0, 1, 0 ,-1}; int[] dc = { 1, 0, -1 ,0}; int n; int m; int dir = 0; boolean[][] ok; private Object solve() throws IOException { n = ni(); m = ni(); ok = new boolean[n][m]; int k = ni(); int[] p = { 1, 1 }; int count = 0; while (count < n * m && k > 1) { p(2 + " " + show(p)); p = move(p); p(" " + show(p)); p = move(p); pln(); k--; count += 2; } if(count<n*m){ p(n*m - count); while(count<n*m){ p(" "+show(p)); p = move(p); count++; } pln(); } return null; } private int[] move(int[] p) { ok[p[0]-1][p[1]-1]=true; int[] ret = { p[0] + dr[dir], p[1] + dc[dir] }; if (1 <= ret[0] && ret[0] <= n && 1 <= ret[1] && ret[1] <= m && !ok[ret[0]-1][ret[1]-1]) return ret; dir = (dir + 1) % 4; return new int[] { p[0] + dr[dir], p[1] + dc[dir] }; } private String show(int[] p) { return p[0] + " " + p[1]; } BufferedReader in; PrintWriter out; StringTokenizer strTok = new StringTokenizer(""); String nextToken() throws IOException { while (!strTok.hasMoreTokens()) strTok = new StringTokenizer(in.readLine()); return strTok.nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } int[] nia(int size) throws IOException { int[] ret = new int[size]; for (int i = 0; i < size; i++) ret[i] = ni(); return ret; } long[] nla(int size) throws IOException { long[] ret = new long[size]; for (int i = 0; i < size; i++) ret[i] = nl(); return ret; } double[] nda(int size) throws IOException { double[] ret = new double[size]; for (int i = 0; i < size; i++) ret[i] = nd(); return ret; } String nextLine() throws IOException { strTok = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!strTok.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; strTok = new StringTokenizer(s); } return false; } void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } public void pln() { out.println(); } public void pln(int arg) { out.println(arg); } public void pln(long arg) { out.println(arg); } public void pln(double arg) { out.println(arg); } public void pln(String arg) { out.println(arg); } public void pln(boolean arg) { out.println(arg); } public void pln(char arg) { out.println(arg); } public void pln(float arg) { out.println(arg); } public void pln(Object arg) { out.println(arg); } public void p(int arg) { out.print(arg); } public void p(long arg) { out.print(arg); } public void p(double arg) { out.print(arg); } public void p(String arg) { out.print(arg); } public void p(boolean arg) { out.print(arg); } public void p(char arg) { out.print(arg); } public void p(float arg) { out.print(arg); } public void p(Object arg) { out.print(arg); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
ac764f7d33d41175dc2805815c15e857
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public class C { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public void run() { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); int count = 0; ArrayList<String> res = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); int nextX = 1, nextY = 1; while (k > 1) { sb = new StringBuilder(); sb.append(2 + " "); sb.append(nextY + " " + nextX + " "); if ((nextY % 2 == 1 && nextX == m) || (nextY % 2 == 0 && nextX == 1)) nextY++; else if (nextY % 2 == 0) nextX--; else nextX++; sb.append(nextY + " " + nextX + " "); res.add(sb.toString()); count += 2; if ((nextY % 2 == 1 && nextX == m) || (nextY % 2 == 0 && nextX == 1)) nextY++; else if (nextY % 2 == 0) nextX--; else nextX++; k--; } sb = new StringBuilder(); sb.append((n*m - count) + " "); while (count < n * m) { sb.append(nextY + " " + nextX + " "); if ((nextY % 2 == 1 && nextX == m) || (nextY % 2 == 0 && nextX == 1)) nextY++; else if (nextY % 2 == 0) nextX--; else nextX++; count++; } res.add(sb.toString()); for (String s : res) { out.println(s); } out.close(); } public static void main(String[] args) { new C().run(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
9f7e927aa15097a5dfbca81b1f9cb0f7
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class C { final public static void main ( String[] args ) { Scanner s = new Scanner( System.in ); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int totalCells = m*n; int cellsPerTube = Math.max( 2 , totalCells/k ); Tube[] tubes = new Tube[ k ]; int currX = 0; int currY = 0; int dx = 1; for ( int i=0 ; i<k-1 ; i++ ) { tubes[ i ] = new Tube(); for ( int j=1 ; j<=cellsPerTube ; j++ ) { tubes[ i ].addCell( currX , currY ); currX += dx; if ( currX >= n || currX < 0 ) { currX -= dx; dx *= -1; currY++; } } } tubes[ k-1 ] = new Tube(); for ( int i=cellsPerTube*(k-1) ; i<totalCells ; i++ ) { tubes[ k-1 ].addCell( currX , currY ); currX += dx; if ( currX >= n || currX < 0 ) { currX -= dx; dx *= -1; currY++; } } for ( int i=0 ; i < k ; i++ ) { System.out.println( tubes[ i ].toString() ); } } static class Tube { ArrayList< Coordinate > cells = new ArrayList< Coordinate >(); public Tube() { } public void addCell( int x0 , int y0 ) { this.cells.add( new Coordinate( x0 , y0 ) ); } @Override public String toString() { StringBuffer s = new StringBuffer( "" ); s.append( this.cells.size() ); for( int i=0 ; i<this.cells.size() ; i++ ) { s.append( " " ); s.append( this.cells.get( i ).toString() ); } return s.toString(); } } static class Coordinate { public int m_x; public int m_y; public Coordinate( int x , int y ) { this.m_x = x+1; this.m_y = y+1; } @Override public String toString() { StringBuffer s = new StringBuffer( "" ); s.append( this.m_x ); s.append( " " ); s.append( this.m_y ); return s.toString(); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
60ca0bfcb8c6720dbc214bcdad3df2bd
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.*; public class C{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int l = sc.nextInt(); int r = 0; int c = 1; int total = 0; for(int j = 0; j < l; j++){ int count = 0; StringBuilder sb = new StringBuilder(); for(int i = 0; i < 2; i++){ count++; if(c==1){ if(r%2 == 0) r++; else c++; }else if(c==m){ if(r%2 == 1) r++; else c--; } else if(r%2 == 0) c--; else c++; sb.append(r + " " +c + " "); } if(j == l-1){ while(count + total < n*m){ count++; if(c==1){ if(r%2 == 0) r++; else c++; }else if(c==m){ if(r%2 == 1) r++; else c--; } else if(r%2 == 0) c--; else c++; sb.append(r + " " +c + " "); } } total += count; System.out.println(count + " " + sb.toString().trim()); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
9fe43931c564bd6db315af998eadd6cb
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
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(); int m = sc.nextInt(); int k = sc.nextInt(); int NoT = (n * m) / k; String[] input = new String[n * m]; int Left = 1; int position = 0; for (int i = 1; i <= n; i++) { if (Left == 1) { for (int j = 1; j <= m; j++) { input[position++] = " " + i + " " + j; } Left = 0; } else { for (int j = m; j >= 1; j--) { input[position++] = " " + i + " " + j; } Left = 1; } } position = 0; StringBuilder sb = new StringBuilder(""); for (int i = 0; i < k; i++) { if (i == k-1 && NoT * k < n * m) { sb.append(n*m - NoT * (i)); for (int h = position; h < n * m; h++) { sb.append(input[position++]); } } else { sb.append(NoT); for (int j = 0; j < NoT; j++) { // position++; sb.append(input[position++]); } } sb.append("\n"); } if (k * NoT > n * m) { int s = n * m / NoT; int count = n * m - NoT * s; sb.append(count); for (int i = position; i < n * m; i++) { sb.append(input[position++]); } } String stringOut = sb.toString(); System.out.println(stringOut); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
e4658b26050845361387cdf2159167f3
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; /** * * * @author pttrung */ public class C { // public static long x, y, gcd; public static PrintWriter out; public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(); out = new PrintWriter(System.out); // System.out.println(Integer.MAX_VALUE); // PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] x = {0, 1, 0, 1}; int[] y = {1, 0, -1, 0}; int dir = 0; int c = 0; int a = 1; int b = 1; int last = 0; for (int i = 0; i < n * m; i++) { if (c + 1 < k) { if (last == 0) { last++; out.print(2 + " " + a + " " + b + " "); } else { c++; last = 0; out.println(a + " " + b); } } else if (c + 1 == k) { out.print((n * m) - (c*2) + " "); out.print(a + " " + b + " "); c++; } else { out.print(a + " " + b + " "); } int e = a + x[dir]; int f = b + y[dir]; if (e > n || e <= 0 || f > m || f <= 0) { dir = (dir + 1) % 4; e = a + x[dir]; f = b + y[dir]; dir = (dir + 1) % 4; } a = e; b = f; } out.close(); } public static int dist(Point a, Point b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } public static Point clock(Point p, int n, int m) { Point result = new Point(p.y, n - p.x + 1); return result; } public static Point anti_clock(Point p, int n, int m) { Point result = new Point(m - p.y + 1, p.x); return result; } public static int cross(Point a, Point b) { int val = a.x * b.y - a.y * b.x; return val; } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static class Point implements Comparable<Point> { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { if (x != o.x) { return x - o.x; } else { return y - o.y; } } @Override public int hashCode() { int hash = 7; hash = 59 * hash + this.x; hash = 59 * 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; } } // public static void extendEuclid(long a, long b) { // if (b == 0) { // x = 1; // y = 0; // gcd = a; // return; // } // extendEuclid(b, a % b); // long x1 = y; // long y1 = x - (a / b) * y; // x = x1; // y = y1; // // } public static class FT { int[] data; FT(int n) { data = new int[n]; } public void update(int index, int value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public int get(int index) { int result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } 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
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
f76bba75d2c0d722ba24b6fd40e7eac7
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
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.util.Arrays; import java.util.ArrayList; import java.util.LinkedList; import java.util.TreeMap; import java.util.HashSet; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Built using CHelper plug-in * Actual solution is at the top */ public class MainC { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int t = in.nextInt(); int[] x = new int[n*m]; int[] y = new int[n*m]; boolean on = true; int count = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { x[count] = i; y[count] = on ? m-j + 1 : j; count++; } on = !on; } count = 0; for (int i = 0; i < t-1; ++i) { out.write("2 "); out.write(x[count] + " " + y[count] + " "); out.write(x[count+1] + " " + y[count+1] + "\n"); count +=2; } out.write(n*m - count + " "); for (int i = count; i < n*m; ++i) { out.write(x[i] + " " + y[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()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
a6a9293bfbdd4b934d290c11a5e6d73c
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.Scanner; public class ValeraAndTubes { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, m, k, t, l, r, d, x, y, c1, c2; n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); t = n * m; l = n * m / k; r = (n * m) % k; d = -1; y = 1; x = 0; c1 = 0; c2 = 1; StringBuilder s = new StringBuilder(); s.append(l + " "); for (int i = 1; i <= t; i++) { if (i % m == 1) { x++; d *= -1; } else { y += 1 * d; } c1++; s.append(x + " " + y + " "); if (c1 == l) { System.out.println(s); c2++; s.setLength(0); if (c2 == k) l += r; s.append(l + " "); c1 = 0; } } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
1524ffc0bdd11a8e7a408421da0207ee
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
//package codeforces; import java.io.*; import java.util.*; public class C { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; C() throws IOException { // reader = new BufferedReader(new FileReader("bridges.in")); // writer = new PrintWriter(new FileWriter("bridges.out")); } String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, int k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } int inv(int x) { return pow(x, MOD - 2); } void solve() throws IOException { int n = nextInt(), m = nextInt(), k = nextInt(); List<Integer> ans = new ArrayList<>(n * m * 2); for(int r = 1; r <= n; r++) { int c0 = r % 2 == 0 ? m : 1; int dc = r % 2 == 0 ? -1 : 1; for(int i = 0; i < m; i++) { ans.add(r); ans.add(c0 + i * dc); } } for(int i = 0; i < k - 1; i++) { writer.println(String.format("2 %d %d %d %d", ans.get(4 * i), ans.get(4 * i + 1), ans.get(4 * i + 2), ans.get(4 * i + 3))); } writer.print(n * m - 2 * (k - 1)); for(int i = 4 * k - 4; i < ans.size(); i++) { writer.print(" " + ans.get(i)); } writer.println(); writer.close(); } public static void main(String[] args) throws IOException { new C().solve(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
261c6949660d99ae2270eda03683fd2f
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
/* * 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. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author RezaM */ public class C2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int length = (n * m) / k; int reminder = (n * m) % k; int i = 1; int j = 1; for (int l = 0; l < k - 1; l++) { out.print(length); int size = 0; while (size < length) { out.print(" " + i + " " + j); if (i % 2 == 1) { j++; } else { j--; } if (j > m) { i++; j--; } if (j < 1) { i++; j++; } size++; } out.println(); } int endlength=length+reminder; out.print(endlength); int size=0; while(size<endlength){ out.print(" " + i + " " + j); if (i % 2 == 1) { j++; } else { j--; } if (j > m) { i++; j--; } if (j < 1) { i++; j++; } size++; } out.println(); out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
e7ef67c0936e4e2326860355ba0561ce
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
/* * 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. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author RezaM */ public class C2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int length = (n * m) / k; int reminder = (n * m) % k; int i = 1; int j = 1; for (int l = 0; l < k - 1; l++) { out.print(length); int size = 0; while (size < length) { if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } size++; } out.println(); } int endlength = length + reminder; out.print(endlength); int size = 0; while (size < endlength) { if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } size++; } out.println(); out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
974d34dfdeecad00c181c94e5ee08f48
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
/* * 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. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author RezaM */ public class C3 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int i = 1; int j = 1; for (int l = 0; l < k - 1; l++) { out.print(2); if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } out.println(); } int reminder=(n*m)-2*(k-1); out.print(reminder); for (int l =1 ; l <= reminder; l++) { if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } } out.println(); out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
6dcb267c2541286bef0e7d2ff6cc45f8
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
/* * 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. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author RezaM */ public class C2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int length = (n * m) / k; int reminder = (n * m) % k; int i = 1; int j = 1; for (int l = 0; l < k - 1; l++) { out.print(length); int size = 0; while (size < length) { if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } size++; } out.println(); } int endlength = length + reminder; out.print(endlength); int size = 0; while (size < endlength) { if (i % 2 == 1) { out.print(" " + i + " " + (j++)); } else { out.print(" " + i + " " + (j--)); } if (j > m) { i++; j--; } else if (j < 1) { i++; j++; } size++; } out.println(); out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
25db238a312cff9cca48c93818fa1b9a
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
/* * 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. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author RezaM */ public class C { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int length = (m * n) / k; int reminder = (m * n) % k; int num = 0; boolean bool = true; for (int i = 0; i < n; i++) { if (i % 2 == 0) { for (int j = 0; j < m; j++) { num++; if (num % length == 1 && bool) { if (num != 1) { System.out.println(); } if (m * n - num + 1 == length+reminder) { bool = false; System.out.print(length + reminder); } else { System.out.print(length); } } System.out.print(" " + (i + 1) + " " + (j + 1)); } } else { for (int j = m - 1; j >= 0; j--) { num++; if (num % length == 1 && bool) { System.out.println(); if (m * n - num + 1 == length+reminder) { bool = false; System.out.print(length + reminder); } else { System.out.print(length); } } System.out.print(" " + (i + 1) + " " + (j + 1)); } } } System.out.println(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
f6d733bd57ffeaffa5494a6344207a48
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { static boolean visited[][]; static int n, m, x, h = 0, counter = 0, k; public static void main(String[] args) throws IOException { Reader.init(System.in); n = Reader.nextInt(); m = Reader.nextInt(); visited = new boolean[n][m]; k = Reader.nextInt(); x = (n*m)/k; System.out.print(x + " "); DFS(0, 0); } static int dx[] = {0, 1, 0, -1,}; static int dy[] = {1, 0, -1, 0}; static void DFS(int r, int c){ if(visited[r][c]) return; visited[r][c] = true; counter++; System.out.print((r+1) + " " + (c+1) + " "); if(counter == x){ h++; if(h+1 == k) x += (n*m)%k; if(h == k) return; System.out.println(); System.out.print(x + " "); counter = 0; } for(int i = 0; i < 4; i++){ int x = r + dx[i], y = c + dy[i]; if(!valid(x, y) || visited[x][y]) continue; DFS(x, y); } } static boolean valid(int r, int c){ return r < n && c < m && r > -1 && c > -1; } } class Node { int r; int c; String s; public Node(int a, int b, String x) { s = x; r = a; c = b; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ public static int pars(String x) { int num = 0; int i = 0; if (x.charAt(0) == '-') { i = 1; } for (; i < x.length(); i++) { num = num * 10 + (x.charAt(i) - '0'); } if (x.charAt(0) == '-') { return -num; } return num; } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static void init(FileReader input) { reader = new BufferedReader(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 pars(next()); } static byte nextByte() throws IOException { return Byte.parseByte(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
5f3df5e6c04e0b311a7fdcc2b3193512
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public class Main{ final boolean isFileIO = false; BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String delim = " "; public static void main(String[] args) throws IOException { Main m = new Main(); m.initIO(); m.solve(); m.in.close(); m.out.close(); } public void initIO() throws IOException { if(!isFileIO) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("A-large-practice.in")); out = new PrintWriter("output.txt"); } } String nextToken() throws IOException { if(!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(delim); } String readLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void solve() throws IOException { int n, m, k; n = nextInt(); m = nextInt(); k = nextInt(); int dir = 1; boolean[][] used = new boolean[n + 2][m + 2]; int x, y; x = y = 1; for(int i = 0; i <= n + 1; i++) for(int j = 0; j <= m + 1; j++) used[i][j] = true; for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) used[i][j] = false; int[] r = new int[k]; int d = (n * m) / k; for(int i = 0; i < k; i++) r[i] = d; r[k - 1] += (n * m) % k; for(int i = 0; i < k; i++) { out.print(r[i] + " "); for(int j = 0; j < r[i]; j++) { out.print(x + " " + y + " "); used[x][y] = true; int _x, _y; _x = x; _y = y; if(dir == 1) _y++; if(dir == 2) _x++; if(dir == 3) _y--; if(dir == 4) _x--; if(used[_x][_y]) { dir = change_dir(dir); if(dir == 1) y++; if(dir == 2) x++; if(dir == 3) y--; if(dir == 4) x--; } else { x = _x; y = _y; } } out.println(); } } int change_dir(int cur) { if(cur == 1) // right cur = 2; else if(cur == 2) // down cur = 3; else if(cur == 3) //left cur = 4; else if(cur == 4) //up cur = 1; return cur; } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
2330e8566d36556d2f8da90be4d55615
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class ValeraAndTubes { private static boolean[][] grid; private static int i = 0, j = -1; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken()), len = n * m / k, last = len + (n * m % k); grid = new boolean[n][m]; while (k > 0) { if (k == 1) len = last; if (j + 1 < m && !grid[i][j + 1]) { System.out.print(len); dfs(n, m, len, i, j + 1); } else if (i + 1 < n && !grid[i + 1][j]) { System.out.print(len); dfs(n, m, len, i + 1, j); } else if (j - 1 > -1 && !grid[i][j - 1]) { System.out.print(len); dfs(n, m, len, i, j - 1); } else if (i - 1 > -1 && !grid[i - 1][j]) { System.out.print(len); dfs(n, m, len, i - 1, j); } k--; System.out.println(); } } private static void dfs(int n, int m, int len, int i, int j) { if (len == 0) return; grid[i][j] = true; ValeraAndTubes.i = i; ValeraAndTubes.j = j; System.out.print(" " + (i + 1) + " " + (j + 1)); if (j + 1 < m && !grid[i][j + 1]) dfs(n, m, len - 1, i, j + 1); else if (i + 1 < n && !grid[i + 1][j]) dfs(n, m, len - 1, i + 1, j); else if (j - 1 > -1 && !grid[i][j - 1]) dfs(n, m, len - 1, i, j - 1); else if (i - 1 > -1 && !grid[i - 1][j]) dfs(n, m, len - 1, i - 1, j); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
877a0677ac11200fa28f9825a25e35de
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Mahmoud Aladdin <aladdin3> */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader jin, OutputWriter jout) { int n = jin.int32(); int m = jin.int32(); int k = jin.int32(); int[] x = new int[n * m]; int[] y = new int[n * m]; for(int i = 0; i < n * m; i++) { x[i] = (i / m) + 1; y[i] = (i % m) + 1; } for(int i = 0; i < n * m; i++) { if(x[i] % 2 == 0) { y[i] = m - y[i] + 1; } } int ci = 0; int d = (n * m) / k; int r = (n * m) % k; for(int i = 0; i < k; i++) { int vv = d + ((i < r)? 1: 0); jout.print(vv); for(int j = 0; j < vv; j++) { jout.print("", x[ci], y[ci]); ci++; } jout.println(); } } } class InputReader { private static final int bufferMaxLength = 1024; private InputStream in; private byte[] buffer; private int currentBufferSize; private int currentBufferTop; private static final String tokenizers = " \t\r\f\n"; public InputReader(InputStream stream) { this.in = stream; buffer = new byte[bufferMaxLength]; currentBufferSize = 0; currentBufferTop = 0; } private boolean refill() { try { this.currentBufferSize = this.in.read(this.buffer); this.currentBufferTop = 0; } catch(Exception e) {} return this.currentBufferSize > 0; } private Byte readChar() { if(currentBufferTop < currentBufferSize) { return this.buffer[this.currentBufferTop++]; } else { if(!this.refill()) { return null; } else { return readChar(); } } } public String token() { StringBuffer tok = new StringBuffer(); Byte first; while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1)); if(first == null) return null; tok.append((char)first.byteValue()); while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) { tok.append((char)first.byteValue()); } return tok.toString(); } public Integer int32() throws NumberFormatException { String tok = token(); return tok == null? null : Integer.parseInt(tok); } } class OutputWriter { private final int bufferMaxOut = 1024; private PrintWriter out; private StringBuilder output; private boolean forceFlush = false; public OutputWriter(OutputStream outStream) { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream))); output = new StringBuilder(2 * bufferMaxOut); } public OutputWriter(Writer writer) { forceFlush = true; out = new PrintWriter(writer); output = new StringBuilder(2 * bufferMaxOut); } private void autoFlush() { if(forceFlush || output.length() >= bufferMaxOut) { flush(); } } public void print(Object... tokens) { for(int i = 0; i < tokens.length; i++) { if(i != 0) output.append(' '); output.append(tokens[i]); } autoFlush(); } public void println(Object... tokens) { print(tokens); output.append('\n'); autoFlush(); } public void flush() { out.print(output); output.setLength(0); } public void close() { flush(); out.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
15f97e55b8ba0cd58261251690542281
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.*; public class round441problemc { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int rowNum=in.nextInt(); int colNum=in.nextInt(); int tubeNum=in.nextInt(); int cellNum=rowNum*colNum/tubeNum; int row=1; int col=1; boolean colEnd=false; boolean colBegin=false; boolean[][] visit=new boolean[rowNum+1][colNum+1]; for(int i=0;i<tubeNum;i++){ if(i==tubeNum-1){ System.out.print(rowNum*colNum-cellNum*(tubeNum-1)+" "); for(int j=0;j<rowNum*colNum-cellNum*(tubeNum-1);j++){ System.out.print(row+" "); System.out.print(col+" "); visit[row][col]=true; if(col==colNum){ if(visit[row][col-1]==false){ col--; } else{ row++; } } else if(col==1){ if(visit[row][col+1]==false){ col++; } else{ row++; } } else{ if(visit[row][col+1]==false)col++; else{col--;} } } continue; } System.out.print(cellNum+" "); for(int j=0;j<cellNum;j++){ System.out.print(row+" "); System.out.print(col+" "); visit[row][col]=true; if(col==colNum){ if(visit[row][col-1]==false){ col--; } else{ row++; } } else if(col==1){ if(visit[row][col+1]==false){ col++; } else{ row++; } } else{ if(visit[row][col+1]==false)col++; else{col--;} } } System.out.println(""); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
816c3586b4356be5b67f40e4ebb4544b
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; import java.util.Vector; /** * Ashesh Vidyut (Drift King) * */ public class C { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); String nmk[] = (in.readLine()).split(" "); int n = Integer.parseInt(nmk[0]); int m = Integer.parseInt(nmk[1]); int k = Integer.parseInt(nmk[2]); String mat[][] = new String[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = (i+1)+" "+(j+1); } } Cells[] spiralpipe = spiralTraversal(mat, n, m); int i; for (i = 0; i < 2*(k - 1); i+=2) { out.write("2 "+spiralpipe[i].toString()+" "+spiralpipe[i+1].toString()); out.newLine(); } int rem = spiralpipe.length - ((k-1)*2); out.write(Integer.toString(rem)+" "); for (int j = i; j < spiralpipe.length; j++) { out.write(spiralpipe[j].toString()+" "); } out.newLine(); out.close(); } catch (Exception e) { e.printStackTrace(); } } public static Cells[] spiralTraversal(String mat[][], int n, int m){ int count = 0; Cells[] ar = new Cells[n*m]; int sr = 0; int sc = 0; int er = n-1; int ec = m-1; while(count != n * m){ for(int i = sc; (i <= ec) && (count != n * m); i++){ ar[count] = new Cells(sr+1, i+1); count++; if(count == n*m) break; } for(int i = sr+1; (i <= er) && (count != n * m); i++){ ar[count] = new Cells(i+1, ec+1); count++; if(count == n*m) break; } for(int i = ec-1; (i >= sc) && (count != n * m); i--){ ar[count] = new Cells(er+1, i+1); count++; if(count == n*m) break; } for(int i = er-1; (i > sr) && (count != n * m); i--){ ar[count] = new Cells(i+1, sc+1); count++; if(count == n*m) break; } if(count == n*m) { break; } sr++;ec--;er--;sc++; } return ar; } } class Cells{ int r,c; public Cells(int x, int y){ this.r = x; this.c = y; } public String toString(){ return this.r+" "+this.c; } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
d4925cb013c7e219013f98113c7b9f5a
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; //import java.util.logging.Level; //import java.util.logging.Logger; public class Main { BufferedReader read; BufferedWriter write; public static void main(String args[]) throws Exception { new Main().init("1"); } void init(String name) throws Exception { read= ri();//rf(name+".txt"); int p[]=ia(read.readLine()); int r=p[0],c=p[1],k=p[2]; node ans[]=new node[r*c+5]; int al=0; for(int i=1;i<=r;i++) { if(i%2!=0)for(int j=1;j<=c;j++)ans[al++]=new node(i,j); else for(int j=c;j>0;j--)ans[al++]=new node(i,j); } int l=0; for(int i=1;i<k;i++) { System.out.println(2+" "+ans[l].i+" "+ans[l++].j+" "+ans[l].i+" "+ans[l++].j); } System.out.print(r*c-2*(k-1)); for(;l<al;l++)System.out.print(" "+ans[l].i+" "+ans[l].j); //s+=ans[l].i+" "+ans[l].j+" "; System.out.println(); } class node { int i;int j; node(int i,int j) { this.i=i; this.j=j; } } int i(String s){return Integer.parseInt(s.trim());} long l(String s){return Long.parseLong(s.trim());} int[] ia(String s1){String s[]=s1.trim().split(" ");int p[]=new int[s.length];for(int i=0;i<s.length;i++)p[i]=Integer.parseInt(s[i]);return p;} long[] la(String s) { String s1[]=s.split(" "); long la[]=new long[s1.length]; for(int i=0;i<s1.length;i++)la[i]=l(s1[i]); return la; } static BufferedWriter wf(String s) throws Exception{return new BufferedWriter(new FileWriter(new File(s)));} static BufferedReader rf(String s) throws Exception{return new BufferedReader(new FileReader(new File(s)));} static BufferedReader ri() throws Exception{return new BufferedReader(new InputStreamReader(System.in));} }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
29ce1067b8b1b99aa27914d0c4912a71
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.IOException; import java.util.Scanner; public class Main { public static int n,m,k,r; public static boolean[][]g ; public static int curr; public static int x,y; public static void main(String[]args) throws IOException{ Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); r = (n*m)/k; g = new boolean[n][m]; int rem = (n*m)%k; curr = rem+r; x = 1; y = 1; System.out.print(curr+" "+x+" "+y+" "); g[x-1][y-1] = true; curr--; while(k!=0){ goRight(); goDown(); goLeft(); goUp(); } } private static void goLeft() { while(y-1>0 && !g[x-1][y-2] && k!=0){ y--; g[x-1][y-1] = true; System.out.print(x+" "+y+" "); curr--; if(curr==0){ k--; if(k==0) break; System.out.println(); System.out.print(r+" "); curr = r; } } } private static void goUp() { while(x-1>0 && !g[x-2][y-1] && k!=0){ x--; g[x-1][y-1] = true; System.out.print(x+" "+y+" "); curr--; if(curr==0){ k--; if(k==0) break; System.out.println(); System.out.print(r+" "); curr = r; } } } private static void goDown() { while(x+1<=n && !g[x][y-1] && k!=0){ x++; g[x-1][y-1] = true; System.out.print(x+" "+y+" "); curr--; if(curr==0){ k--; if(k==0) break; System.out.println(); System.out.print(r+" "); curr = r; } } } private static void goRight() { while(y+1<=m && !g[x-1][y] && k!=0){ y++; g[x-1][y-1] = true; System.out.print(x+" "+y+" "); curr--; if(curr==0){ k--; if(k==0) break; System.out.println(); System.out.print(r+" "); curr = r; } } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
9321f21c09f2a9eaa38400c004e89156
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class ValeraAndTubes { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int K = sc.nextInt(); ArrayList<Location> locs = new ArrayList<Location>(); for (int x = 1; x <= N; x++) { if (x % 2 == 1) { for (int y = 1; y <= M; y++) { locs.add(new Location(x, y)); } } else { for (int y = M; y >= 1; y--) { locs.add(new Location(x, y)); } } } int curr = 0; for (int i = 1; i < K; i++) { System.out.println("2 " + locs.get(curr++) + " " + locs.get(curr++)); } System.out.print(locs.size() - curr); for (int i = curr; i < locs.size(); i++) { System.out.print(" " + locs.get(i)); } System.out.println(); } public static class Location { public int X; public int Y; public Location(int x, int y) { this.X = x; this.Y = y; } @Override public String toString() { return (X + " " + Y); } } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
a214eac99acdf62cba588dd5b167add3
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public final class varela_and_tubes { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static ArrayList<Pair>[] al; static List<Pair> list=new ArrayList<Pair>(); @SuppressWarnings("unchecked") public static void main(String args[]) throws Exception { int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); al=new ArrayList[k]; for(int i=0;i<k;i++) { al[i]=new ArrayList<Pair>(); } boolean left=true; for(int i=1;i<=n;i++) { if(left) { for(int j=1;j<=m;j++) { list.add(new Pair(i,j)); } } else { for(int j=m;j>=1;j--) { list.add(new Pair(i,j)); } } left=!left; } int ptr=list.size()-1; for(int i=0;i<k-1;i++) { for(int j=0;j<2;j++) { al[i].add(list.get(ptr--)); } } for(int i=0;i<=ptr;i++) { al[k-1].add(list.get(i)); } for(int i=0;i<k;i++) { out.print(al[i].size()+" "); for(Pair p:al[i]) { out.print(p.x+" "+p.y+" "); } out.println(""); } out.close(); } } class Pair { int x,y; public Pair(int x,int y) { this.x=x; this.y=y; } } 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 String next() throws Exception { return nextToken().toString(); } 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()); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
72cd885938b7354287bbd9b832504ac7
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * User: Andreev Kirill * Date: 18.06.14 */ public class Pipes { FastScanner in; PrintWriter out; class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new Pipes().run(); } public void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } ////////////////////////////////// int n; int m; int x = 0; int y = -1; int direction = 1; void nextCell(){ int next = y + direction; if (next >= 0 && next < m) { y = next; } else { x++; direction = -direction; } out.print(Integer.toString(x + 1) + " " + Integer.toString(y + 1) + " "); } public void solve() { n = in.nextInt(); m = in.nextInt(); int k = in.nextInt(); for (int i = 0; i < k - 1; i++) { out.print("2 "); nextCell(); nextCell(); out.println(); } int left = m * n - 2 * (k - 1); out.print(left + " "); for (int i = 0; i < left; i++) { nextCell(); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
ea9237811dd2496158ca75333e9e2a24
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.Scanner; public class Main { public static int cR, cC; // current row and column public static int n, m; // number of rows and number of columns public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); // number of rows m = sc.nextInt(); // number of columns int k = sc.nextInt(); // number of tubes int numTubesLaid = 0; cR = 1; cC = 1; // Algorithm: We take a snake-like path that hits all cells in the table, starting in the top // left corner and moving through one complete row at a time. We always lay tubes of length 2, // except for possibly the last tube, which will cover all the remaining cells. while (numTubesLaid < k - 1) { System.out.print("2 " + cR + " " + cC + " "); move(); System.out.println(cR + " " + cC); move(); numTubesLaid++; } // Lay the last tube. System.out.print((n * m - 2 * (k - 1)) + " " + cR + " " + cC + " "); do { move(); System.out.print(cR + " " + cC + " "); } while (!done(cR, cC)); } public static void move() { if (cR % 2 == 1) { // moving right if (cC == m) { cR++; } else { cC++; } } else { // moving left if (cC == 1) { cR++; } else { cC--; } } } public static boolean done(int cR, int cC) { if (n % 2 == 0) { return (cR == n && cC == 1); } else { return (cR == n && cC == m); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
5ec4a312c45d4fabb7cec3afc9db6b97
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static String n1, n2;public static long min; public static int mod = 1000000007; public static void main(String[] args)throws IOException { OutputWriter out=new OutputWriter(System.out); Reader r=new Reader(); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); //StringTokenizer st =new StringTokenizer(br.readLine()); //int n =Integer.parseInt(st.nextToken()); //int nr =Integer.parseInt(st.nextToken()); int n=r.nextInt(); int m=r.nextInt(); int k=r.nextInt(); int dir=1; //if curr direction = right then dir =1 else dir = -1 if direction =left int currx=1;int curry=1; //curr cells StringBuilder sb=null; for(int i=1;i<=k-1;i++) { sb = new StringBuilder("2"); for(int j=1;j<=2;j++) { sb.append(" "+curry+" "+currx); if(dir==1) {if(currx==m) {curry++;dir=-1;} else currx++; } else { if(currx==1) {curry++;dir=1;} else currx--; } } System.out.println(sb.toString()); } //System.out.println(dir+" "+currx+" "+curry); sb=new StringBuilder(String.valueOf(m*n-2*(k-1))); while(curry<=n) { sb.append(" "+curry+" "+currx); if(dir==1) {if(currx==m) {curry++;dir=-1;} else currx++; } else { if(currx==1) {curry++;dir=1;} else currx--; } } System.out.println(sb.toString()); } } class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
c4eb1593ef2b62108e9f6c490e0b5fd9
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class C implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter{ final int DEFAULT_PRECISION = 12; int precision; String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// void solve() throws IOException { int rowsCount = readInt(); int columnsCount = readInt(); int pipesCount = readInt(); int currentRow = 1, currentColumn = 1; int currentPipesCount = 0; while (++currentPipesCount < pipesCount) { int pipeLength = 2; out.print(pipeLength + " " + currentRow + " " + currentColumn); if ((currentRow & 1) == 1) { if (currentColumn == columnsCount) { currentRow++; } else { ++currentColumn; } } else { if (currentColumn == 1) { ++currentRow; } else { --currentColumn; } } out.println(" " + currentRow + " " + currentColumn); if ((currentRow & 1) == 1) { if (currentColumn == columnsCount) { currentRow++; } else { ++currentColumn; } } else { if (currentColumn == 1) { ++currentRow; } else { --currentColumn; } } } int lastPipeLength = rowsCount * columnsCount - ((pipesCount - 1) << 1); out.print(lastPipeLength); while (currentRow <= rowsCount) { out.print(" " + currentRow + " " + currentColumn); if ((currentRow & 1) == 1) { if (currentColumn == columnsCount) { currentRow++; } else { ++currentColumn; } } else { if (currentColumn == 1) { ++currentRow; } else { --currentColumn; } } } out.println(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
a38196a91c7a9f6d8f0a766d8af98714
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
//package spoj; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class Back { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int r=s.nextInt(); int c=s.nextInt(); int pipes=s.nextInt(); int q=(r*c)/pipes;//no. of nodes in a pipe int rem=(r*c)%pipes; int p=0,xadd=1; int x=1,y=1; x=y=1; int covered = 0; for (int i = 0; i < pipes - 1; i++) { System.out.print(q); for (int j = 0; j < q; j++) { System.out.print(" "+x+" "+y); if (x % 2 == 1) { y++; if (y > c) { x++; y = c; } } else { y--; if (y < 1) { x++; y = 1; } } covered++; } System.out.println(); } System.out.print((r * c) - covered); for (int i = covered;i < r*c; i++) { System.out.print(" "+x+" "+y); if (x % 2 == 1) { y++; if (y > c) { x++; y = c; } } else { y--; if (y < 1) { x++; y = 1; } } } System.out.println(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
9aa9d98b507d3369f470d016fbe95d9d
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public class Main { public Scanner sc; private final int[] dy = { 1, -1 }; public void run() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int x = 1, y = 1, d = 0; for (int i = 0; i < k; i++) { int cnt = 0; ArrayList<Integer> xs = new ArrayList<>(); ArrayList<Integer> ys = new ArrayList<>(); while (true) { if (i < k-1 && cnt == 2) break; else if (x > n) break; xs.add(x); ys.add(y); if ((d == 0 && y == m) || (d == 1 && y == 1)) { x++; d = 1-d; } else { y += dy[d]; } cnt++; } System.out.print(xs.size() + " "); for (int j = 0; j < xs.size(); j++) System.out.print(xs.get(j) + " " + ys.get(j) + " "); System.out.println(); if (x > n) break; } } public static void main(String[] args) { Main main = new Main(); try { main.sc = new Scanner(new FileInputStream("test.in")); } catch (FileNotFoundException e) { main.sc = new Scanner(System.in); } main.run(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
e60d44fe6ca98dd2e51edaa373893281
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String []args) throws FileNotFoundException, IOException { Scanner br = new Scanner(System.in); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = br.nextInt(); int m = br.nextInt(); int k = br.nextInt(); List<List<Integer>> l = new ArrayList<List<Integer>>(); int i = 1; int j = 1; int iChange = 1; int curTubeLength = 0; int step = 1; int spaceForTube = (n * m) / k; int leftOver = (n * m) % k; for (int t = 0; t < k; t++) { List<Integer> ll = new ArrayList<Integer>(); while (true) { curTubeLength++; ll.add(i); ll.add(j); if ((j == m || j == 1) && iChange == 0) { i += 1; step = -step; iChange = 2; } if (iChange == 2) { iChange = 1; } else if (iChange == 1) { j += step; iChange = 0; } else { j += step; } if (curTubeLength == spaceForTube) { curTubeLength = 0; break; } } if ((k - 1) == t) { for (int p = 0; p < leftOver; p++) { ll.add(i); ll.add(j); if ((j == m || (j == 1 && t != 0)) && iChange == 0) { i += 1; step = -step; iChange = 2; } if (iChange == 2) { iChange = 1; } else if (iChange == 1) { j += step; iChange = 0; } else { j += step; } } } l.add(ll); } for (List<Integer> list : l) { bw.write(list.size()/2 + " "); for (Integer o : list) { bw.write(o + " "); } bw.newLine(); } bw.close(); br.close(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
237fc5eb5d37a4c6e4b3c7a89f6c9ae3
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * 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 DELL */ public class Problem_C { public static void main(String[] args) throws IOException { BufferedReader x = new BufferedReader(new InputStreamReader(System.in)); String s = x.readLine(); String[] s1 = s.split(" "); int n = Integer.parseInt(s1[0]); int m = Integer.parseInt(s1[1]); int k = Integer.parseInt(s1[2]); String[] t = new String[k]; int gg=(n*m)/k; int zz = n * m - gg * (k - 1); int [] xx=new int[k]; boolean right = true; int q=0; for(int i=0;i<m*n;i++){ xx[q]++; q++; q=q%k; } for (int i = 0; i < k - 1; i++) { t[i] = xx[i]+" "; } t[k - 1] = zz + " "; String rs=""; int cnt=0; int in=0; System.out.print(xx[0]+" "); for (int i = 1; i < n + 1; i++) { if(right){ for(int j=1;j<m+1;j++){ System.out.print(i + " "+ j+" "); cnt++; if(in!=k-1 && cnt==xx[in]){ cnt=0; in++; System.out.println(""); System.out.print(xx[in]+" "); } } right=!right; } else { for(int j=m;j>0;j--){ System.out.print(i + " "+ j+" "); cnt++; if(in!=k-1 && cnt==xx[in]){ cnt=0; in++; System.out.println(""); System.out.print(xx[in]+" "); } } right=!right; } } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
b2bb3694fd3b8ac8a190c0ab078f7c4f
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; public class ValeraAndTubes { static class P { int x, y; public P(int i, int j) { x = i; y = j; } public String toString() { return x + " " + y; } } public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String l[] = bf.readLine().split(" "); int n = Integer.parseInt(l[0]); int m = Integer.parseInt(l[1]); int k = Integer.parseInt(l[2]); LinkedList<P> nextPair = new LinkedList<P>(); boolean alter = false; for (int i = 0; i < n; i++) { for (int j = alter ? m - 1 : 0; (alter ? j >= 0 : j < m);) { nextPair.add(new P(i + 1, j + 1)); if (alter) j--; else j++; } alter = !alter; } int max = (n * m) / k; int left = (n * m) % k; while (k-- > 0) { int i = 0; if (k == 0) System.out.print((max + left) + " "); else System.out.print(max + " "); while (i++ < max && !nextPair.isEmpty()) System.out.print(nextPair.remove(0) + " "); while (k == 0 && !nextPair.isEmpty()) System.out.print(nextPair.remove(0) + " "); System.out.println(); } } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
84303aa3159697bc70dd63766905f049
train_003.jsonl
1402241400
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: r ≥ 2; for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.
256 megabytes
import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; public class ValeraTubes441C { public static void main(String[] args) { Scanner br = new Scanner(System.in); int rows = br.nextInt(), cols = br.nextInt(), tubes = br.nextInt(); int[][] grid = new int[rows][cols]; int[] counts = new int[tubes]; int inc = 1, count = 0, tube = 1; int j = 0; for(int i = 0; i < rows; i++){ for(;j >= 0 && j < cols; j += inc){ grid[i][j] = tube; count++; if(count >= 2 && tube < tubes){ counts[tube - 1] = count; tube++; count = 0; } } inc *= -1; j += inc; } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); counts[tubes - 1] = count; tube = 0; j = 0; inc = 1; out.print(counts[tube]); for(int i = 0; i < rows; i++){ for(;j >= 0 && j < cols; j += inc){ if(grid[i][j] == tube + 1){ out.printf(" %d %d", i + 1, j + 1); } else if(grid[i][j] > (tube + 1)){ out.println(); tube++; j -= inc; if(tube < tubes){ out.print(counts[tube]); } } } inc *= -1; j += inc; } out.flush(); } }
Java
["3 3 3", "2 3 1"]
1 second
["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"]
NotePicture for the first sample: Picture for the second sample:
Java 7
standard input
[ "constructive algorithms", "implementation", "dfs and similar" ]
779e73c2f5eba950a20e6af9b53a643a
The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.
1,500
Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
53ade5dfe6ed9f6b6ae8019658a55b70
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import sun.reflect.generics.tree.Tree; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; /** * Created by Anna on 28.09.2016. */ public class TaskD { BufferedReader in; PrintWriter out; StringTokenizer st; public static void main(String[] args) throws IOException { TaskD task = new TaskD(); task.open(); task.solve(); task.close(); } class Vertex implements Comparable<Vertex> { int ind; int size = 0; Vertex parent; ArrayList<Vertex> children = new ArrayList<>(); public Vertex(int ind, Vertex parent) { this.ind = ind; this.parent = parent; } @Override public int compareTo(Vertex o) { if (this.size != o.size) return Integer.compare(this.size, o.size); return Integer.compare(this.ind, o.ind); } } Vertex[] graph; int[] center; TreeSet<Vertex> dfs(Vertex v) { TreeSet<Vertex> current = new TreeSet<>(); for (Vertex child : v.children) { TreeSet<Vertex> childSet = dfs(child); if (childSet.size() > current.size()) { TreeSet<Vertex> tmp = current; current = childSet; childSet = tmp; } current.addAll(childSet); } v.size = current.size() + 1; current.add(v); Vertex searchVert = new Vertex(-1, null); searchVert.size = (v.size + 1) / 2; center[v.ind] = current.ceiling(searchVert).ind; return current; } private void solve() throws IOException { int n = nextInt(); int q = nextInt(); graph = new Vertex[n]; center = new int[n]; Arrays.fill(center, -1); for (int i = 0; i < n; i++) { graph[i] = new Vertex(i, null); } for (int i = 1; i < n ; i++) { final int parent = nextInt() - 1; graph[parent].children.add(graph[i]); graph[i].parent = graph[i]; } dfs(graph[0]); for (int i = 0; i < q; i++) { int v = nextInt() - 1; out.println(center[v] + 1); } } private void close() { out.flush(); out.close(); } private void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; st = new StringTokenizer(str); } return st.nextToken(); } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
b47c409e4b58a354d152ea7b6dc8e0fb
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import java.util.TreeSet; public class Main { static ContestScanner in;static Writer out;public static void main(String[]args) {try{in=new ContestScanner();out=new Writer();Main solve=new Main();solve.solve(in,out); in.close();out.close();}catch(IOException e){e.printStackTrace();}} void dump(int[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} void dump(int[]a,int n){for(int i=0;i<a.length;i++)out.printf("%"+n+"d",a[i]);out.println();} void dump(long[]a){for(int i=0;i<a.length;i++)out.print(a[i]+" ");out.println();} void dump(char[]a){for(int i=0;i<a.length;i++)out.print(a[i]);out.println();} long pow(long a,long n){long r=1;while(n>0){if((n&1)==1)r*=a;a*=a;n>>=1;}return r;} String itob(int a,int l){return String.format("%"+l+"s",Integer.toBinaryString(a)).replace(' ','0');} void sort(int[]a){m_sort(a,0,a.length,new int[a.length]);} void m_sort(int[]a,int s,int sz,int[]b) {if(sz<7){for(int i=s;i<s+sz;i++)for(int j=i;j>s&&a[j-1]>a[j];j--)swap(a,j,j-1);return;} m_sort(a,s,sz/2,b);m_sort(a,s+sz/2,sz-sz/2,b);int idx=s;int l=s,r=s+sz/2;final int le=s+sz/2,re=s+sz; while(l<le&&r<re){if(a[l]>a[r])b[idx++]=a[r++];else b[idx++]=a[l++];} while(r<re)b[idx++]=a[r++];while(l<le)b[idx++]=a[l++];for(int i=s;i<s+sz;i++)a[i]=b[i]; } /* qsort(3.5s)<<msort(9.5s)<<<shuffle+qsort(17s)<Arrays.sort(Integer)(20s) */ void swap(int[]a,int i,int j){final int t=a[i];a[i]=a[j];a[j]=t;} int binarySearchSmallerMax(int[]a,int v)// get maximum index which a[idx]<=v {int l=0,r=a.length-1,s=0;while(l<=r){int m=(l+r)/2;if(a[m]>v)r=m-1;else{l=m+1;s=m;}}return a[s]>v?-1:s;} void solve(ContestScanner in,Writer out)throws IOException{ int n = in.nextInt(); int q = in.nextInt(); tree = new List[n]; for(int i=0; i<n; i++) tree[i] = new ArrayList<>(); for(int i=1; i<n; i++){ final int p = in.nextInt()-1; tree[p].add(i); } ans = new int[n]; dfs(0); for(int i=0; i<q; i++){ int v = in.nextInt()-1; out.println(ans[v]+1); } } int[] ans; List<Integer>[] tree; Node seeker = new Node(-1, 0); TreeSet<Node> dfs(int c){ TreeSet<Node> res = new TreeSet<>(); int max = 0; for(int v: tree[c]){ TreeSet<Node> s = dfs(v); max = Math.max(max, s.size()); res = merge(res, s); } final int size = res.size()+1; res.add(new Node(c, size)); if(max<=size/2) ans[c] = c; else{ seeker.st = (size+1)/2; Node ceil = res.ceiling(seeker); if(ceil==null){ System.err.println("Null error"); return res; } ans[c] = ceil.id; } return res; } TreeSet<Node> merge(TreeSet<Node> a, TreeSet<Node> b){ if(a.size()>b.size()){ TreeSet<Node> tmp = a; a = b; b = tmp; } b.addAll(a); return b; } } class Node implements Comparable<Node>{ int id, st; Node(int id, int st){ this.id = id; this.st = st; } @Override public int compareTo(Node o) { if(st != o.st) return st-o.st; return id-o.id; } } class MultiSet<T> extends HashMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key) {final int v=get(key);if(v==1)remove(key);else put(key,v-1);} } class OrderedMultiSet<T> extends TreeMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key) {final int v=get(key);if(v==1)remove(key);else put(key,v-1);} } class Pair implements Comparable<Pair>{ int a,b;int hash;Pair(int a,int b){this.a=a;this.b=b;hash=(a<<16|a>>16)^b;} public boolean equals(Object obj){Pair o=(Pair)(obj);return a==o.a&&b==o.b;} public int hashCode(){return hash;} public int compareTo(Pair o){if(a!=o.a)return a<o.a?-1:1;else if(b!=o.b)return b<o.b?-1:1;return 0;} public String toString() {return String.format("(%d, %d)", a, b);} } class Timer{ long time; public void set(){time=System.currentTimeMillis();} public long stop(){return time=System.currentTimeMillis()-time;} public void print() {System.out.println("Time: "+(System.currentTimeMillis()-time)+"ms");} @Override public String toString(){return"Time: "+time+"ms";} } class Writer extends PrintWriter{ public Writer(String filename)throws IOException {super(new BufferedWriter(new FileWriter(filename)));} public Writer()throws IOException{super(System.out);} } class ContestScanner implements Closeable{ private BufferedReader in;private int c=-2; public ContestScanner()throws IOException {in=new BufferedReader(new InputStreamReader(System.in));} public ContestScanner(String filename)throws IOException {in=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));} public String nextToken()throws IOException { StringBuilder sb=new StringBuilder(); while((c=in.read())!=-1&&Character.isWhitespace(c)); while(c!=-1&&!Character.isWhitespace(c)){sb.append((char)c);c=in.read();} return sb.toString(); } public String readLine()throws IOException{ StringBuilder sb=new StringBuilder();if(c==-2)c=in.read(); while(c!=-1&&c!='\n'&&c!='\r'){sb.append((char)c);c=in.read();} return sb.toString(); } public long nextLong()throws IOException,NumberFormatException {return Long.parseLong(nextToken());} public int nextInt()throws NumberFormatException,IOException {return(int)nextLong();} public double nextDouble()throws NumberFormatException,IOException {return Double.parseDouble(nextToken());} public void close() throws IOException {in.close();} }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
69f1a03b125d536d5bce8337c43722e2
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class D { FastScanner scanner; PrintWriter writer; class Node { int n; Node parent; List<Node> children = new ArrayList<>(); int size; Node center; Node bigChild; public Node(int n) { this.n = n; } } boolean isCenter(Node n, Node c) { return n.size - c.size <= n.size / 2 && c.bigChild.size <= n.size / 2; } void dfs(Node n) { for (Node child : n.children) { dfs(child); n.size += child.size; if (n.bigChild == null || n.bigChild.size < child.size) { n.bigChild = child; } } n.size++; if (n.bigChild == null) { n.center = n; n.bigChild = n; return; } n.center= n.bigChild.center; while (!isCenter(n, n.center)) { n.center = n.center.parent; } } void solve() throws IOException { scanner = new FastScanner(System.in); writer = new PrintWriter(System.out); int n = scanner.nextInt(); int q = scanner.nextInt(); List<Node> nodes = new ArrayList<>(); for (int i = 0; i < n; i++) { nodes.add(new Node(i)); } for (int i = 1; i < n; i++) { int p = scanner.nextInt() - 1; Node parent = nodes.get(p); Node child = nodes.get(i); child.parent = parent; parent.children.add(child); } dfs(nodes.get(0)); for (int i = 0; i < q; i++) { int v = scanner.nextInt() - 1; writer.println(nodes.get(v).center.n + 1); } writer.close(); } public static void main(String... args) throws IOException { new D().solve(); } static class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(String fileName) throws FileNotFoundException { this(new FileInputStream(new File(fileName))); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
219aca5c68f872456a4d6455f01ff524
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import static java.lang.Math.* ; import static java.util.Arrays.* ; import java.util.*; import java.io.*; public class D{ int N, L[], P[][]; ArrayList<Integer> [] adjList ; int [] size ; int [] centroid ; int dfs(int u , int p) { int sz = 1 ; int c = u; for(int v : adjList[u]) if(v != p) { sz += dfs(v, u); if(size[v] > size[c]) c = v ; } P[u][0] = c ; size[u] = sz ; return sz ; } void preprocessChildren() { int k = 0; while(1<<k+1 < N) ++k; P = new int[N][k + 1]; size = new int [N] ; dfs(0 , 0); for(int j = 1; j <= k; j++) for(int i = 0; i < N; i++) if(P[i][j-1] != -1) P[i][j] = P[P[i][j-1]][j-1]; } void preCompute(int u) { int k = 0; while(1<<k+1 < N) ++k; int x = u ; for (int i = k; i >= 0; i--) if(P[x][i] != -1) { if(size[P[x][i]] * 2 >= size[u]) x = P[x][i] ; } centroid[u] = x ; } void main() throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt() ; int q = sc.nextInt() ; N = n ; adjList = new ArrayList[N] ; for(int i = 0 ;i < N ;i++) adjList[i] = new ArrayList<>() ; for(int v = 1 ;v < n ;v++) { int u = sc.nextInt() - 1 ; adjList[u].add(v) ; } preprocessChildren(); centroid = new int [N] ; for(int i = 0 ; i< N ;i++) preCompute(i); while(q-->0) { int x = sc.nextInt() - 1; out.println(centroid[x] + 1); } out.flush(); out.close(); } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next());} } public static void main (String [] args) throws Exception {(new D()).main();} }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
2afcfc3e6faf63f884b76bae3cc412ac
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.*; import java.util.*; /** * * @author Sourav Kumar Paul */ public class SolveD { public static int size[],parent[],centroid[]; public static ArrayList<Integer> adj[]; public static void main(String[] args) throws IOException{ Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int q = in.nextInt(); adj = new ArrayList[n]; for(int i=0; i<n; i++) adj[i] = new ArrayList<>(); for(int i=0; i<n-1; i++) { int x =in.nextInt()-1; // adj[i+1].add(x); adj[x].add(i+1); } size = new int[n]; parent = new int[n]; centroid = new int[n]; dfs(0,-1); // out.println(Arrays.toString(size)); dfs_c(0,-1); for(int i=0; i<q; i++) { int x = in.nextInt()-1; out.println(centroid[x]+1); } out.flush(); out.close(); } private static void dfs(int start, int pa) { parent[start] = pa; size[start] = 1; for(int v: adj[start]) { if(v!= pa) { dfs(v, start); size[start] += size[v]; } } } private static void dfs_c(int start, int pa) { if(size[start]==1) { centroid[start] = start; return; } int p =0; for(int v=0; v<adj[start].size(); v++) { if(adj[start].get(v) != pa){ dfs_c(adj[start].get(v), start); if(size[adj[start].get(v)] > size[adj[start].get(p)]) p = v; } } int c = centroid[adj[start].get(p)]; while(!valid(start,c)){ c = parent[c]; } centroid[start] =c ; } private static boolean valid(int start, int c) { return (2*(size[start] - size[c]) <= size[start]); } public static class Reader { public BufferedReader reader; public StringTokenizer st; public Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() throws IOException{ return reader.readLine(); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
4aa383ea43f821e96b852c95bf6fc55a
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; 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 */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[] maxWeight; int[] size; int[] tree; int[] centroid; List<Integer>[] subtree; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), q = in.nextInt(), i, j; tree = new int[n]; maxWeight = new int[n]; size = new int[n]; centroid = new int[n]; subtree = new List[n]; for (i = 0; i < n; i++) { subtree[i] = new ArrayList<>(); } for (i = 1; i < n; i++) { tree[i] = in.nextInt() - 1; subtree[tree[i]].add(i); } recur(0); // DebugUtils.print(size); // DebugUtils.print(maxWeight); // DebugUtils.print(centroid); // DebugUtils.print(subtree); while (q-- > 0) { j = in.nextInt() - 1; out.printLine(centroid[j] + 1); } } public int recur(int node) { int total = 0, max = 0, maxIndex = -1, p; for (int x : subtree[node]) { p = recur(x); total += p; if (p > max) { max = p; maxIndex = x; } } maxWeight[node] = max; size[node] = 1 + total; if (size[node] >= 2 * maxWeight[node]) { centroid[node] = node; } else { int x = centroid[maxIndex]; while (size[x] * 2 <= size[node]) { x = tree[x]; } centroid[node] = x; } return size[node]; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { BufferedReader in; StringTokenizer tokenizer = null; public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
57f853810a9b30ec70a2e25675955ba9
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer buffer; static class Node { int index; int subTreeSize; List<Node>children; Node centroid; Node parent; public Node(int index) { this.index = index; this.centroid = null; this.parent = null; children = new ArrayList<Node>(); } public void calcSubTreeSize() { this.subTreeSize = 1; for (Node child: children) { child.calcSubTreeSize(); subTreeSize += child.subTreeSize; } } public void findCentroid() { Node largest = null; for (Node child: children) { child.findCentroid(); if (largest == null || child.subTreeSize > largest.subTreeSize) { largest = child; } } if (largest == null || largest.subTreeSize*2 <= this.subTreeSize) { this.centroid = this; } else { this.centroid = largest.centroid; while (centroid.subTreeSize*2 <= this.subTreeSize) { centroid = centroid.parent; } } } } public static void solve() { int n = ni(), q = ni(); Node[] nodes = new Node[n]; for (int i=0;i<n;i++) nodes[i] = new Node(i); for (int i=1;i<n;i++) { Node p = nodes[ni()-1]; nodes[i].parent = p; p.children.add(nodes[i]); } Node root = nodes[0]; root.calcSubTreeSize(); root.findCentroid(); for (int i=0;i<q;i++) { out.println(nodes[ni()-1].centroid.index+1); } } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } static String next() { while (buffer == null || !buffer.hasMoreElements()) { try { buffer = new StringTokenizer(in.readLine()); } catch (IOException e) { } } return buffer.nextToken(); } static int ni() { return Integer.parseInt(next()); } static long nl() { return Long.parseLong(next()); } static double nd() { return Double.parseDouble(next()); } static String ns() { return next(); } static int[] ni(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = Integer.parseInt(next()); return res; } static long[] nl(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = Long.parseLong(next()); return res; } static double[] nd(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) res[i] = Double.parseDouble(next()); return res; } static String[] ns(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = next(); return res; } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
8a4aa2c729493bef42054c43be4c840d
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int n; int q; IntArrayList[] gr; int[] parent; int[] size; int[] ans; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); q = in.readInt(); gr = new IntArrayList[n + 1]; for (int v = 1; v <= n; v++) { gr[v] = new IntArrayList(); } parent = new int[n + 1]; for (int v = 2; v <= n; v++) { int p = in.readInt(); parent[v] = p; gr[p].add(v); } size = new int[n + 2]; initSize(1); for (int v = 1; v <= n; v++) { size[v] *= 2; } for (int v = 1; v <= n; v++) { gr[v].sort((first, second) -> -(size[first] - size[second])); } ans = new int[n + 1]; //f(1, new TreeSet<>((a,b)->size[a] - size[b])); f(1, new TreeSet<>((a, b) -> size[a] - size[b])); for (int iter = 0; iter < q; iter++) { int v = in.readInt(); out.printLine(ans[v]); } } private void f(int v, TreeSet<Integer> set) { for (int j = 1; j < gr[v].size(); j++) { int to = gr[v].get(j); f(to, new TreeSet<>((a, b) -> size[a] - size[b])); } if (0 < gr[v].size()) { f(gr[v].get(0), set); } set.add(v); size[n + 1] = size[v] / 2; ans[v] = set.ceiling(n + 1); } private void initSize(int v) { size[v] = 1; for (Integer to : gr[v]) { initSize(to); size[v] += size[to]; } } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } } 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 printLine(int i) { writer.println(i); } } static interface IntComparator { public int compare(int first, int second); } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntReversableCollection extends IntCollection { } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
c711653a2bb033dbf824e2bd55a1bddb
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.util.*; import java.io.*; public class Kay_and_Snowflake { public static int n; public static ArrayList<ArrayList<Integer>> adj; public static int[] ans, id; public static TreeSet<Pair> dfs(int x) { id[x] = x; int size = 1; int max = 0; TreeSet<Pair> set = new TreeSet<Pair>(); /* DFS Through Points and Generate Data */ for (int i : adj.get(x)) { TreeSet<Pair> tmp = dfs(i); size += tmp.size(); max = Math.max(max, tmp.size()); set = union(set, tmp); } set.add(new Pair(x, size)); /* Get Answer */ if (max < (size + 1) / 2) { ans[x] = x; } else { ans[x] = set.ceiling(new Pair(0, (size + 1) / 2)).n; } return set; } public static TreeSet<Pair> union(TreeSet<Pair> a, TreeSet<Pair> b) { if (a.size() > b.size()) { a.addAll(b); return a; } else { b.addAll(a); return b; } } public static void main(String[] args) throws IOException { /* Read in Input */ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); n = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken()); adj = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i <= n; i++) { ArrayList<Integer> tl = new ArrayList<Integer>(); adj.add(tl); } st = new StringTokenizer(f.readLine()); for (int i = 2; i <= n; i++) { int p = Integer.parseInt(st.nextToken()); adj.get(p).add(i); } /* DFS Through Nodes to Find Centroids */ ans = new int[n + 1]; id = new int[n + 1]; dfs(1); /* Answer Queries */ for (int i = 0; i < q; i++) { st = new StringTokenizer(f.readLine()); int v = Integer.parseInt(st.nextToken()); System.out.println(ans[v]); } f.close(); } public static class Pair implements Comparable<Pair> { /* Class for Storing Data */ public int n, v; public Pair(int n, int v) { this.n = n; this.v = v; } /* Make Compare Operator for TreeSet Sorting */ public int compareTo(Pair o) { if (v == o.v) { if (n == o.n) { return 0; } else { return n < o.n ? -1 : 1; } } else { return v < o.v ? -1 : 1; } } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
8a74907afa13ae2dd359b9915736bd6d
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; public class D { private static class Task { ArrayList<Integer>[] graph; ArrayList<Integer>[] inv; int N; int[] children; int[] centroid; int[] maxPart; ArrayList<Integer>[] map; int dfs(int v) { for (int u : graph[v]) { int d = dfs(u); children[v] += d; maxPart[v] = Math.max(maxPart[v], d); } if (children[v] == 0 || maxPart[v] * 2 <= children[v] + 1) centroid[v] = v; return children[v] + 1; } void dfs2(int v) { int subtree = children[v] + 1; int from = maxPart[v] * 2; int to = subtree * 2; for (int i = from; i <= Math.min(to, N); i++) { for (int u : map[i]) centroid[u] = v; map[i].clear(); } if (centroid[v] < 0) map[subtree].add(v); for (int u : graph[v]) dfs2(u); } void solve(FastScanner in, PrintWriter out) throws Exception { N = in.nextInt(); int Q = in.nextInt(); graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); inv = new ArrayList[N]; for (int i = 0; i < N; i++) inv[i] = new ArrayList<>(); for (int i = 1; i <= N - 1; i++) { int p = in.nextInt() - 1; graph[p].add(i); inv[i].add(p); } children = new int[N]; centroid = new int[N]; Arrays.fill(centroid, -1); maxPart = new int[N]; map = new ArrayList[N + 1]; for (int i = 0; i < N + 1; i++) map[i] = new ArrayList<>(); dfs(0); dfs2(0); for (int q = 0; q < Q; q++) { int v = in.nextInt() - 1; out.println(centroid[v] + 1); } } } // Template public static void main(String[] args) throws Exception { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
5849504e93db737eceaa0e3ceb62f2ec
train_003.jsonl
1466699700
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; public class D { private static class Task { ArrayList<Integer>[] graph; ArrayDeque<Integer>[] deque; int N; int[] children;// children[v] := v の子要素の合計数 int[] centroid;// centroid[v] := v の centroid int[] maxPart;// maxPart[v] := v を消去した時、v の子の部分集合の中で最大のもの // v の子について色々求める DFS int dfs(int v) { for (int u : graph[v]) { int d = dfs(u); children[v] += d; maxPart[v] = Math.max(maxPart[v], d); } if (children[v] == 0 || maxPart[v] * 2 <= children[v] + 1) centroid[v] = v; return children[v] + 1; } // centroid を求める DFS void centroidDFS(int v) { int vSubtree = children[v] + 1;// v を根とする subtree のサイズ int from = maxPart[v] * 2;// v が centroid と成り得る subtree のサイズの下限 int to = vSubtree * 2;// v が centroid と成り得る subtree のサイズの上限 // v が centroid と成り得る subtree を処理 for (int i = from; i <= Math.min(to, N); i++) while (!deque[i].isEmpty()) { int u = deque[i].poll(); centroid[u] = v; } if (centroid[v] < 0) deque[vSubtree].add(v);// v の centroid が決まっていなければキューに入れておく for (int u : graph[v]) centroidDFS(u); } void solve(FastScanner in, PrintWriter out) throws Exception { N = in.nextInt(); int Q = in.nextInt(); graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); for (int i = 1; i <= N - 1; i++) { int p = in.nextInt() - 1; graph[p].add(i); } children = new int[N]; centroid = new int[N]; Arrays.fill(centroid, -1); maxPart = new int[N]; deque = new ArrayDeque[N + 1]; for (int i = 0; i < N + 1; i++) deque[i] = new ArrayDeque<>(); dfs(0); centroidDFS(0); for (int q = 0; q < Q; q++) { int v = in.nextInt() - 1; out.println(centroid[v] + 1); } } } // Template public static void main(String[] args) throws Exception { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
Java
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
3 seconds
["3\n2\n3\n6"]
Note The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
Java 8
standard input
[ "dp", "dfs and similar", "data structures", "trees" ]
7f15864d46f09ea6f117929565ccb867
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
1,900
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
standard output
PASSED
3cdde52f7886cbc70e6a84eb575482fa
train_003.jsonl
1442416500
You are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); long ans = n*m-n; for(int i = 1;i<n;i++){ if(s.charAt(i)!=s.charAt(i-1)){ ans+=n*m-n; } } long cur = 1; for(int i = 1;i<n;i++){ if(cur==1){ if(s.charAt(i)==s.charAt(i-1)){ continue; } else{ cur++; } } else{ if(s.charAt(i)==s.charAt(i-2)){ cur++; } else{ ans-=(cur*(cur-1))/2;; if(s.charAt(i)==s.charAt(i-1)){ cur=1; } else{ cur=2; } } } } ans-=(cur*(cur-1))/2; System.out.println(ans); } }
Java
["3 3\naaa", "3 3\naab", "1 2\na", "10 9\nabacadefgh"]
2 seconds
["6", "11", "1", "789"]
NoteFor the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.For the third sample, the only possible string T is b.
Java 8
standard input
[ "dp", "greedy" ]
69090abd03e01dae923194e50d528216
The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26). The second line contains string S.
2,700
Print the only line containing the answer.
standard output
PASSED
75733d3b7ae5c75c4ad5eadbf49a1a1c
train_003.jsonl
1442416500
You are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.
256 megabytes
import java.io.*; import java.util.Scanner; public class Main1 { static int hashi(int x, int y) { if (x == y) return -1; if (x > y) { int temp = x; x = y; y = temp; } return x * 1000 + y; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, m; int id[] = new int[100005]; long ans = 0; String s;//[100005]; n = sc.nextInt(); m = sc.nextInt(); String str = sc.next(); s = " " + str; ans = (m - 1) * n; for (int i = 2; i <= n; i++) if (s.charAt(i - 1) != s.charAt(i)) ans += (i - 1) * (m - 1); for (int i = 1; i <= n - 1; i++) if (s.charAt(i) != s.charAt(i + 1)) ans +=(n - i) * (m - 1); for (int i = 1; i <= n - 1; i++) id[i] = hashi(s.charAt(i), s.charAt(i + 1)); for (int i = 1; i <= n - 1; i++) if (id[i] != -1 && (i == 1 || id[i] != id[i - 1])) for (int j = i; j <= n - 1 && id[j] == id[i]; j++) ans -= j - i + 1; System.out.println(ans); } }
Java
["3 3\naaa", "3 3\naab", "1 2\na", "10 9\nabacadefgh"]
2 seconds
["6", "11", "1", "789"]
NoteFor the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.For the third sample, the only possible string T is b.
Java 8
standard input
[ "dp", "greedy" ]
69090abd03e01dae923194e50d528216
The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26). The second line contains string S.
2,700
Print the only line containing the answer.
standard output
PASSED
925d3210e1a9106a0085ec72459aa497
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; import java.lang.Math; public class A_razvedka { final String filename = "test"; class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String filename) { try { br = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (IOException e) { e.printStackTrace(); return null; } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } // fucking java void solve() { int n, i, m = 0, j, d; n = in.nextInt(); d = in.nextInt(); //n = int[] a = new int[n]; for (i = 0; i < n; i++) { a[i] = in.nextInt(); } for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if(Math.abs(a[i]-a[j]) <= d) m++; } } System.out.print(m*2); //out.print(m*2); } PrintWriter out; //MyScanner in; Scanner in; void run() { try { //in = new MyScanner(filename + ".in"); in = new Scanner(System.in); out = new PrintWriter(filename + ".out"); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new A_razvedka().run(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
8ab7c411308908b90682383a0913e11e
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
//package round32; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A { private Scanner in; private PrintWriter out; // private String INPUT = "5 10 10 20 50 60 65"; // private String INPUT = "5 1 55 30 29 31 55"; private String INPUT = ""; public void solve() { int n = ni(); int d = ni(); int[] h = new int[n]; for(int i = 0;i < n;i++){ h[i] = ni(); } Arrays.sort(h); int ct = 0; int p = 0; for(int i = 0;i < n;i++){ for(int j = i + 1;j < n;j++){ if(h[j] - h[i] <= d){ ct+=2; }else{ break; } } } out.println(ct); } public void run() throws Exception { in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new A().run(); } private int ni() { return Integer.parseInt(in.next()); } private void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
153d038bba04fc9c5b78d9395a349233
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
/* * 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. */ //package broblem2.soulution; import java.util.Arrays; import java.util.Scanner; /** * * @author Shubham */ public class cf32A { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int n,d; Scanner s=new Scanner(System.in); n=s.nextInt(); d=s.nextInt(); int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=s.nextInt(); Arrays.sort(ar); int count=0; //for(int i=0;i<n;i++) // System.out.print(ar[i]+" "); for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if((ar[j]-ar[i])<=d) count++; } } //System.out.println(""); System.out.println(count*2); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
45637a06ef2f587cf59921df97e3efcb
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class reconassance32A { public static void main(String[] args) { try { Scanner s=new Scanner(System.in); int n=s.nextInt(); long d=s.nextLong(); int count=0; long a[]=new long[n]; for(int i=0;i<n;i++) { a[i]=s.nextLong(); } Arrays.sort(a); for(int i=n-1;i>=0;i--) { for(int j=i-1;j>=0;j--) { if((a[i]-a[j])<=d) { count++; } } } //System.out.println(count); System.out.println(count*2); } catch(Exception e) { System.out.println(e.getMessage()); } } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
4e1a6216df38415505a34c0ec05acf5d
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Arrays; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /*BY:-PRASANG*/ /** * * @author Seedha */ public class Reconnaissance { static int n,m,count; static int []a; public static void main(String[]hh) { Scanner sc=new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); a=new int[n]; for(int i=0;i<a.length;i++) a[i]=sc.nextInt(); Arrays.sort(a); for(int i=0;i<a.length;i++) { int j=i+1; while(j<n) { if(a[j]-a[i]<=m) count++; j++; } } System.out.println(2*count); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
4a7ad159789ee8e2a0db171c0d0e5e46
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Scanner; public class a32 { public static void main(String[] args) { try { Scanner s=new Scanner(System.in); int n,d; n=s.nextInt(); d=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int count=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) {} else if((a[i]-a[j]<=d)&&(a[i]-a[j]>=0)) count++; else if((a[j]-a[i]<=d)&&(a[j]-a[i]>=0)) count++; } } System.out.println(count); } catch(Exception e) { System.out.println(e.getMessage()); } } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
6b963c3b090136e8dcf70f85a6a2a34e
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } private static FastScanner s = new FastScanner(); private static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); static int count=0; public static void main(String[] args) throws IOException { int n = s.nextInt(); int d= s.nextInt(); int a[]= new int[n];int count =0; for(int i=0;i<n;i++) a[i]=s.nextInt(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i!=j) { if(Math.max(a[i]-a[j],a[j]-a[i])<=d) count++; } } } ww.println(count); s.close(); ww.close(); } public static int gcd(int a, int b){ return b == 0 ? a : gcd(b,a%b); } } /*zabardast swappimng of sorting /* for(int h=0;h<n;h++) { int temp,temp1,temp2; for(int y=h+1;y<n;y++) { if(a[y][2]>=a[h][2]) { temp=a[y][2]; //////sorting a[y][2]=a[h][2]; a[h][2]=temp; temp1=a[y][0]; a[y][0]=a[h][0]; a[h][0]=temp1; temp2=a[y][1]; a[y][1]=a[h][1]; a[h][1]=temp2; } } } */
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
aa9cd2bc26992b16d666e3196c85d756
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Scanner; public class Exploration { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] a = new int[n]; int max = 0; for(int i = 0; i<n; i++){ a[i] = in.nextInt(); } for(int i = 0; i<n; i++){ for(int j=0; j<n; j++){ if(i!=j && Math.abs(a[i]-a[j]) <= d){ ++max; } } } System.out.println(max); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
cce48e5eb1c467aa4e47d4e46415d430
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; public class Recon { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String[] list1 = r.readLine().split(" "); long n = Long.parseLong(list1[0]); long d = Long.parseLong(list1[1]); String[] list2 = r.readLine().split(" "); long[] list = new long[list2.length]; for(int i = 0; i<list.length; i++) { list[i] = Long.parseLong(list2[i]); } int count = 0; for(int i = 0; i<list.length; i++) { for(int j = 0; j<list.length; j++) { if(i!=j && Math.abs(list[i]-list[j])<=d) { count++; } } } System.out.println(count); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
ad73251af2a00a79eb7211d96e766b52
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Scanner; public class Reconnaissance { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int r = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { if (i != j && Math.abs(a[i] - a[j]) <= d) r++; } } System.out.println(r); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
dd58f616068d7f953785d063d21a6ffb
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); public static int nextInt() throws Exception { int x = 0, c = bf.read(); while(c < 48 || c > 57) c = bf.read(); while(c >= 48 && c <= 57) { x = (x << 1) + (x << 3) + c - 48; c = bf.read();} return x; } public static void main(String args[]) throws Exception { //Scanner cin = new Scanner(System.in); int t = nextInt(); int a[] = new int[t]; int n = nextInt(); for(int i = 0; i < t; i++) a[i] = nextInt(); int c = 0; for(int i = 0; i < t; i++) for(int j = 0; j < t; j++) { if(i != j && Math.abs(a[i] - a[j]) <= n) c++; } System.out.println(c); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
96368fbc11c2561c768c9f6d3168a94b
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class ProblemA_32 { 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()){ tok=new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } public static void main(String[] args){ new ProblemA_32().run(); } public void run(){ try{ long t1=System.currentTimeMillis(); init(); solve(); out.close(); long t2=System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n=readInt(); int d=readInt(); int[] a=new int[n]; for (int i=0; i<n; i++){ a[i]=readInt(); } Arrays.sort(a); long[] c=new long[n]; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (d<a[j]-a[i]){ break; } c[i]++; } for (int j=i-1; j>=0; j--){ if (d<a[i]-a[j]){ break; } c[i]++; } } long s=0; for (int i=0; i<n; i++){ s+=c[i]; } out.print(s); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
a3b3386a6b55571da5497363d2fbd41f
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution32A { 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()){ 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()); } public static void main(String[] args){ new Solution32A().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = readInt(); long d = readLong(); long[] a = new long[n]; for(int i = 0; i < n; i++){ a[i] = readLong(); } int count = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i != j && abs(a[i] - a[j]) <= d) count++; } } out.println(count); } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
4843e7080b475b7481b1d6b4c05abec2
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class A { static InputStreamReader in = new InputStreamReader(System.in); static BufferedReader bf = new BufferedReader(in); static StreamTokenizer st = new StreamTokenizer(bf); public static void main(String[] args) throws IOException{ int n = nextInt(); int d = nextInt(); int []a = new int [n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } int ans = 0; for (int i = 0; i < a.length; i++) { for (int j = i+1; j < a.length; j++) { if (Math.abs(a[i]-a[j]) <= d) ans++; } } System.out.println(ans*2); } private static int nextInt() throws IOException{ st.nextToken(); return (int) st.nval; } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
315c96339ca2407ae9bcf03b5d4eefb4
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { void solve() throws IOException { int n = nextInt(); int d = nextInt(); int[] a = new int[n]; int pares = 0; for (int i = 0; i < n; i++) { a[i] = nextInt(); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (Math.abs((a[i] - a[j])) <= d) ++pares; } } out.print((pares*2)); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Main(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
f0739341e972f20b2b339d56ecde7697
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { BufferedReader in; PrintWriter out; StringTokenizer st; void solve() throws IOException { int n = ni(); int d = ni(); int[] v = new int[n]; for (int i = 0; i < v.length; i++) { v[i] = ni(); } int ret = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (i != j) { if (abs(v[i] - v[j]) <= d) ++ret; } out.println(ret); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Solution(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
6c82accde376e7b74fdcc7b8c59a7ea3
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Scanner; public class p32a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] all = new int[n]; for (int i = 0; i < all.length; i++) { all[i] = in.nextInt(); } long ans = 0; for (int i = 0; i < all.length; i++) { for (int j = 0; j < all.length; j++) { if(i == j) continue; int diff = Math.abs(all[i]-all[j]); if(diff<=d) { ans++; } } } System.out.println(ans); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
f823e4f46abfdee99b8e264f4115851d
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int d = in.nextInt(); int ans = 0; int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { if (i == j) continue; if ((int) Math.abs(a[i] - a[j]) <= d) ans++; } } out.print(ans); out.close(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
e0361b946066de52b2fac9c3fc958618
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static int[] c; public static int solve(int d) { int res = 0; for (int i = 0; i < c.length - 1; i++) { for (int j = i + 1; j < c.length; j++) { if(c[j] - c[i] <= d) { res += 2; } else { break; } } } return res; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //BufferedReader input = new BufferedReader(new FileReader("input.txt")); //BufferedWriter output = new BufferedWriter(new FileWriter("output.txt")); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StreamTokenizer in = new StreamTokenizer(input); in.nextToken(); int n = (int)in.nval; in.nextToken(); int d = (int)in.nval; c = new int[n]; for (int i = 0; i < c.length; i++) { in.nextToken(); c[i] = (int)in.nval; } Arrays.sort(c); int res = solve(d); output.write(String.valueOf(res)); input.close(); output.close(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
4cde119665aa6c750a1e39c1894b002d
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} new Main().run(); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int N; int D; int[] a; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); N = nextInt(); D = nextInt(); a = new int [N]; for (int i = 0; i < N; i++) a[i] = nextInt(); int ans = 0; for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (abs(a[i] - a[j]) <= D) ans += 2; out.println(ans); out.close(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return true; } st = new StringTokenizer(s); } return false; } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
9906f81bdf6368253768a21da572d6ab
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; public class Reconnaissance { Scanner in; PrintWriter out; Reconnaissance() { in = new Scanner(System.in); out = new PrintWriter(System.out); } Reconnaissance(String o) throws FileNotFoundException { in = new Scanner(System.in); out = new PrintWriter(new File(o)); } Reconnaissance(String i, String o) throws FileNotFoundException { in = new Scanner(new File(i)); out = new PrintWriter(new File(o)); } public void finalize() { out.flush(); in.close(); out.close(); } void solve() { int n = in.nextInt(), d = in.nextInt(); int[] ar = new int[n]; int c = 0; for(int i = 0; i < n; ++i) ar[i] = in.nextInt(); Arrays.sort(ar); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) if(i != j) if(Math.abs(ar[i] - ar[j]) <= d) ++c; out.println(c); } public static void main(String[] args) throws FileNotFoundException { Reconnaissance t = new Reconnaissance(); t.solve(); t.finalize(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
103c01d9b3f8c56d0e3d40904746e270
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class BetaRound32_A implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws IOException { 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()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } @Override public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } public static void main(String[] args) { new Thread(new BetaRound32_A()).start(); } void solve() throws IOException { int n = readInt(); int d = readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (abs(a[i] - a[j]) <= d) { ans += 2; } } } out.print(ans); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
ed3559ccf5827b32364be3b6677ea424
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.TreeSet; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ inB = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(inB); out = new PrintWriter(System.out); } public static void main(String[] args)throws Exception{ int n = nextInt(), d = nextInt(); int[] mas = new int[n]; for(int i = 0; i<n; i++)mas[i] = nextInt(); int count = 0; for(int i = 0; i<n; i++) { for(int j = 0; j<n; j++) if(j!= i) { if(Math.abs(mas[i] - mas[j]) <= d)count++; } } System.out.println(count); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
6970e6d58586510c0ec2a1b8c2eb48f7
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { new A().process(); } public void process() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } int res = 0; for (int i = 0; i< n; i++) { for (int j = i+1; j < n; j++) { if (Math.abs(arr[i] - arr[j]) <= d) { res += 2; } } } System.out.println(res); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
070b3d67dc7b81715b4900dbe9f3efee
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int N = Integer.parseInt(st.nextToken()); int differ = Integer.parseInt(st.nextToken()); int [] data = new int[N]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < data.length; i++) { data[i] = Integer.parseInt(st.nextToken()); } int ret = 0; for (int i = 0; i < data.length; i++) { for (int j = i+1; j < data.length; j++) { if(Math.abs(data[i] - data[j]) <=differ)++ret; }} System.out.println(ret*2); // // UnsortedStringList ll = new UnsortedStringList(); // int tt = ll.length(); // // ll.insert("Mostafa"); // ll.insert("Mahmoud"); // ll.insert("El-Abady"); // System.out.println(ll); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
306446f1d87cd96efcd6449b1575722e
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package javatest1; import java.io.PrintWriter; import java.util.Scanner; import java.util.ArrayList; /** * * @author alper */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); PrintWriter writer = new PrintWriter(System.out); ArrayList<Integer> array = new ArrayList<Integer>(); int n, d; n = scanner.nextInt(); d = scanner.nextInt(); for (int i = 0; i < n; ++i) //while (scanner.hasNext()) array.add(scanner.nextInt()); int count = 0; for (Integer number1 : array) for (Integer number2 : array) { int d1 = number1 - number2; if (d1 < 0) d1 = -d1; int d2 = number2 - number1; if (d2 < 0) d2 = -d2; if (d1 <= d || d2 <= d) count++; } writer.print(count - n); writer.close(); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
7e8a7eb7288e19bc140c60e2caffee74
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
//package reconnaissance; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author haytham */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("x.in")); while(br.ready()){ String x=br.readLine().trim(); if(x.equals("")) continue; String y[]=x.split(" +"); int m=Integer.parseInt(y[1]); //System.out.println(m); x=br.readLine().trim(); String r[]=x.split(" +"); int count=0; for (int i = 0; i < r.length; i++) { int h=Integer.parseInt(r[i]); for (int j = 0; j < r.length; j++) { if(i==j) continue; int g=Integer.parseInt(r[j]); //System.out.println(h+" "+g); if((h-g<=m&&h-g>0)||(g-h<=m&&g-h>0)||(g==h)) count++; } } System.out.println(count); } } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
d8cc89060b9ca18eac2ac747ca3557fa
train_003.jsonl
1286002800
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.
256 megabytes
import static java.lang.Integer.*; import static java.lang.Math.*; import java.io.IOException; import java.util.Scanner; @SuppressWarnings("unused") public class round32A { public static void main(String[] args)throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int d = sc.nextInt(); int [] in = new int [n]; for(int i = 0 ; i < n ; ++i) in[i] = sc.nextInt(); int ans = 0; for(int i = 0 ; i < n ; ++i){ for(int j = i + 1 ; j < n ; ++j){ if(abs(in[i] - in[j]) <= d){ ans++; } } } System.out.println(ans * 2); } }
Java
["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"]
2 seconds
["6", "6"]
null
Java 6
standard input
[ "brute force" ]
d7381f73ee29c9b89671f21cafee12e7
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
800
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
standard output
PASSED
6a7436404eb0dc797dd8fcff3be82566
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.StringBuilder; import java.util.*; public class CF342B { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); String a = reader.readLine(); String b = reader.readLine(); int lena = a.length(); int lenb = b.length(); int ans = 0; for (int i = 0; i < lena; i++) { int j = 0; while (j < lenb && i+j < lena && a.charAt(i+j) == b.charAt(j)) j++; if (j == lenb) { ans++; i = i+j-1; } } writer.write(ans + "\n"); writer.flush(); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
aa8d0b00626760022030585e93ac3bd0
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static String [] r() throws IOException { return s.readLine().split(" "); } static int Int (String D) { return Integer.parseInt(D); } static long Lon (String D) { return Long.parseLong(D); } static double Dou (String D) { return Double.parseDouble(D); } public static void main (String args[]) throws IOException { String S[] = r(); String st1=S[0]; S=r(); String st2=S[0]; long res=0; int len1=st1.length(); int len2=st2.length(); int count=0; int i=0; while (i<=len1-len2) { if (st1.substring(i, i+len2).equals(st2)) { count++; i=i+len2-1; } i++; } pr(count+""); out.close();} private static void pr(String S) throws IOException { out.write(S); out.flush(); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
dda1b0a55c4fa62a8953ed50addadc8d
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
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 Ex625B { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); new Ex(in,out); out.close(); } static class Ex{ InputReader in; PrintWriter out; int ans=0; public Ex(InputReader in, PrintWriter out){ this.in=in; this.out=out; decide(); } public void decide(){ String s1; String s2; s1=in.next(); s2=in.next(); int s1len=s1.length(); int s2len=s2.length(); for(int i=0;i<s1len-s2len+1;++i){ if(s1.substring(i,i+s2len).equals(s2)){ ans+=1; i+=(s2len-1); } } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
7ca5c90c1da216da5ee1c15dcb90ae08
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; /** * * @author adhithyan-3592 * **/ public class WarOfCorp { public static void main(String[] args){ Scanner input = new Scanner(System.in); String gogol = input.next(); String pineapple = input.next(); if(!gogol.contains(pineapple)){ System.out.println("0"); }else{ int prevLength = gogol.length(); int pineappleLength = pineapple.length(); gogol = gogol.replaceAll(pineapple, ""); int ans = (prevLength - gogol.length()) / pineappleLength; System.out.println(ans); } input.close(); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
da6a13daaaea2c4bb285f8be1949db24
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class B { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String name = br.readLine(); String coso = br.readLine(); int index; int r = 0; int lastIndex = 0; while ((index = name.indexOf(coso, lastIndex)) > -1) { lastIndex = index + coso.length(); r++; } System.out.println(r); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
703cb0191c8442c468033039a70dfdbd
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class R342Div2B { public static void main(String[] args) { FastScanner in=new FastScanner(); String s=in.nextToken(); String p=in.nextToken(); int m=p.length(); ArrayList<Integer> a=new ArrayList<Integer>(); int x=-1; while(true){ x=s.indexOf(p,x+1); if(x==-1) break; a.add(x); x+=m-1; } System.out.println(a.size()); } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));} String nextToken(){ while(st==null||!st.hasMoreElements()) try{st=new StringTokenizer(br.readLine());}catch(Exception e){} return st.nextToken(); } int nextInt(){return Integer.parseInt(nextToken());} long nextLong(){return Long.parseLong(nextToken());} double nextDouble(){return Double.parseDouble(nextToken());} } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
62f62e23a28947cb666f30bbff222fc7
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { char[] ai = in.next().toCharArray(); char[] phone = in.next().toCharArray(); int start = 0; int count = 0; while (start < ai.length) { if (checkSubstring(start, ai, phone)) { start += phone.length; count++; } else { start += 1; } } out.println(count); } private boolean checkSubstring(int start, char[] a, char[] str) { for (int i = 0; i < str.length; i++) { if (i + start >= a.length) return false; if (a[i + start] != str[i]) { return false; } } return true; } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
00c70ff871ebd2e2030784b1ade02ae0
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class MainB { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); long start = System.currentTimeMillis(); long fin = System.currentTimeMillis(); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { char[] a = sc.next().toCharArray(); char[] b = sc.next().toCharArray(); int cnt = 0; for (int i = 0; i < a.length; i++) { boolean match = true; int in = i; for (int j = 0; j < b.length; j++) { if (in + j == a.length || b[j] != a[in + j]) { match = false; break; } } if (match) { a[i + b.length - 1] = '#'; cnt++; } } System.out.println(cnt); } public static void main(String[] args) { new MainB().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(long[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } boolean inner(int h, int w, int limH, int limW) { return 0 <= h && h < limH && 0 <= w && w < limW; } void swap(char[] x, int a, int b) { char tmp = x[a]; x[a] = x[b]; x[b] = tmp; } // find minimum i (k <= a[i]) int lower_bound(int a[], int k) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (k <= a[mid]) r = mid; else l = mid; } // r = l + 1 return r; } // find minimum i (k < a[i]) int upper_bound(int a[], int k) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (k < a[mid]) r = mid; else l = mid; } // r = l + 1 return r; } int gcd(int a, int b) { return a % b == 0 ? b : gcd(b, a % b); } int lcm(int a, int b) { return a * b / gcd(a, b); } boolean palindrome(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; } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } int[] nextIntArray(int n) { int[] in = new int[n]; for (int i = 0; i < n; i++) { in[i] = nextInt(); } return in; } int[][] nextInt2dArray(int n, int m) { int[][] in = new int[n][m]; for (int i = 0; i < n; i++) { in[i] = nextIntArray(m); } return in; } double[] nextDoubleArray(int n) { double[] in = new double[n]; for (int i = 0; i < n; i++) { in[i] = nextDouble(); } return in; } long[] nextLongArray(int n) { long[] in = new long[n]; for (int i = 0; i < n; i++) { in[i] = nextLong(); } return in; } char[][] nextCharField(int n, int m) { char[][] in = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { in[i][j] = s.charAt(j); } } return in; } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
f7ebb5adc8402ef0180a5488715e8e17
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class B_Div2_342 { public static void main(String[]arg) throws IOException { new B_Div2_342().solve(); } char[]T,P; int[]b; int n,m; public void solve()throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); T = in.readLine().toCharArray(); P = in.readLine().toCharArray(); n = T.length; m = P.length; kmpPreprocess(); int ans = 0; int i = 0, j = 0; while(i < n) { while(j >= 0 && T[i] != P[j]) j = b[j]; i++; j++; if(j == m) { //System.out.println(i); T[i-j] = '#'; ans++; //System.out.println("P is foun index: "+(i-j)); j = 0; } } //System.out.println(String.valueOf(T)); System.out.println(ans); } private void kmpPreprocess() { b = new int[m+10]; int i = 0, j = -1; b[0] = -1; while(i < m) { while(j >= 0 && P[i] != P[j]) j = b[j]; i++; j++; b[i] = j; } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
f6db13e9e5f6d6f739d94ba4fb5f51f8
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class B { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static float nextFloat() throws IOException { return Float.parseFloat(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { long res = 0; String name = next(); StringBuilder str = new StringBuilder(name); String phone = next(); for (int i = 0; i < str.length() - phone.length() + 1; i++) { String sub = str.substring(i, i + phone.length()); if (sub.equals(phone)) { str.setCharAt(i + phone.length() - 1, '#'); res++; } } System.out.println(res); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
4290c50d475b4a430b6caeaadf9a1817
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class test { public static void main(String[] args)throws IOException { // Scanner ob=new Scanner(System.in); BufferedReader ob=new BufferedReader(new InputStreamReader(System.in)); String s=ob.readLine(); String s1=ob.readLine(); int x=s.length(); int y=s1.length(); int ans=0; for(int i=0;i<x;i++) { if((i+y)>x) break; if(s.substring(i,i+y).equals(s1)) { ans+=1; i+=y-1; } } System.out.println(ans); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
058b58a098dde2349a287e4eb9e875d4
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; /** * http://codeforces.com/contest/625/problem/B */ public class B { public static void main(String[] args) { new B().doJob(); } private void doJob() { try (Scanner scanner = new Scanner(System.in)) { String string = scanner.next(); String subString = scanner.next(); int cnt = 0; int charIdx = 0; while ((charIdx = string.indexOf(subString, charIdx)) >= 0) { charIdx += subString.length(); cnt++; } System.out.println(cnt); } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
b84a35803c0c51bfdcb613d59940ebbf
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { String value = in.next(); String test = in.next(); int size = value.length(); int testSize = test.length(); int result = 0; if (size < testSize) { out.print(0); return; } for (int i = 0; (i + testSize - 1) < size; i++) { if (OK(value, i, test)) { result += 1; i = i + testSize - 1; } } out.print(result); } public boolean OK(String arr, int index, String test) { int sz = test.length(); for (int i = 0; i < sz; i++) { if (arr.charAt(i + index) != test.charAt(i)) return false; } return true; } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
5ec2ba516e936ae09091c9f7f44b2337
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.awt.Point; import java.awt.geom.Line2D; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.GuardedObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.InputStream; import java.math.BigInteger; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in; PrintWriter out; in=new FastScanner(System.in); out=new PrintWriter(System.out); //in=new FastScanner(new FileInputStream(new File("C://Users//KANDARP//Desktop//coding_contest_creation (1).txt"))); TaskC solver = new TaskC(); long var=System.currentTimeMillis(); solver.solve(1, in, out); /*if(System.getProperty("ONLINE_JUDGE")==null){ out.println("["+(double)(System.currentTimeMillis()-var)/1000+"]"); }*/ out.close(); } } class Pair { long x,y,index; long r1,r2; HashMap<Double,Long> map=new HashMap<>(); Pair(long x,long y,int index){ this.x=x; this.y=y; this.index=index; } public String toString(){ return this.x+" "+this.y+" "; } } class tupple{ long x,y,z; ArrayList<String> list=new ArrayList<>(); tupple(long x,long y,long z){ this.x=x; this.y=y; this.z=z; } tupple(tupple cl){ this.x=cl.x; this.y=cl.y; this.z=cl.z; this.list=cl.list; } } class Edge implements Comparable<Edge>{ int u; int v; int time; long cost; long wcost; public Edge(int u,int v,long cost,long wcost){ this.u=u; this.v=v; this.cost=cost; this.wcost=wcost; time=Integer.MAX_VALUE; } public int other(int x){ if(u==x)return v; return u; } @Override public int compareTo(Edge o) { // TODO Auto-generated method stub return Long.compare(cost, o.cost); } } class Ss{ Integer a[]=new Integer[3]; Ss(Integer a[]){ this.a=a; } public int hashCode(){ return a[0].hashCode()+a[1].hashCode()+a[2].hashCode(); } public boolean equals(Object o){ Ss x=(Ss)o; for(int i=0;i<3;i++){ if(x.a[i]!=this.a[i]){ return false; } } return true; } } class queary{ int type; int l; int r; int index; queary(int type,int l,int r){ this.type=type; this.l=l; this.r=r; } } class boat implements Comparable<boat>{ int capacity; int index; boat(int capacity,int index) { this.capacity=capacity; this.index=index; } @Override public int compareTo(boat o) { // TODO Auto-generated method stub return this.capacity-o.capacity; } } class angle{ double x,y,angle; int index; angle(int x,int y,double angle){ this.x=x; this.y=y; this.angle=angle; } } class TaskC { static long mod=1000000007; // SegTree tree; // int min[]; /* static int prime_len=1000010; static int prime[]=new int[prime_len]; static long n_prime[]=new long[prime_len]; static ArrayList<Integer> primes=new ArrayList<>(); static{ for(int i=2;i<=Math.sqrt(prime.length);i++){ for(int j=i*i;j<prime.length;j+=i){ prime[j]=i; } } for(int i=2;i<prime.length;i++){ n_prime[i]=n_prime[i-1]; if(prime[i]==0){ n_prime[i]++; } } // System.out.println("end"); // prime[0]=true; // prime[1]=1; } /* * long pp[]=new long[10000001]; pp[0]=0; pp[1]=1; for(int i=2;i<pp.length;i++){ if(prime[i]!=0){ int gcd=(int)greatestCommonDivisor(i/prime[i], prime[i]); pp[i]=(pp[i/prime[i]]*pp[prime[i]]*gcd)/pp[(int)gcd]; } else pp[i]=i-1; } } * */ class Rmq { int[] logTable; int[][] rmq; int[] a; public Rmq(int[] a) { this.a = a; int n = a.length; logTable = new int[n + 1]; for (int i = 2; i <= n; i++) logTable[i] = logTable[i >> 1] + 1; rmq = new int[logTable[n] + 1][n]; for (int i = 0; i < n; ++i) rmq[0][i] = i; for (int k = 1; (1 << k) < n; ++k) { for (int i = 0; i + (1 << k) <= n; i++) { int x = rmq[k - 1][i]; int y = rmq[k - 1][i + (1 << k - 1)]; rmq[k][i] = a[x] <= a[y] ? x : y; } } } public int minPos(int i, int j) { int k = logTable[j - i]; int x = rmq[k][i]; int y = rmq[k][j - (1 << k) + 1]; return a[x] <= a[y] ? a[x] : a[y]; } } public void solve(int testNumber, FastScanner in, PrintWriter out) throws IOException { String s=in.readString(); String s1=in.readString(); int i=0; long ans=0; while(s.indexOf(s1,i)>=0){ ans++; i=s.indexOf(s1,i)+s1.length(); } out.println(ans); } static long greatestCommonDivisor (long m, long n){ long x; long y; while(m%n != 0){ x = n; y = m%n; m = x; n = y; } return n; } } /* * long res[]=new long[m]; int cl=1; int cr=0; for(int i=0;i<m;i++){ int l=(int)q[i].x; int r=(int)q[i].y; while(cl>l){ cl--; ans+=add(cl); } while(cl<l){ ans-=remove(cl); cl++; } while(cr>r){ ans-=remove(cr); cr--; } while(cr<r){ cr++; ans+=add(cr); } res[(int)q[i].index]=ans; } for(int i=0;i<m;i++) out.println(res[i]); */ class SegmentTree2D { public long max(int[][] t, int x1, int y1, int x2, int y2) { int n = t.length >> 1; x1 += n; x2 += n; int m = t[0].length >> 1; y1 += m; y2 += m; long res = 0; for (int lx = x1, rx = x2; lx <= rx; lx = (lx + 1) >> 1, rx = (rx - 1) >> 1) for (int ly = y1, ry = y2; ly <= ry; ly = (ly + 1) >> 1, ry = (ry - 1) >> 1) { if ((lx & 1) != 0 && (ly & 1) != 0) res = (res+ t[lx][ly]); if ((lx & 1) != 0 && (ry & 1) == 0) res = (res+ t[lx][ry]); if ((rx & 1) == 0 && (ly & 1) != 0) res =(res+t[rx][ly]); if ((rx & 1) == 0 && (ry & 1) == 0) res = (res+ t[rx][ry]); } return res; } public void add(int[][] t, int x, int y, int value) { x += t.length >> 1; y += t[0].length >> 1; t[x][y] += value; for (int tx = x; tx > 0; tx >>= 1) for (int ty = y; ty > 0; ty >>= 1) { if (tx > 1) t[tx >> 1][ty] = (t[tx][ty]+t[tx ^ 1][ty]); if (ty > 1) t[tx][ty >> 1] = (t[tx][ty]+ t[tx][ty ^ 1]); } // for (int ty = y; ty > 1; ty >>= 1) // t[x][ty >> 1] = Math.max(t[x][ty], t[x][ty ^ 1]); // for (int tx = x; tx > 1; tx >>= 1) // for (int ty = y; ty > 0; ty >>= 1) // t[tx >> 1][ty] = Math.max(t[tx][ty], t[tx ^ 1][ty]); // for (int lx=x; lx> 0; lx >>= 1) { // if (lx > 1) // t[lx >> 1][y] = Math.max(t[lx][y], t[lx ^ 1][y]); // for (int ly = y; ly > 1; ly >>= 1) // t[lx][ly >> 1] = Math.max(t[lx][ly], t[lx][ly ^ 1]); // } } } class SegmentTree { // Modify the following 5 methods to implement your custom operations on the tree. // This example implements Add/Max operations. Operations like Add/Sum, Set/Max can also be implemented. long modifyOperation(long x, long y) { return y; } // query (or combine) operation long queryOperation(long leftValue, long rightValue) { return (leftValue| rightValue); } long deltaEffectOnSegment(long delta, long segmentLength) { // Here you must write a fast equivalent of following slow code: // int result = delta; // for (int i = 1; i < segmentLength; i++) result = queryOperation(result, delta); // return result; return delta; } int getNeutralDelta() { return 0; } int getInitValue() { return 0; } // generic code int n; long[] value; long[] delta; // delta[i] affects value[i], delta[2*i+1] and delta[2*i+2] long joinValueWithDelta(long value, long delta) { if (delta == getNeutralDelta()) return value; return modifyOperation(value, delta); } long joinDeltas(long delta1, long delta2) { if (delta1 == getNeutralDelta()) return delta2; if (delta2 == getNeutralDelta()) return delta1; return modifyOperation(delta1, delta2); } void pushDelta(int root, int left, int right) { value[root] = joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1)); delta[2 * root + 1] = joinDeltas(delta[2 * root + 1], delta[root]); delta[2 * root + 2] = joinDeltas(delta[2 * root + 2], delta[root]); delta[root] = getNeutralDelta(); } public SegmentTree(int n) { this.n = n; value = new long[4 * n]; delta = new long[4 * n]; init(0, 0, n - 1); } void init(int root, int left, int right) { if (left == right) { value[root] = getInitValue(); delta[root] = getNeutralDelta(); } else { int mid = (left + right) >> 1; init(2 * root + 1, left, mid); init(2 * root + 2, mid + 1, right); value[root] = queryOperation(value[2 * root + 1], value[2 * root + 2]); delta[root] = getNeutralDelta(); } } public long query(int from, int to) { return query(from, to, 0, 0, n - 1); } long query(int from, int to, int root, int left, int right) { if (from == left && to == right) return joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1)); pushDelta(root, left, right); int mid = (left + right) >> 1; if (from <= mid && to > mid) return queryOperation( query(from, Math.min(to, mid), root * 2 + 1, left, mid), query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right)); else if (from <= mid) return query(from, Math.min(to, mid), root * 2 + 1, left, mid); else if (to > mid) return query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right); else throw new RuntimeException("Incorrect query from " + from + " to " + to); } public void modify(int from, int to, long delta) { modify(from, to, delta, 0, 0, n - 1); } void modify(int from, int to, long delta, int root, int left, int right) { if (from == left && to == right) { this.delta[root] = joinDeltas(this.delta[root], delta); return; } pushDelta(root, left, right); int mid = (left + right) >> 1; if (from <= mid) modify(from, Math.min(to, mid), delta, 2 * root + 1, left, mid); if (to > mid) modify(Math.max(from, mid + 1), to, delta, 2 * root + 2, mid + 1, right); value[root] = queryOperation( joinValueWithDelta(value[2 * root + 1], deltaEffectOnSegment(this.delta[2 * root + 1], mid - left + 1)), joinValueWithDelta(value[2 * root + 2], deltaEffectOnSegment(this.delta[2 * root + 2], right - mid))); } } class LcaSparseTable { int len; int[][] up; int[][] max; int[] tin; int[] tout; int time; int []lvel; void dfs(List<Integer>[] tree, int u, int p) { tin[u] = time++; lvel[u]=lvel[p]+1; up[0][u] = p; if(u!=p) //max[0][u]=weight(u,p); for (int i = 1; i < len; i++) { up[i][u] = up[i - 1][up[i - 1][u]]; max[i][u]=Math.max(max[i-1][u],max[i-1][up[i-1][u]]); } for (int v : tree[u]) if (v != p) dfs(tree, v, u); tout[u] = time++; } public LcaSparseTable(List<Integer>[] tree, int root) { int n = tree.length; len = 1; while ((1 << len) <= n) ++len; up = new int[len][n]; max=new int[len][n]; tin = new int[n]; tout = new int[n]; lvel=new int[n]; lvel[root]=0; dfs(tree, root, root); } boolean isParent(int parent, int child) { return tin[parent] <= tin[child] && tout[child] <= tout[parent]; } public int lca(int a, int b) { if (isParent(a, b)) return a; if (isParent(b, a)) return b; for (int i = len - 1; i >= 0; i--) if (!isParent(up[i][a], b)) a = up[i][a]; return up[0][a]; } public long max(int a,int b){ int lca=lca(a,b); // System.out.println("LCA "+lca); long ans=0; int h=lvel[a]-lvel[lca]; // System.out.println("Height "+h); int index=0; while(h!=0){ if(h%2==1){ ans=Math.max(ans,max[index][a]); a=up[index][a]; } h/=2; index++; } h=lvel[b]-lvel[lca]; // System.out.println("Height "+h); index=0; while(h!=0){ if(h%2==1){ ans=Math.max(ans,max[index][b]); b=up[index][b]; } h/=2; index++; } return ans; } static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u,int parent,List<Integer> collection) { used[u] = true; Integer uu=new Integer(u); collection.add(uu); for (int v : graph[u]){ if (!used[v]){ dfs(graph, used, res, v,u,collection); } else if(collection.contains(v)){ System.out.println("Impossible"); System.exit(0); } } collection.remove(uu); res.add(u); } public static List<Integer> topologicalSort(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> res = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, res, i,-1,new ArrayList<Integer>()); Collections.reverse(res); return res; } static class pairs{ String company,color; String type; boolean visit=false; pairs(String company,String color,String type){ this.company=company; this.color=color; this.type=type; } } static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs1(graph, used, res, v); res.add(u); } public static List<Integer> topologicalSort1(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> res = new ArrayList<>(); for (int i = n-1; i >0; i--) if (!used[i]) dfs1(graph, used, res, i); Collections.reverse(res); return res; } public static long[][] mulmatrix(long m1[][],long m2[][],long mod){ long ans[][]=new long[m1.length][m2[0].length]; for(int i=0;i<m1.length;i++){ for(int j=0;j<m2[0].length;j++){ for(int k=0;k<m1.length;k++){ ans[i][j]+=(m1[i][k]*m2[k][j]); ans[i][j]%=mod; } } } return ans; } public static long[][] matrixexpo(long m[][],String n,long mod){ if(n.equals("1")){ return m.clone(); } if(n.equals("10")){ return mulmatrix(m, m , mod); } else{ long temp [][]=matrixexpo(m,n.substring(0,n.length()-1),mod); temp=mulmatrix(temp, temp, mod); if(n.charAt(n.length()-1)=='0')return temp; else return mulmatrix(temp, m,mod); } } public static boolean isCompatible(long x[],long y[]){ for(int i=0;i<x.length-1;i++){ if(x[i]==y[i] && x[i+1]==y[i+1] && x[i]==x[i+1] && y[i]==y[i+1]){ return false; } } return true; } int phi(int n) { int res = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } res -= res / i; } } if (n != 1) { res -= res / n; } return res; } long pow(long x,long y,long mod){ if(y<=0){ return 1; } if(y==1){ return x%mod; } long temp=pow(x,y/2,mod); if(y%2==0){ return (temp*temp)%mod; } else{ return (((temp*temp)%mod)*x)%mod; } } /* long DP(int id,int mask){ //System.out.println("hi"+dp[id][mask]+" "+id+" "+Integer.toBinaryString(mask)); if(id==0 && mask==0){ dp[0][mask]=1; return 1; } else if(id==0){ dp[0][mask]=0; return 0; } if(dp[id][mask]!=-1){ return dp[id][mask]; } long ans=0; for(int i=0;i<n;i++){ if((mask & (1<<i))!=0 && c[i][id]>=1){ ans+=DP(id-1,mask ^ (1 << i)); ans%=mod; } } ans+=DP(id-1,mask); ans%=mod; dp[id][mask]=ans; return ans; }*/ long no_of_primes(long m,long n,long k){ long count=0,i,j; int primes []=new int[(int)(n-m+2)]; if(m==1) primes[0] = 1; for(i=2; i<=Math.sqrt(n); i++) { j = (m/i); j *= i; if(j<m) j+=i; for(; j<=n; j+=i) { if(j!=i) primes[(int)(j-m)] = 1; } } for(i=0; i<=n-m; i++) if(primes[(int)i]==0 && (i-1)%k==0) count++; return count; } } class SegTree { int n; long t[]; long mod=(long)(1000000007); SegTree(int n,long t[]){ this.n=n; this.t=t; build(); } void build() { // build the tree for (int i = n - 1; i > 0; --i) t[i]=(t[i<<1]|t[i<<1|1]); } void modify(int p, long value) { // set value at position p for (t[p += n]+=value; p > 1; p >>= 1) t[p>>1] = (t[p]|t[p^1]); } long query(int l, int r) { // sum on interval [l, r) long res=0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l&1)!=0) res=Math.max(res,t[l++]); if ((r&1)!=0) res=Math.max(res,t[--r]); } return res; } // // // } class FastScanner { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public FastScanner(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 readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components public UF(int N) { if (N < 0) throw new IllegalArgumentException(); count = N; parent = new int[N]; rank = new byte[N]; for (int i = 0; i < N; i++) { parent[i] = i; rank[i] = 0; } } public int find(int p) { if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException(); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public boolean union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return false; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; return true; } } class MyArrayList { private int[] myStore; private int actSize = 0; public MyArrayList(){ myStore = new int[2]; } public int get(int index){ if(index < actSize) return myStore[index]; else throw new ArrayIndexOutOfBoundsException(); } public void add(int obj){ if(myStore.length-actSize <= 1) increaseListSize(); myStore[actSize++] = obj; } public int size(){ return actSize; } private void increaseListSize(){ myStore = Arrays.copyOf(myStore, myStore.length*2); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
ed8f2a1546105d9ad34f26f8a9a2ab3d
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; public class WarOfTheCorporations { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String A= scan.next(); String B = scan.next(); A=A.replace(B,"#"); int count=0; for(int i=0;i<A.length();i++) if(A.charAt(i)=='#') count++; System.out.println(count); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
48ca786f4a738995356ff2c7a19c0ba4
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.*; public class A { public static void main(String [] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String first = reader.readLine().trim(); String second = reader.readLine().trim(); int lastIndex = 0; int count = 0; while(lastIndex != -1){ lastIndex = first.indexOf(second,lastIndex); if(lastIndex != -1){ count ++; lastIndex += second.length(); } } System.out.println(count); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
be609face6ee93370b3ba6a023d185da
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; public class WarOfCorp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String google = sc.nextLine(); String apple = sc.nextLine(); int index = google.indexOf(apple); int occurrences = 0; while (index != -1) { occurrences++; //google = google.substring(index + (apple.length()< google.length()? apple.length(): 1)); //google = google.substring(index + 1); index += apple.length(); index = google.indexOf(apple, index); } System.out.println(occurrences); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
e14ef51d26759422a39d1142e36098c5
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; public class TaskB { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); String s2 = sc.nextLine(); int n = 0; int i = s1.indexOf(s2); while (i != -1) { ++n; i = s1.indexOf(s2, i + s2.length()); } System.out.println(n); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
0c34a68690f188d85c0ea9795f07a4ea
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
/** * Created by Minsu on 2016-02-07. */ import java.util.*; import java.io.*; public class Main { MyScanner sc; PrintWriter out; void sol() { sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); String a = sc.next(), b = sc.next(); List<Integer> occur = new ArrayList<>(); for(int i=0; i+b.length() <= a.length(); i++){ boolean match = true; for(int j=0; j<b.length() && match; j++){ if( a.charAt(i+j) != b.charAt(j) ) match = false; } if( match ) occur.add( i ); } int ls = -1, ans = 0; for(int i=0; i<occur.size(); i++){ if( ls < occur.get(i) ){ ans++; ls = occur.get(i) + b.length() - 1; } } out.println( ans ); out.close(); } public static void main(String args[]) { new Main().sol(); } 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 ni() { return Integer.parseInt(sc.next()); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
50712d14014899d2fdda12420e19cee8
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static void newST() throws IOException {st = new StringTokenizer(in.readLine());} static int stInt() {return Integer.parseInt(st.nextToken());} static String stStr() {return st.nextToken();} static int[] getInts(int n) throws IOException {newST(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = stInt(); return arr;} static int readInt() throws IOException {return Integer.parseInt(in.readLine());} static void println(Object o) {System.out.println(o);} static void print(Object o) {System.out.print(o);} public static void main(String[] args) throws Exception { String s = in.readLine(); String t = in.readLine(); int sl = s.length(); int tl = t.length(); int last = -100; int a = 0; for (int i = 0; i <= sl-tl; i++) { boolean eq = true; for (int j = 0; j < tl; j++) { if (s.charAt(i+j) != t.charAt(j)) { eq = false; break; } } if (eq) { if (i-last >= tl) { a += 1; last = i; } } } System.out.println(a); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
23935a1875012cef48c71511b14e8867
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.*; import java.util.*; // Input // The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters. // Output // Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring. public class C625B { public static void main(String[] args) { NewReader sc = new NewReader(); char[] parentString = sc.nextString().toCharArray(); char[] childString = sc.nextString().toCharArray(); int prev = -1; int total = 0; for (int i = 0; i < parentString.length; i++) { boolean isSubstring = true; for (int j = 0; j < childString.length; j++) { if (i+j >= parentString.length || parentString[i+j] != childString[j]) { isSubstring = false; break; } } if (isSubstring) { if(prev == -1 || i-prev >= childString.length) { total++; prev=i;} } } System.out.println(total); } } class NewReader { InputStream is; public NewReader() { is = System.in; } String nextString() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } byte[] inbuf = new byte[1024]; 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++]; } 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(); } } char nextChar() { return (char) skip(); } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } 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(); } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
c0700d8729c4008575c67b41c4905f42
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
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; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream)) { Task solver = new Task(); solver.solve(1, in, out); } } } class Task { int result = 0; public void solve(int testNumber, InputReader in, PrintWriter out) { String gogole = in.nextLine(); String app = in.nextLine().trim(); gogole = gogole.replace(app, "^"); int i = 0; while(i < gogole.length()){ if(gogole.charAt(i) == '^') result++; i++; } out.println(result); } } 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); } } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output