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
b3180bd9e0078c80d53f8973336b6e9c
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class H { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int n = s.length(); int[][] A = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { A[i][i] = 1; if (i < n && s.charAt(i - 1) == s.charAt(i)) A[i][i + 1] = 1; } for (int l = 3; l <= n; l++) for (int i = 1; i + l <= n + 1; i++) A[i][i + l - 1] = A[i + 1][i + l - 2] & ((s.charAt(i - 1) == s.charAt(i + l - 2)) ? 1 : 0); for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) A[i][j] += A[i][j - 1]; for (int i = n; i > 0; i--) for (int j = 1; j <= n; j++) { if (i < n) A[i][j] += A[i + 1][j]; } int q = Integer.parseInt(in.readLine()); while (q-- > 0) { String[] Ss = in.readLine().split(" "); int x = Integer.parseInt(Ss[0]); int y = Integer.parseInt(Ss[1]); System.out.println(A[x][y]); } } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
53c2646d9b7d2cbc747659558434ed8d
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author sandeepandey */ 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); QueriesForNumberOfPalindrome solver = new QueriesForNumberOfPalindrome(); solver.solve(1, in, out); out.close(); } } class QueriesForNumberOfPalindrome { public void solve(int testNumber, InputReader in, OutputWriter out) { String type = in.readString(); int charCount = type.length(); boolean[][] isPalindrome = new boolean[charCount+1][charCount+1] ; int[][] dp = new int[charCount+1][charCount+1]; ArrayUtils.fill(isPalindrome, false); ArrayUtils.fill(dp,0); // all one length strings are palindrome for(int i = 0;i < charCount ; i++) { isPalindrome[i][i] = true; dp[i][i] = 1; } for(int len = 2;len <= charCount;len++) { for(int j = 0;(len + j -1) < charCount;j++) { int start = j; int end = len+j-1; if(len == 2) { isPalindrome[start][end] = (type.charAt(start)== type.charAt(end)); } else { isPalindrome[start][end] = isPalindrome[start+1][end-1] && (type.charAt(start)== type.charAt(end)); } dp[start][end] = dp[start][end-1]+dp[start+1][end]-dp[start+1][end-1]; if(isPalindrome[start][end]){ dp[start][end]+=1; } } } int queryCount = in.readInt(); for(int i = queryCount;i != 0 ; i--) { out.printLine(dp[in.readInt()-1][in.readInt()-1]); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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(); } } class ArrayUtils { public static void fill(int[][] array,int value) { for(int[] i : array) { Arrays.fill(i,value); } } public static void fill(boolean[][] array,boolean value) { for(boolean[] i: array){ Arrays.fill(i,value); } } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
07169d7c3092be2244315ad5a3db9850
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * 6 * 1 0 * 0 0 * 0 0 * 1 1 * 0 1 * 1 1 * * @author pttrung */ public class B { public static int[] x = {0, 0, 1, -1}; public static int[] y = {-1, 1, 0, 0}; static HashMap<Long, Integer> map = new HashMap(); public static void main(String[] args) throws FileNotFoundException { PrintWriter out; Scanner in = new Scanner(); // out = new PrintWriter(new FileOutputStream(new File("output.txt"))); out = new PrintWriter(System.out); String v = in.next(); int q = in.nextInt(); int n = v.length(); boolean[][] check = new boolean[n][n]; for (int i = 0; i < n; i++) { check[i][i] = true; for (int j = 0; j < i; j++) { if (v.charAt(j) == v.charAt(i)) { if (j + 1 <= i - 1) { check[j][i] = check[j + 1][i - 1]; } else { check[j][i] = true; } } } } int[][] dp = new int[n][n]; for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { if (check[i][j]) { // System.out.println(i + " " + j); dp[i][j]++; } if (j > 0) { dp[i][j] += dp[i][j - 1]; } if (i + 1 <= j) { dp[i][j] += dp[i + 1][j]; } if (j > 0 && i + 1 <= j - 1) { dp[i][j] -= dp[i + 1][j - 1]; } //System.out.println(i + " " + j + " " + dp[i][j]); } } for (int i = 0; i < q; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; out.println(dp[a][b]); } out.close(); } static int cost(long v, long[] p) { if (map.containsKey(v)) { return map.get(v); } long s = v; int result = 0; for (long i : p) { while (v % i == 0) { v /= i; result--; } } for (long i = 2; i * i <= v; i++) { while (v % i == 0) { v /= i; result++; } } if (v != 1) { result++; } map.put(s, result); return result; } static int countDivisor(long a) { int c = 0; for (long i = 2; i * i <= a; i++) { while (a % i == 0) { a /= i; c++; } } if (a != 1) { c++; } return c; } static long gcd(long a, long b) { while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } static int find(int index, int[] u) { if (index != u[index]) { return u[index] = find(u[index], u); } return index; } public static long dist(int x1, int y1, int x2, int y2) { long x = x1 - x2; long y = y1 - y2; return x * x + y * y; } public static Line getLine(Point a, Point b) { int c = (a.x - b.x); int d = (a.y - b.y); if (c == 0) { return new Line(1, 0, -a.x); } else if (d == 0) { return new Line(0, 1, -a.y); } else { double rate = (double) (-d) / c; double other = ((double) rate * a.x) + a.y; //System.out.println(a + "|" + b + ": " + rate + " " + other); return new Line(rate, 1, -other); } } public static class Line { double a, b, c; public Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public int hashCode() { int hash = 7; hash = 47 * hash + (int) (Double.doubleToLongBits(this.a) ^ (Double.doubleToLongBits(this.a) >>> 32)); hash = 47 * hash + (int) (Double.doubleToLongBits(this.b) ^ (Double.doubleToLongBits(this.b) >>> 32)); hash = 47 * hash + (int) (Double.doubleToLongBits(this.c) ^ (Double.doubleToLongBits(this.c) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Line other = (Line) obj; if (Double.doubleToLongBits(this.a) != Double.doubleToLongBits(other.a)) { return false; } if (Double.doubleToLongBits(this.b) != Double.doubleToLongBits(other.b)) { return false; } if (Double.doubleToLongBits(this.c) != Double.doubleToLongBits(other.c)) { return false; } return true; } @Override public String toString() { return a + " " + b + " " + c; } } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } public static double dist(Point a, Point b) { double val = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return Math.sqrt(val); } public static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static long pow(int a, int 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 long lcm(long a, long b) { return a * b / gcd(a, b); } 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 FileReader(new File("output.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
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
41b678ceebf84b1bb6adaeefe65f8912
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; 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); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } } class TaskH { public void solve(int testNumber, InputReader in, OutputWriter out) { char[] s = in.readString().toCharArray(); int n = s.length; int[][] dp = new int[n][n]; boolean[][] isPalindrome = new boolean[n][n]; for (int i = 0; i < n; i++) { isPalindrome[i][i] = true; dp[i][i] = 1; } for (int len = 2; len <= n; len++) { for (int i = 0; i < n; i++) { int j = i + len - 1; if (j >= n) break; if (len == 2) { isPalindrome[i][j] = (s[i] == s[j]); dp[i][j] = 2 + (isPalindrome[i][j] ? 1 : 0); } else { isPalindrome[i][j] = (isPalindrome[i + 1][j - 1] && s[i] == s[j]); dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] + (isPalindrome[i][j] ? 1 : 0); } } } int q = in.readInt(); while (q-- > 0) { int l = in.readInt() - 1; int r = in.readInt() - 1; out.printLine(dp[l][r]); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return 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); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } 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
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
83c723d710512bc8f80017fdcdfa9998
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class appl { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tok; private static String nextToken() { while (tok == null || !tok.hasMoreTokens()) { try { tok = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return tok.nextToken(); } private static int nextInt() { return Integer.parseInt(nextToken()); } public static void main(String[] args) { byte[][] array = new byte[5000][5000]; int[][] pals = new int[5000][5000]; String str = nextToken(); int strlen = str.length(); for (int i = 0; i < strlen; i++) { array[i][i] = 1; pals[i][i] = 1; } for (int i = 1; i < strlen; i++) { for (int j = i - 1; j >= 0; j--) { if (i - j > 1 && array[i - 1][j + 1] == 1 && str.charAt(i) == str.charAt(j)) { array[i][j] = 1; } else if (i - j <= 1 && str.charAt(i) == str.charAt(j)) { array[i][j] = 1; pals[i][j] = 3; } else if (i - j <= 1 && str.charAt(i) != str.charAt(j)) { pals[i][j] = 2; } if(i - j > 1){ pals[i][j] = pals[i - 1][j] + pals[i][j + 1] - pals[i - 1][j + 1] + array[i][j]; } // pals[i][j] = pals[i - 1][j] + 1; // for (int k = j; k < i; k++) { // pals[i][j] += array[i][k]; // } } } int count = nextInt(); for (int i = 0; i < count; i++) { int l = nextInt(), r = nextInt(); System.out.println(pals[r - 1][l - 1]); } // for (int i = 0; i < str.length(); i++) { // for (int j = 0; j < str.length(); j++) { // System.out.print(pals[i][j]); // System.out.print(" "); // } // System.out.println(); // } } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
867fa8f2fdd7d7fcd5736ce626aa9737
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class H { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } public static void main(String[] args) throws Exception { String str = next(); int[][] count = new int[str.length()][str.length()]; for (int i = 0; i < str.length(); i++) { for (int j = 0; j + i < str.length(); j++) { int next = j + i; if (j == next) { count[j][j] = 1; } else { if (str.charAt(j) == str.charAt(next)) { if (j + 1 <= next - 1) { count[j][next] = count[j + 1][next - 1]; } else { count[j][next] = 1; } } } } } for (int i = 0; i < str.length(); i++) { for (int j = 0; j + i < str.length(); j++) { int next = j + i; if (j == next) { count[j][j] = 1; } else { count[j][next] += count[j + 1][next] + count[j][next - 1]; if (j + 1 <= next - 1) { count[j][next] -= count[j + 1][next - 1]; } } } } PrintWriter out=new PrintWriter(System.out); int qCnt = nextInt(); for (int i = 0; i < qCnt; i++) { out.println(count[nextInt() - 1][nextInt() - 1]); if(i%100==0){ out.flush(); } } out.flush(); } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
661e01fc564bfa8660ac860927607c90
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.*; import java.util.*; public class H { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { char[] s = nextToken().toCharArray(); int n = s.length; int[][] a = new int[n + 1][n + 1]; for (int i = 0; i < n; i++) { a[i + 1][i + 1] = 1; } for (int i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) a[i + 1][i + 2] = 1; } for (int len = 3; len <= n; len++) for (int st = 0; st <= n - len; st++) { int en = st + len - 1; if (s[st] == s[en] && a[st + 1 + 1][en - 1 + 1] == 1) a[st + 1][en + 1] = 1; } // System.err.println(); // for (int i = 0; i <= n; i++) // System.err.println(Arrays.toString(a[i])); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i + 1][j + 1] += a[i + 1][j] + a[i][j + 1] - a[i][j]; // System.err.println(); // for (int i = 0; i <= n; i++) // System.err.println(Arrays.toString(a[i])); int q = nextInt(); while (q-- > 0) { int l = nextInt() - 1; int r = nextInt() - 1; int res = a[r + 1][r + 1] - a[r + 1][l] - a[l][r + 1] + a[l][l]; out.println(res); } } H() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new H(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
06ce678a4a4f6c4c2ce0903dfba2eee0
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.*; import java.util.*; public class H { private static BufferedReader reader; private static PrintWriter writer; private static StringTokenizer tokenizer; private static void println() { writer.println(); } private static void print(String obj) { writer.print(obj); } private static void println(Object obj) { writer.println(obj); } private static void printf(String f, Object... obj) { writer.printf(f, obj); } private static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException{ begin(); String s = nextToken(); int n = s.length(); int [][]dp = new int [n+1][n+1]; boolean [][]pdm = new boolean [n+1][n+1]; for (int i = 0; i < n; i++) { dp[i][i] = 1; pdm[i][i] = true; } for (int i = 2; i <=n; i++) { for (int j = 0; j <=n-i; j++) { dp[j][j+i-1] = dp[j+1][j+i-1]+dp[j][j+i-2]-dp[j+1][i+j-2]; if (s.charAt(j) == s.charAt(j+i-1)){ if (pdm[j+1][j+i-2]){ dp[j][j+i-1]++; pdm[j][j+i-1] = true; } if (i == 2){ dp[j][j+i-1]++; pdm[j][j+i-1] = true; } } } } int m = nextInt(),L,R; for (int i = 0; i < m; i++) { L = nextInt()-1; R = nextInt()-1; println(dp[L][R]); } end(); } private static void end() { writer.close(); } private static void begin() throws IOException{ reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new OutputStreamWriter(System.out)); } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
096c1cfddaf7f33781df5e6fb0df6582
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; StreamInputReader in = new StreamInputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskH solver = new TaskH(); solver.solve(1, in, out); out.close(); } } class TaskH { public void solve(int testNumber, StreamInputReader in, PrintWriter out) { String s = in.nextString(); int N = s.length(); /*int Q = in.nextInt(); ArrayList<Pair>[] queries = new ArrayList[N + 1]; for(int i = 1; i <= N; i++) queries[i] = new ArrayList<Pair>(); for(int i = 0; i < Q; i++) { int left = in.nextInt() - 1; int right = in.nextInt() - 1; queries[right - left].add(new Pair(left, i)); }*/ int[][] numPal = new int[N + 1][N + 1]; for(int i = 0; i < N; i++) numPal[i][i] = 1; for(int i = 0; i < N; i++) { // centered for(int j = 1; i - j >= 0 && i + j < N; j++) if(s.charAt(i - j) == s.charAt(i + j)) numPal[i - j][i + j] = 1; else break; // not centered if(i < N - 1 && s.charAt(i) == s.charAt(i + 1)) { numPal[i][i + 1] = 1; for(int j = 1; i - j >= 0 && i + 1 + j < N; j++) if(s.charAt(i - j) == s.charAt(i + j + 1)) numPal[i - j][i + j + 1] = 1; else break; } } for(int len = 2; len <= N; len++) for(int i = 0; i < N - len + 1; i++) { int j = i + len - 1; numPal[i][j] = numPal[i][j] + numPal[i + 1][j] + numPal[i][j - 1] - numPal[i + 1][j - 1]; } int Q = in.nextInt(); int left = -1; int right = -1; for(int i = 0; i < Q; i++) { left = in.nextInt() - 1; right = in.nextInt() - 1; out.println(numPal[left][right]); } } /* private class Pair { public int left; public int idx; private Pair(int left, int idx) { this.left = left; this.idx = idx; } }*/ } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public StreamInputReader(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++]; } } abstract class InputReader { public abstract int read(); public int nextInt() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
2ac69b77b58f270c56d03d79e27a8fa7
train_003.jsonl
1353339000
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class taskH { StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws NumberFormatException, IOException { taskH solver = new taskH(); solver.open(); long time = System.currentTimeMillis(); solver.solve(); if (!"true".equals(System.getProperty("ONLINE_JUDGE"))) { System.out.println("Spent time: " + (System.currentTimeMillis() - time)); System.out.println("Memory: " + (Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory())); } solver.close(); } public void open() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } public void solve() throws NumberFormatException, IOException { String tmp = nextToken(); int n = tmp.length(); char inp[] = new char[n]; for (int i = 0; i < n; i++) { inp[i]=tmp.charAt(i); } int dp[][] = new int[n][n]; boolean pl[][] = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j]=0; pl[i][j]=false; } } for (int i = 0; i < n; i++) { int d =0; while (i-d>=0 && i+d < n && inp[i-d]==inp[i+d]) { pl[i-d][i+d] = true; d++; } d = 0; while (i-d>=0 && i+d+1 < n && inp[i-d]==inp[i+d+1]) { pl[i-d][i+d+1] = true; d++; } } for (int i = 0; i < n; i++) { int cnt = 0; for (int j = i; j < n; j++) { if (pl[i][j]) cnt++; dp[i][j]+=cnt; } } for (int j = 0; j < n; j++) { for (int i = j; i >= 0 ; i--) { if (i+1<n) dp[i][j] +=dp[i+1][j]; } } int q = nextInt(); for (int i = 0; i < q; i++) { int l = nextInt(), r = nextInt(); out.println(dp[l-1][r-1]); } } public void close() { out.flush(); out.close(); } }
Java
["caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5"]
5 seconds
["1\n7\n3\n4\n2"]
NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».
Java 7
standard input
[ "dp", "hashing", "strings" ]
1d8937ab729edad07b3b23b1927f7e11
The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.
1,800
Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
standard output
PASSED
46f7fc40ac8e4e4e91644b5f0bc34e91
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; public class CF1105D { public static void main(String[] args) { CF1105D cf = new CF1105D(); /** 初始化游戏场景 **/ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //行数 int m = sc.nextInt(); //列数 int p = sc.nextInt(); //人数 //初始化玩家的扩张速度 long[] speed = new long[p + 1]; //初始化玩家的可扩张点(可扩张点是指在玩家的所占领的城堡中,不被"包围",仍然可以向外扩张的点) Map<Integer, Set<Point>> playerSeeds = new HashMap<Integer, Set<Point>>(); //初始化玩家占领的城堡总数 int[] castles = new int[p + 1]; for(int i = 1; i < p + 1; i++){ speed[i] = sc.nextLong(); Set<Point> seeds = new HashSet<Point>(); playerSeeds.put(i, seeds); } //初始化棋盘 int[][] grid = new int[n][m]; for(int i = 0; i < n; i++){ String line = sc.next(); for(int j = 0; j < m; j++){ String cell = line.charAt(j) + ""; if(".".equals(cell)){ grid[i][j] = 0; }else if("#".equals(cell)){ grid[i][j] = -1; }else{ int player = Integer.parseInt(cell); //玩家序号 grid[i][j] = player; Set<Point> seeds = playerSeeds.get(player); seeds.add(cf.new Point(i, j)); playerSeeds.put(player, seeds); castles[player] = castles[player] + 1; } } } /** 开始游戏 **/ //从第1个玩家开始 int playerInRound = 1; while(true){ //玩家还可以游戏 if(playerSeeds.get(playerInRound).size() != 0){ //计算本次扩张将得到的领地列表,并把新的可扩张点更新到playerSeeds中 Set<Point> expansionPoint = cf.expansion(speed, playerInRound, grid, playerSeeds); //在棋盘上建立城堡 if(expansionPoint.size() > 0){ for(Point point : expansionPoint){ grid[point.getX()][point.getY()] = playerInRound; castles[playerInRound] = castles[playerInRound] + 1; } } } //轮换下一个玩家 if(playerInRound == p){ playerInRound = 1; }else{ playerInRound++; } //所有的玩家都无法扩张则游戏结束 boolean end = true; checkEnd: for(int i = 1; i < p + 1; i++){ if(playerSeeds.get(i).size() != 0){ end = false; break checkEnd; } } if(end){ break; } } /** 游戏结束,打印结果 **/ String result = ""; for(int i = 1; i < p + 1; i++){ result = result + castles[i] + " "; } System.out.println(result); } /** * 扩张 * @param speed 扩张速度 * @param player 玩家 * @param grid 棋盘 * @param playerSeeds 玩家的可扩张点集合 */ private Set<Point> expansion(long[] speed, int player, int[][] grid, Map<Integer, Set<Point>> playerSeeds){ Set<Point> expansionPoint = new HashSet<Point>(); //从原点向外逐层扩张 Set<Point> seeds = playerSeeds.get(player); for(int expLayer = 0; expLayer < speed[player]; expLayer++){ Set<Point> nextSeeds = new HashSet<Point>(); for(Point seed : seeds){ Set<Point> expanedPoint = expansionFromSeed(seed, grid, expansionPoint); nextSeeds.addAll(expanedPoint); expansionPoint.addAll(expanedPoint); } seeds = nextSeeds; if(seeds.size() == 0){ break; } } playerSeeds.put(player, seeds); return expansionPoint; } /** * 一个节点的一步扩张 * @param seed 可扩张点 * @param grid 棋盘 * @param expansedPoint 之前层级已经扩张的点 * @return */ private Set<Point> expansionFromSeed(Point seed, int[][] grid, Set<Point> expansedPoint){ int i = seed.getX(); int j = seed.getY(); int n = grid.length; int m = grid[0].length; Set<Point> expansionPoint = new HashSet<Point>(); //向上扩张一格 if(i > 0){ Point point = new Point(i - 1, j); if(grid[point.getX()][point.getY()] == 0 && !expansedPoint.contains(point)) { expansionPoint.add(point); } } //向下扩张一格 if(i < n - 1){ Point point = new Point(i + 1, j); if(grid[point.getX()][point.getY()] == 0 && !expansedPoint.contains(point)) { expansionPoint.add(point); } } //向左扩张一格 if(j > 0){ Point point = new Point(i, j - 1); if(grid[point.getX()][point.getY()] == 0 && !expansedPoint.contains(point)) { expansionPoint.add(point); } } //向右扩张一格 if(j < m - 1){ Point point = new Point(i, j + 1); if(grid[point.getX()][point.getY()] == 0 && !expansedPoint.contains(point)) { expansionPoint.add(point); } } return expansionPoint; } class Point{ int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public String toString() { return "(" + x + "," + y + ")"; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (obj instanceof Point) { Point point = (Point) obj; if (point.x == this.getX() && point.y == this.getY()) return true; } return false; } @Override public int hashCode() { return Integer.valueOf(x).hashCode() * Integer.valueOf(y).hashCode(); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
dc4fc77eedf2464b6403a0ff06af5e0a
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.AbstractCollection; import java.util.Vector; import java.util.Scanner; import java.util.LinkedList; /** * 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); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); char[][] grid = new char[n][m]; List<Integer[]>[] adj = new Vector[p]; int[] s = new int[p]; for (int i = 0; i < p; i++) { s[i] = in.nextInt(); adj[i] = new Vector<>(); } in.nextLine(); for (int i = 0; i < n; i++) grid[i] = in.nextLine().toCharArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '.' || grid[i][j] == '#') continue; int player = grid[i][j] - '1'; if (i - 1 >= 0 && grid[i - 1][j] == '.') { adj[player].add(new Integer[]{i - 1, j}); } if (i + 1 < n && grid[i + 1][j] == '.') { adj[player].add(new Integer[]{i + 1, j}); } if (j - 1 >= 0 && grid[i][j - 1] == '.') { adj[player].add(new Integer[]{i, j - 1}); } if (j + 1 < m && grid[i][j + 1] == '.') { adj[player].add(new Integer[]{i, j + 1}); } } } while (true) { boolean end = false; for (int i = 0; i < p; i++) { boolean flag = BFS(adj[i], grid, i, s[i], n, m, out); end = end || flag; } if (end == false) break; } int[] r = new int[p]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (grid[i][j] != '#' && grid[i][j] != '.') { r[grid[i][j] - '1']++; } } for (int i = 0; i < p; i++) { out.print(r[i] + " "); } out.println(); } private static boolean BFS(List<Integer[]> adjP, char[][] grid, int player, int dist, int n, int m, PrintWriter out) { LinkedList<Integer[]> queue = new LinkedList(); for (Integer[] v : adjP) queue.add(new Integer[]{v[0], v[1], 1}); adjP.clear(); while (queue.isEmpty() == false) { Integer[] v = queue.pollFirst(); int i = v[0]; int j = v[1]; int d = v[2]; if (grid[i][j] != '.') continue; if (d > dist) { adjP.add(new Integer[]{i, j}); continue; } else { grid[i][j] = (char) (player + '1'); } if (i - 1 >= 0 && grid[i - 1][j] == '.') { queue.add(new Integer[]{i - 1, j, d + 1}); } if (i + 1 < n && grid[i + 1][j] == '.') { queue.add(new Integer[]{i + 1, j, d + 1}); } if (j - 1 >= 0 && grid[i][j - 1] == '.') { queue.add(new Integer[]{i, j - 1, d + 1}); } if (j + 1 < m && grid[i][j + 1] == '.') { queue.add(new Integer[]{i, j + 1, d + 1}); } } return adjP.isEmpty() == false; } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
fece1388a3f116d9a92c1166765545bc
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; public class Ans { static int n; static int m; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); int p = sc.nextInt(); char [][] grid = new char[n][m]; ArrayDeque<Pair> q [] = new ArrayDeque[p]; int [] count = new int[p]; int [] turns = new int[p]; for(int i = 0; i < p; i++) { turns[i] = sc.nextInt(); q[i] = new ArrayDeque<>(); } for (int i = 0; i < n; i++) { String s = sc.nextLine(); for (int j = 0; j < m; j++) { grid[i][j] = s.charAt(j); if (Character.isDigit(grid[i][j])) { q[grid[i][j] - '1'].add(new Pair(i, j, 0)); count[grid[i][j] - '1']++; } } } boolean flag = true; int [] res = new int[p]; while (flag) { flag = false; for (int i = 0; i < p; i++) { ArrayDeque<Pair> temp = new ArrayDeque<>(); while (!q[i].isEmpty()) { Pair poll = q[i].poll(); // don't explore children if (poll.c >= turns[i]) { continue; } if (isValid(grid, poll.a + 1, poll.b)) { flag = true; Pair e = new Pair(poll.a + 1, poll.b, poll.c + 1); q[i].add(e); temp.add(e); grid[poll.a + 1][poll.b] = (char) (i + 1); res[i]++; } if (isValid(grid, poll.a - 1, poll.b)) { flag = true; Pair e = new Pair(poll.a - 1, poll.b, poll.c + 1); q[i].add(e); temp.add(e); grid[poll.a - 1][poll.b] = (char) (i + 1); res[i]++; } if (isValid(grid, poll.a, poll.b + 1)) { flag = true; Pair e = new Pair(poll.a, poll.b + 1, poll.c + 1); q[i].add(e); temp.add(e); grid[poll.a][poll.b + 1] = (char) (i + 1); res[i]++; } if (isValid(grid, poll.a, poll.b - 1)) { flag = true; Pair e = new Pair(poll.a, poll.b - 1, poll.c + 1); q[i].add(e); temp.add(e); grid[poll.a][poll.b - 1] = (char) (i + 1); res[i]++; } } q[i].clear(); for (Pair pair : temp) { q[i].add(new Pair(pair.a, pair.b, 0)); } // q[i].addAll(temp); } } for (int i = 0; i < p; i++) { System.out.print((res[i] + count[i]) + " "); } } private static boolean isValid(char[][] grid, int r, int c) { if (r >= 0 && c >= 0 && r < n && c < m && grid[r][c] == '.') { return true; } return false; } static class Pair implements Comparable<Pair> { int a; int b; int c; public Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(Pair o) { return this.a - o.a; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() { for (long i = 0; i < 3e9; i++) ; } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
d59f35bdceae4af78656b106da299e1f
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; public class KilaniAndTheGame{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int p = sc.nextInt(); int speed[] = new int[p]; int grid[][] = new int[n][m]; int cord[][][] = new int[1000000][2][p]; int count[] = new int[p]; for(int i=0;i<p;i++) speed[i]=sc.nextInt(); for(int i=0;i<n;i++){ String s = sc.next(); for(int j=0;j<m;j++){ if(s.charAt(j)=='.') grid[i][j]=0; else if(s.charAt(j)=='#') grid[i][j]=-1; else{ int temp = s.charAt(j) - '0'; //System.out.println(temp); grid[i][j]= temp; cord[count[temp-1]][0][temp-1]=i; cord[count[temp-1]][1][temp-1]=j; count[temp-1]++; } } } // for(int i=0;i<p;i++){ // System.out.print(count[i]+" "); // } // for(int i=0;i<p;i++){ // for(int j=0;j<count[i];j++){ // System.out.println(cord[j][0][i]); // System.out.println(cord[j][1][i]); // } // } Queue<Integer>[] xque = new ArrayDeque[p]; Queue<Integer>[] yque = new ArrayDeque[p]; for(int i=0;i<p;i++) xque[i] = new ArrayDeque(); for(int i=0;i<p;i++) yque[i] = new ArrayDeque(); for(int i=0;i<p;i++){ for(int j=0;j<count[i];j++){ xque[i].add(cord[j][0][i]); yque[i].add(cord[j][1][i]); } } boolean b=true; for(int i=0;i<p;i++){ b = b && !xque[i].isEmpty(); } int ax[] = new int[]{0, 1, -1, 0}; int ay[] = new int[]{1, 0, 0, -1}; while(b){ for(int i=0;i<p;i++){ int tmp=xque[i].size(); if(!xque[i].isEmpty()){ for(int k=0;k<speed[i] && !xque[i].isEmpty();k++){ for(int po=0;po<tmp;po++){ int x = xque[i].poll(); int y = yque[i].poll(); for(int j=0;j<4;j++){ int x1 = x - ax[j]; int y1 = y - ay[j]; if(x1>=0 && x1<n && y1>=0 && y1<m){ if(grid[x1][y1]==0){ xque[i].add(x1); yque[i].add(y1); grid[x1][y1]=i+1; count[i]++; } } } } tmp=xque[i].size(); // for(int l=0;l<n;l++) // { // for(int o=0;o<m;o++) // System.out.print(grid[l][o]+" "); // System.out.println(); // } } } } b=false; for(int i=0;i<p;i++){ b = b || !xque[i].isEmpty(); } } // for(int i=0;i<n;i++) // { // for(int j=0;j<m;j++) // System.out.print(grid[i][j]+" "); // System.out.println(); // } for(int i=0;i<p;i++) System.out.print(count[i]+" "); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
0a1e7057a401fc27249640dd4a3783d9
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.Function; public class MainD { static int H, W, P; static int[] S; static char[][] C; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); H = sc.nextInt(); W = sc.nextInt(); P = sc.nextInt(); S = sc.nextIntArray(P); C = new char[H][]; for (int i = 0; i < H; i++) { C[i] = sc.next().toCharArray(); } int[] ans = solve(); StringJoiner j = new StringJoiner(" "); for (int i : ans) { j.add(String.valueOf(i)); } System.out.println(j.toString()); } static int[] solve() { State[][] D = new State[H][W]; ArrayDeque<State>[] currs = new ArrayDeque[P]; ArrayDeque<State>[] nexts = new ArrayDeque[P]; for (int i = 0; i < P; i++) { currs[i] = new ArrayDeque<>(); nexts[i] = new ArrayDeque<>(); } List<State> init = new ArrayList<>(); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if( Character.isDigit(C[i][j]) ) { int p = C[i][j] - '0'; State s = new State(i, j, p, 1, S[p-1]); currs[p-1].add( s ); D[i][j] = s; } } } while(true) { boolean hasNext = false; for (int i = 0; i < P; i++) { hasNext |= bfs(D, currs[i], nexts[i]); } if( hasNext ) { ArrayDeque<State>[] t = currs; currs = nexts; nexts = t; } else { break; } } int[] ans = new int[P]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if( D[i][j] != null ) { ans[D[i][j].p-1]++; } } } // char[][] R = new char[H][W]; // for (int i = 0; i < H; i++) { // for (int j = 0; j < W; j++) { // if( C[i][j] == '#' ) { // R[i][j] = '#'; // // } else if( D[i][j] != null ) { // R[i][j] = (char)('0' + D[i][j].p); // // } else { // R[i][j] = '?'; // } // } // } // // for (char[] row : R) { // debug(new String(row)); // } return ans; } static boolean bfs(State[][] D, ArrayDeque<State> curr, ArrayDeque<State> next) { while(!curr.isEmpty()) { State s = curr.poll(); for (int i = 0; i < 4; i++) { int nh = s.h + DH[i]; int nw = s.w + DW[i]; if( !inRange(nh, nw) ) continue; int nt; int nr; if( s.r == 1 ) { nt = s.t + 1; nr = S[s.p-1]; } else { nt = s.t; nr = s.r-1; } if( D[nh][nw] == null ) { State ns = new State(nh, nw, s.p, nt, nr); if( ns.t == s.t ) { curr.add(ns); } else { next.add(ns); } D[nh][nw] = ns; } } } return !next.isEmpty(); } static boolean inRange(int nh, int nw) { return 0 <= nh && nh < H && 0 <= nw && nw < W && C[nh][nw] == '.'; } static int[] DH = {0, 1, 0, -1}; static int[] DW = {1, 0, -1, 0}; static class State { int h, w; int p, t, r; public State(int h, int w, int p, int t, int r) { this.h = h; this.w = w; this.p = p; this.t = t; this.r = r; } public int compareTo(int t1, int p1, int r1) { if( t != t1 ) return Integer.compare(t, t1); if( p != p1 ) return Integer.compare(p, p1); return Integer.compare(r, r1); } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
bf717383f3af10cbcba02a192d5a8c62
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.math.*; public class Main{ static class stage{ int r,l,dex,step; } static int row,line,num,xx,dir[][]={{1,0},{-1,0},{0,1},{0,-1}}; static char ch; static Queue<stage> q1=new LinkedList(),q2=new LinkedList(),q3=new LinkedList(),q4=new LinkedList(),q5=new LinkedList(),q6=new LinkedList(),q7=new LinkedList(),q8=new LinkedList(),q9=new LinkedList(); static String str=new String(); static int vis[][]=new int[1005][1005],pep[]=new int[11],v[]=new int[11]; public static void main(String args[]){ Scanner cin=new Scanner(System.in); row=cin.nextInt(); line=cin.nextInt(); num=cin.nextInt(); xx=9-num; for(int i=1;i<=num;i++) v[i]=cin.nextInt(); Arrays.fill(pep,0); for(int i=1;i<=row;i++){ str=cin.next(); for(int j=1;j<=line;j++){ if(str.charAt(j-1)=='#') vis[i][j]=-1; else if(str.charAt(j-1)=='.') vis[i][j]=0; else { stage er=new stage(); er.r=i; er.l=j; int x=(str.charAt(j-1)-'0'); vis[i][j]=er.dex=x; er.step=0; switch(x){ case 1: q1.add(er); break; case 2: q2.add(er); break; case 3: q3.add(er); break; case 4: q4.add(er); break; case 5: q5.add(er); break; case 6: q6.add(er); break; case 7: q7.add(er); break; case 8: q8.add(er); break; case 9: q9.add(er); break; } } //System.out.println(vis[i][j]); } } while(true){ if(xx==9) break; switch(1){ case 1: if(!q1.isEmpty()) bfs(q1); case 2: if(!q2.isEmpty()) bfs(q2); case 3: if(!q3.isEmpty()) bfs(q3); case 4: if(!q4.isEmpty()) bfs(q4); case 5: if(!q5.isEmpty()) bfs(q5); case 6: if(!q6.isEmpty()) bfs(q6); case 7: if(!q7.isEmpty()) bfs(q7); case 8: if(!q8.isEmpty()) bfs(q8); case 9: if(!q9.isEmpty()) bfs(q9); } } //System.out.println("$$$$$$$$$$$$"); for(int i=1;i<=row;i++){ for(int j=1;j<=line;j++){ if(vis[i][j]>0) pep[vis[i][j]]++; } } for(int i=1;i<=num;i++){ if(i>1) System.out.print(" "); System.out.print(pep[i]); } } static void bfs(Queue<stage> que){ int h=v[que.peek().dex]; stage op,os; while(h>0){ if(que.isEmpty()){ xx++; //System.out.println("*"+xx); return; } h--; int ss=que.peek().step; while(true){ if(que.isEmpty()){ xx++; //System.out.println("*"+xx); return; } if(que.peek().step>ss) break; op=que.remove(); for(int i=0;i<4;i++){ int yy=op.r+dir[i][0]; int xx=op.l+dir[i][1]; if(yy>0&&yy<=row&&xx>0&&xx<=line&&vis[yy][xx]==0){ vis[yy][xx]=op.dex; os=new stage(); os.l=xx; os.r=yy; os.dex=op.dex; os.step=op.step+1; que.add(os); } } } } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
22f6c75ff485ea3b63b39544a9494b23
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.math.*; public class Main{ static class stage{ int r,l,dex,step; } static int row,line,num,xx,dir[][]={{1,0},{-1,0},{0,1},{0,-1}}; static char ch; static Queue<stage> q[]=new Queue[10]; static String str=new String(); static int vis[][]=new int[1005][1005],pep[]=new int[11],v[]=new int[11]; public static void main(String args[]){ Scanner cin=new Scanner(System.in); row=cin.nextInt(); line=cin.nextInt(); num=cin.nextInt(); for(int i=1;i<=9;i++) q[i]=new LinkedList<stage>(); xx=9-num; for(int i=1;i<=num;i++) v[i]=cin.nextInt(); Arrays.fill(pep,0); for(int i=1;i<=row;i++){ str=cin.next(); for(int j=1;j<=line;j++){ if(str.charAt(j-1)=='#') vis[i][j]=-1; else if(str.charAt(j-1)=='.') vis[i][j]=0; else { stage er=new stage(); er.r=i; er.l=j; int x=(str.charAt(j-1)-'0'); vis[i][j]=er.dex=x; er.step=0; q[x].add(er); } } } while(true){ if(xx==9) break; for(int i=1;i<=9;i++){ if(!q[i].isEmpty()) bfs(q[i]); } } for(int i=1;i<=row;i++){ for(int j=1;j<=line;j++){ if(vis[i][j]>0) pep[vis[i][j]]++; } } for(int i=1;i<=num;i++){ if(i>1) System.out.print(" "); System.out.print(pep[i]); } } static void bfs(Queue<stage> que){ int h=v[que.peek().dex]; stage op,os; while(h>0){ if(que.isEmpty()){ xx++; return; } h--; int ss=que.peek().step; while(true){ if(que.isEmpty()){ xx++; return; } if(que.peek().step>ss) break; op=que.remove(); for(int i=0;i<4;i++){ int yy=op.r+dir[i][0]; int xx=op.l+dir[i][1]; if(yy>0&&yy<=row&&xx>0&&xx<=line&&vis[yy][xx]==0){ vis[yy][xx]=op.dex; os=new stage(); os.l=xx; os.r=yy; os.dex=op.dex; os.step=op.step+1; que.add(os); } } } } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
c12abe7102d2460a9d9ae9ff20603e5a
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
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 * * @author Vadim */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), m = in.ni(), p = in.ni(); int[] speed = in.na(p); char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = in.ns().toCharArray(); } Point[][] qs = new Point[p][n * m]; int[] qis = new int[p]; int totCnt = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] != '.' && map[i][j] != '#') { int id = map[i][j] - '1'; qs[id][qis[id]++] = new Point(i, j); totCnt++; } } } Point[] temp = new Point[n * m]; int[] dirr = new int[]{1, 0, -1, 0}; int[] dirc = new int[]{0, 1, 0, -1}; while (totCnt > 0) { for (int i = 0; i < p; i++) { for (int round = 0; round < speed[i] && qis[i] != 0; round++) { int nqi = 0; for (int j = 0; j < qis[i]; j++) { Point po = qs[i][j]; totCnt--; for (int k = 0; k < 4; k++) { int nr = po.r + dirr[k]; int nc = po.c + dirc[k]; if (0 <= nr && nr < n && 0 <= nc && nc < m && map[nr][nc] == '.') { temp[nqi++] = new Point(nr, nc); totCnt++; map[nr][nc] = (char) ('1' + i); } } } qis[i] = nqi; Point[] swap = qs[i]; qs[i] = temp; temp = swap; } } } int[] cnt = new int[p]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] != '.' && map[i][j] != '#') cnt[(map[i][j] - '1')]++; } } for (int i = 0; i < p; i++) { out.print(cnt[i] + " "); } out.println(); } class Point { int r; int c; public Point(int r, int c) { this.r = r; this.c = c; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } public int[] na(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = ni(); } return ret; } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
34257dd95d69553ccc27718bdf955ef2
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces1105D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] s = new int[p]; for (int i = 0; i < p; i++) { s[i] = Integer.parseInt(st.nextToken()); } //keeps track of the places we have visited int[][] BFS = new int[p][n*m]; int[] BFSleft = new int[p]; int[] BFSright = new int[p]; int notdone = p; //bool keeps track of which places have been taken or can't be reached boolean[][] bool = new boolean[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); String str = st.nextToken(); for (int j = 0; j < m; j++) { char k = str.charAt(j); if (k == '#') { bool[i][j] = true; } else if (k != '.') { int pos = (int) k - 49; BFS[pos][BFSright[pos]] = m*i+j; bool[i][j] = true; BFSright[pos]++; } } } int loc = 0; while (notdone > 0) { if (BFSleft[loc] < BFSright[loc]) { for (int i = 0; (i < s[loc]) && (BFSleft[loc] < BFSright[loc]); i++) { int left = BFSleft[loc]; int right = BFSright[loc]; for (int j = left; j < right; j++) { int a = BFS[loc][j]; int x = a/m; int y = a%m; if ((x > 0) && (!(bool[x-1][y]))) { bool[x-1][y] = true; BFS[loc][BFSright[loc]] = a-m; BFSright[loc]++; } if ((x < (n-1)) && (!(bool[x+1][y]))) { bool[x+1][y] = true; BFS[loc][BFSright[loc]] = a+m; BFSright[loc]++; } if ((y > 0) && (!(bool[x][y-1]))) { bool[x][y-1] = true; BFS[loc][BFSright[loc]] = a-1; BFSright[loc]++; } if ((y < (m-1)) && (!(bool[x][y+1]))) { bool[x][y+1] = true; BFS[loc][BFSright[loc]] = a+1; BFSright[loc]++; } } BFSleft[loc] = right; } if (BFSleft[loc] == BFSright[loc]) { notdone--; } } loc = (loc+1)%p; } for (int i = 0; i < p; i++) { System.out.print(BFSright[i] + " "); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
49046bf3153a15c4a139b675d094788a
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Abhas Jain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int p = in.ni(); char[][] ar = new char[n + 2][m + 2]; ArrayList<Pair>[] str = new ArrayList[p]; for (int i = 0; i < p; ++i) str[i] = new ArrayList<>(); int[] speed = new int[p]; for (int i = 0; i < p; ++i) speed[i] = in.ni(); for (int i = 1; i <= n; ++i) { String curr = in.next(); for (int j = 1; j <= m; ++j) { ar[i][j] = curr.charAt(j - 1); if (ar[i][j] >= '1' && ar[i][j] <= '9') { str[Character.getNumericValue(ar[i][j]) - 1].add(new Pair(i, j)); } } } int[][] ans = new int[n + 2][m + 2]; for (int i = 0; i < n + 2; ++i) { for (int j = 0; j < m + 2; ++j) { ans[i][j] = Integer.MAX_VALUE; } } int[] pr = new int[p]; PriorityQueue<Game> pq = new PriorityQueue<>(new Comparator<Game>() { public int compare(Game o1, Game o2) { if (o1.chance != o2.chance) return Integer.compare(o1.chance, o2.chance); if (o1.p != o2.p) return Integer.compare(o1.p, o2.p); return Integer.compare(o2.rem, o1.rem); } }); for (int i = 0; i < p; ++i) { for (Pair g : str[i]) { pq.add(new Game(g.F, g.S, 0, speed[i], i)); } } // while (!pq.isEmpty()) { Game lol = pq.poll(); int i = lol.i; int j = lol.j; if (lol.rem == 0) { pq.add(new Game(i, j, lol.chance + 1, speed[lol.p], lol.p)); continue; } if (ar[i + 1][j] == '.') { pq.add(new Game(i + 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i + 1][j] = '#'; } if (ar[i - 1][j] == '.') { pq.add(new Game(i - 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i - 1][j] = '#'; } if (ar[i][j + 1] == '.') { pq.add(new Game(i, j + 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j + 1] = '#'; } if (ar[i][j - 1] == '.') { pq.add(new Game(i, j - 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j - 1] = '#'; } } for (int i = 0; i < p; ++i) { out.print((pr[i] + str[i].size()) + " "); } } public class Game { int i; int j; int chance; int rem; int p; public Game(int i, int j, int chance, int rem, int p) { this.i = i; this.j = j; this.chance = chance; this.rem = rem; this.p = p; } } public class Pair { int F; int S; public Pair(int f, int s) { F = f; S = s; } } } 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 ni() { return Integer.parseInt(next()); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
cbf8a02d7da5645082b1b29fbbfb18c5
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Abhas Jain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int p = in.ni(); char[][] ar = new char[n + 2][m + 2]; ArrayList<Pair>[] str = new ArrayList[p]; for (int i = 0; i < p; ++i) str[i] = new ArrayList<>(); int[] speed = new int[p]; for (int i = 0; i < p; ++i) speed[i] = in.ni(); for (int i = 1; i <= n; ++i) { String curr = in.next(); for (int j = 1; j <= m; ++j) { ar[i][j] = curr.charAt(j - 1); if (ar[i][j] >= '1' && ar[i][j] <= '9') { str[Character.getNumericValue(ar[i][j]) - 1].add(new Pair(i, j)); } } } int[][] ans = new int[n + 2][m + 2]; for (int i = 0; i < n + 2; ++i) { for (int j = 0; j < m + 2; ++j) { ans[i][j] = Integer.MAX_VALUE; } } int[] pr = new int[p]; PriorityQueue<Game> pq = new PriorityQueue<>(new Comparator<Game>() { public int compare(Game o1, Game o2) { if (o1.chance != o2.chance) return Integer.compare(o1.chance, o2.chance); if (o1.p != o2.p) return Integer.compare(o1.p, o2.p); return Integer.compare(o2.rem, o1.rem); } }); for (int i = 0; i < p; ++i) { for (Pair g : str[i]) { pq.add(new Game(g.F, g.S, 0, speed[i], i)); } } while (!pq.isEmpty()) { Game lol = pq.poll(); int i = lol.i; int j = lol.j; if (lol.rem == 0) { pq.add(new Game(i, j, lol.chance + 1, speed[lol.p], lol.p)); continue; } if (ar[i + 1][j] == '.') { pq.add(new Game(i + 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i + 1][j] = '#'; } if (ar[i - 1][j] == '.') { pq.add(new Game(i - 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i - 1][j] = '#'; } if (ar[i][j + 1] == '.') { pq.add(new Game(i, j + 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j + 1] = '#'; } if (ar[i][j - 1] == '.') { pq.add(new Game(i, j - 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j - 1] = '#'; } } for (int i = 0; i < p; ++i) { out.print((pr[i] + str[i].size()) + " "); } } public class Game { int i; int j; int chance; int rem; int p; public Game(int i, int j, int chance, int rem, int p) { this.i = i; this.j = j; this.chance = chance; this.rem = rem; this.p = p; } } public class Pair { int F; int S; public Pair(int f, int s) { F = f; S = s; } } } 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 ni() { return Integer.parseInt(next()); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
45fa2d6a2a91e45a95008bbd0b1a6cab
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Abhas Jain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int p = in.ni(); char[][] ar = new char[n + 2][m + 2]; ArrayList<Pair>[] str = new ArrayList[p]; for (int i = 0; i < p; ++i) str[i] = new ArrayList<>(); int[] speed = new int[p]; for (int i = 0; i < p; ++i) speed[i] = in.ni(); for (int i = 1; i <= n; ++i) { String curr = in.next(); for (int j = 1; j <= m; ++j) { ar[i][j] = curr.charAt(j - 1); if (ar[i][j] >= '1' && ar[i][j] <= '9') { str[Character.getNumericValue(ar[i][j]) - 1].add(new Pair(i, j)); } } } int[][] ans = new int[n + 2][m + 2]; for (int i = 0; i < n + 2; ++i) { for (int j = 0; j < m + 2; ++j) { ans[i][j] = Integer.MAX_VALUE; } } int[] pr = new int[p]; PriorityQueue<Game> pq = new PriorityQueue<>(new Comparator<Game>() { public int compare(Game o1, Game o2) { if (o1.chance != o2.chance) return Integer.compare(o1.chance, o2.chance); if (o1.p != o2.p) return Integer.compare(o1.p, o2.p); return Integer.compare(o2.rem, o1.rem); } }); for (int i = 0; i < p; ++i) { for (Pair g : str[i]) { pq.add(new Game((int) g.F, (int) g.S, 0, speed[i], i)); } } while (!pq.isEmpty()) { Game lol = pq.poll(); int i = lol.i; int j = lol.j; if (lol.rem == 0) { pq.add(new Game(i, j, lol.chance + 1, speed[lol.p], lol.p)); continue; } if (ar[i + 1][j] == '.') { pq.add(new Game(i + 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i + 1][j] = '#'; } if (ar[i - 1][j] == '.') { pq.add(new Game(i - 1, j, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i - 1][j] = '#'; } if (ar[i][j + 1] == '.') { pq.add(new Game(i, j + 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j + 1] = '#'; } if (ar[i][j - 1] == '.') { pq.add(new Game(i, j - 1, lol.chance, lol.rem - 1, lol.p)); pr[lol.p]++; ar[i][j - 1] = '#'; } } for (int i = 0; i < p; ++i) { out.print((pr[i] + str[i].size()) + " "); } } public class Game { int i; int j; int chance; int rem; int p; public Game(int i, int j, int chance, int rem, int p) { this.i = i; this.j = j; this.chance = chance; this.rem = rem; this.p = p; } } public class Pair { Object F; Object S; public Pair(Object f, Object s) { F = f; S = s; } } } 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 ni() { return Integer.parseInt(next()); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
11b419b7fa2d278a6b7a9a97108ecdf6
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable{ FastScanner sc; PrintWriter pw; final class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public long nlo() { return Long.parseLong(next()); } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int ni() { return Integer.parseInt(next()); } public String nli() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nd() { return Double.parseDouble(next()); } } public static void main(String[] args) { new Thread(null,new Main(),"codeforces",1<<26).start(); } public void run() { sc=new FastScanner(); pw=new PrintWriter(System.out); solve(); pw.flush(); pw.close(); } public long gcd(long a,long b) { return b==0L?a:gcd(b,a%b); } public long ppow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } public int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } ////////////////////////////////// ///////////// LOGIC /////////// //////////////////////////////// public class Node implements Comparable<Node>{ int x; int y; Node(int a,int b) { x=a; y=b; } public int compareTo(Node b) {return 1;} } public void solve() { int n=sc.ni(); int m=sc.ni(); int p=sc.ni(); int[] prr=new int[p]; char[][] arr=new char[n][]; for(int i=0;i<p;i++) prr[i]=sc.ni(); HashSet<Node>[] set=new HashSet[p]; for(int i=0;i<p;i++) set[i]=new HashSet(); for(int i=0;i<n;i++){ arr[i]=sc.next().toCharArray(); } for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(arr[i][j]>='1'&&arr[i][j]<=p+'0') if(f(arr,i,j,set)) set[arr[i][j]-'1'].add(new Node(i,j)); long t=0; for(int i=0;i<p;i++) t+=set[i].size(); int I=0; while(t>0) { for(int j=0;j<prr[I];j++) { ArrayList<Node> l1=new ArrayList(); ArrayList<Node> l2=new ArrayList(); for(Node P:set[I]) { l2.addAll(dop(P,set,arr)); l1.add(P); } for(Node P:l1) set[I].remove(P); for(Node P:l2) set[I].add(P); t-=l1.size(); t+=l2.size(); if(t==0||set[I].size()==0) break; } I=(I+1)%p; } int[] frr=new int[p]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++){//pw.print(arr[i][j]+" "); if(arr[i][j]>'0'&&arr[i][j]<=('0'+p)) frr[arr[i][j]-'1']++;} // pw.println(""); } for(int i=0;i<p;i++) pw.print(frr[i]+" "); } public boolean f(char[][] arr,int i,int j,HashSet<Node>[] set) { if(i+1<arr.length&&arr[i+1][j]=='.') return true; else if(j+1<arr[0].length&&arr[i][j+1]=='.') return true; else if(i-1>=0&&arr[i-1][j]=='.') return true; else if(j-1>=0&&arr[i][j-1]=='.') return true; return false; } public ArrayList<Node> dop(Node p,HashSet<Node>[] set,char[][] arr) { int i=p.x; int j=p.y; ArrayList<Node> list=new ArrayList(); if(i+1<arr.length&&arr[i+1][j]=='.') { arr[i+1][j]=arr[i][j]; if(f(arr,i+1,j,set)) list.add(new Node(i+1,j)); } if(j+1<arr[0].length&&arr[i][j+1]=='.') { arr[i][j+1]=arr[i][j]; if(f(arr,i,j+1,set)) list.add(new Node(i,j+1)); } if(i-1>=0&&arr[i-1][j]=='.') { arr[i-1][j]=arr[i][j]; if(f(arr,i-1,j,set)) list.add(new Node(i-1,j)); } if(j-1>=0&&arr[i][j-1]=='.') { arr[i][j-1]=arr[i][j]; if(f(arr,i,j-1,set)) list.add(new Node(i,j-1)); } return list; } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
f4a6738f5161b3430a72f36155afb3da
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; public class Solution{ static InputReader sc; static PrintWriter wc; static int arr[][],n,m; static Queue<Pair>[] q; static int steps[]; static void bfs(int player){ Queue<Pair> qq=new LinkedList<>(); while(q[player].size()>0) qq.add(q[player].remove()); while(qq.size()>0){ Pair p=qq.remove(); if(p.left==0){ q[player].add(new Pair(p.x,p.y,steps[player],player)); continue; } if(p.x>=1&&arr[p.x-1][p.y]==0){ arr[p.x-1][p.y]=player; qq.add(new Pair(p.x-1,p.y,p.left-1,player)); } if(p.x+1<n&&arr[p.x+1][p.y]==0){ arr[p.x+1][p.y]=player; qq.add(new Pair(p.x+1,p.y,p.left-1,player)); } if(p.y>=1&&arr[p.x][p.y-1]==0){ arr[p.x][p.y-1]=player; qq.add(new Pair(p.x,p.y-1,p.left-1,player)); } if(p.y+1<m&&arr[p.x][p.y+1]==0){ arr[p.x][p.y+1]=player; qq.add(new Pair(p.x,p.y+1,p.left-1,player)); } } } public static void main(String[] args) { sc=new InputReader(System.in); wc=new PrintWriter(System.out); n=sc.nextInt(); m=sc.nextInt(); arr=new int[n][m]; int p=sc.nextInt(); steps=new int[p+1]; q=new Queue[p+1]; int i; for(i=0;i<p;i++){ steps[i+1]=sc.nextInt(); q[i+1]=new LinkedList<Pair>(); } int j; String s; for(i=0;i<n;i++){ s=sc.next(); for(j=0;j<m;j++){ if(s.charAt(j)=='#') arr[i][j]=-1; else{ if(s.charAt(j)!='.'){ arr[i][j]=Integer.parseInt(s.charAt(j)+""); q[arr[i][j]].add(new Pair(i,j,steps[arr[i][j]],arr[i][j])); } } } } int empty[]=new int[p+1]; while(true){ for(i=1;i<=p;i++){ if(q[i].size()>0){ bfs(i); } else{ empty[i]=1; } } int brk=1; for(i=1;i<=p;i++){ if(empty[i]==0) brk=0; } if(brk==1) break; } int res[]=new int[p+1]; for(i=0;i<n;i++){ for(j=0;j<m;j++){ if(arr[i][j]>0){ res[arr[i][j]]++; } } } for(i=1;i<=p;i++){ wc.print(res[i]+" "); } wc.println(); wc.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } } class Pair{ int x,y,left,player; Pair(int x,int y,int left,int player){ this.x=x; this.y=y; this.left=left; this.player=player; } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
f2d48efb07db0d393baa80a468a47bc3
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; public class D { public static void main(String[]args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(), m=sc.nextInt(), p=sc.nextInt(); int[]s=new int[p]; for(int i=0;i<p;i++) s[i]=sc.nextInt(); sc.nextLine(); char[][]grid=new char[n][m]; for(int i=0;i<n;i++) grid[i]=sc.nextLine().toCharArray(); sc.close(); HashMap<Integer,HashMap<Integer,HashSet<Integer>>>castles=new HashMap<Integer,HashMap<Integer,HashSet<Integer>>>(); for(int i=0;i<p;i++){ castles.put(i,new HashMap<Integer,HashSet<Integer>>()); for(int r=0;r<n;r++) for(int c=0;c<m;c++) if(grid[r][c]==i+49) add(castles.get(i),i,r,c,grid); } HashSet<Integer>stuck=new HashSet<Integer>(); while(stuck.size()<p) for(int i=0;i<p;i++){ if(!stuck.contains(i)){ for(int q=0;q<s[i];q++){ HashMap<Integer,HashSet<Integer>>temp=new HashMap<Integer,HashSet<Integer>>(); for(int r:castles.get(i).keySet()){ for(int c:castles.get(i).get(r)) addNeighbors(grid,r,c,i,temp); } castles.put(i, temp); if(castles.get(i).isEmpty()) break; } if(castles.get(i).keySet().isEmpty()) stuck.add(i); } } int[]controlled=new int[p]; for(int r=0;r<n;r++) for(int c=0;c<m;c++) if(grid[r][c]>48&&grid[r][c]<58) controlled[grid[r][c]-49]++; for(int i:controlled) System.out.print(i+" "); } public static void addNeighbors(char[][]grid,int r,int c,int p,HashMap<Integer,HashSet<Integer>>ca){ if(r>0&&grid[r-1][c]=='.') add(ca,p,r-1,c,grid); if(r+1<grid.length&&grid[r+1][c]=='.') add(ca,p,r+1,c,grid); if(c>0&&grid[r][c-1]=='.') add(ca,p,r,c-1,grid); if(c+1<grid[0].length&&grid[r][c+1]=='.') add(ca,p,r,c+1,grid); } public static void add(HashMap<Integer,HashSet<Integer>>ca,int p,int r,int c,char[][]grid){ if(!ca.containsKey(r)) ca.put(r, new HashSet<Integer>()); ca.get(r).add(c); grid[r][c]=(char)(p+49); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
59f34ce97a91dab50aa9df7978863336
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Queue; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { static final int MAXA = (int) 1e3 + 10; String[] a = new String[MAXA]; int[] s = new int[MAXA]; Queue<Integer[]> q = new LinkedList<>(); ArrayList<Queue<Integer[]>> re = new ArrayList<>(11); int[][] ch = new int[MAXA][MAXA]; int[] dx = {-1, 1, 0, 0}; int[] dy = {0, 0, -1, 1}; int n; int m; int p; int[] cnt = new int[MAXA]; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); p = in.nextInt(); for (int i = 1; i <= p; i++) { s[i] = in.nextInt(); } for (int i = 0; i <= 10; i++) { Queue<Integer[]> tmp = new LinkedList<>(); re.add(tmp); } for (int i = 1; i <= n; i++) { a[i] = "#" + in.next(); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i].charAt(j) != '.' && a[i].charAt(j) != '#') { int l = a[i].charAt(j) - '0'; ch[i][j] = l; re.get(l).add(new Integer[]{l, i, j, 1}); } if (a[i].charAt(j) == '#') { ch[i][j] = 99; } } } while (true) { int cur = check(); if (cur == 0) break; for (cur = 1; cur <= p; cur++) { while (!re.get(cur).isEmpty()) { q.add(re.get(cur).remove()); } while (!q.isEmpty()) { Integer[] tmp = q.remove(); int x = tmp[1]; int y = tmp[2]; int dis = tmp[3]; for (int l = 0; l < 4; l++) { int xx = x + dx[l]; int yy = y + dy[l]; if (ok(xx, yy)) { ch[xx][yy] = tmp[0]; if (dis < s[tmp[0]]) { q.add(new Integer[]{cur, xx, yy, dis + 1}); } else if (dis == s[tmp[0]]) { re.get(cur).add(new Integer[]{cur, xx, yy, 1}); } } } } // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // out.print(ch[i][j] + " "); // } // out.println(""); // } // out.println(""); } } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cnt[ch[i][j]]++; for (int i = 1; i <= p; i++) out.print(cnt[i] + " "); } private int check() { for (int i = 1; i <= p; i++) { if (!re.get(i).isEmpty()) return i; } return 0; } private boolean ok(int i, int j) { return i >= 1 && j >= 1 && i <= n && j <= m && ch[i][j] <= 0; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
332cc4fc1449fdfe939331fa35da0b30
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; public class B{ public static void main(String[] args) throws IOException { Scanner sc=new Scanner(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(),p=sc.nextInt(); int []s=new int [p]; Queue<int []>[]cells=new Queue[p]; int []ans=new int [p]; for(int i=0;i<p;i++) { s[i]=sc.nextInt(); cells[i]=new LinkedList(); } char [][]grid=new char [n][m]; for(int i=0;i<n;i++) { grid[i]=sc.next().toCharArray(); for(int j=0;j<m;j++) if(grid[i][j]>='0' && grid[i][j]<='9') { int idx=grid[i][j]-'0'-1; cells[idx].add(new int [] {i,j,0}); ans[idx]++; } } int []di= {1,-1,0,0}; int []dj= {0,0,1,-1}; Queue<int []>tmp=new LinkedList(); while(true) { boolean change=false; for(int player=0;player<p;player++) { // while(!cells[player].isEmpty()) { int []x=cells[player].poll(); int i=x[0],j=x[1],d=x[2]; for(int k=0;k<4;k++) { int i2=i+di[k],j2=j+dj[k]; if(i2>=0 && i2<n && j2>=0 && j2<m && grid[i2][j2]=='.') { grid[i2][j2]='#'; change=true; ans[player]++; if(d+1<s[player]) cells[player].add(new int [] {i2,j2,d+1}); else tmp.add(new int []{i2,j2,0}); } } } while(!tmp.isEmpty()) cells[player].add(tmp.poll()); } if(!change) break; } for(int x:ans) out.println(x); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException{ br=new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException{ return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
69b4771bda9c9d3db0246e6d9f355067
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class B { String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// long INF = Long.MAX_VALUE / 1000; long MODULO = 998244353; int[][] steps = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; private final static Random rnd = new Random(); double eps = 1e-1; class Pair implements Comparable<Pair>{ int val, ind; public Pair(int val, int ind) { this.val = val; this.ind = ind; } @Override public int compareTo(Pair o) { return -Integer.compare(this.val, o.val); } } ArrayList<Integer>[] graph; boolean[] used; int[] dist; boolean flag = true; long[] pows; int l = 20; int[][] color; char[][] grid; void solve() throws IOException { int n = readInt(); int m = readInt(); int p = readInt(); int[] s= readIntArray(p); int[] count = new int[p]; ArrayDeque<Vertex>[] q = new ArrayDeque[p]; for (int i=0; i<p; ++i) q[i] = new ArrayDeque<>(); grid = new char[n][m];; color = new int[n][m]; for (int i=0; i<n; ++i){ grid[i] = readString().toCharArray(); Arrays.fill(color[i], -1); for (int j=0; j<m; ++j){ if (grid[i][j] != '.' && grid[i][j] != '#'){ q[grid[i][j] - '1'].add(new Vertex(i, j, 0, 1)); color[i][j] = grid[i][j] - '1'; } } } int curPlayer = 0; int curMove = 1; ArrayDeque<Vertex> nextQueue = new ArrayDeque<>(); int c = 0; while (c < 100){ if (curPlayer == p){ curMove++; curPlayer = 0; } while (q[curPlayer].size() > 0){ Vertex v = q[curPlayer].poll(); for (int[] step: steps){ int nextI = v.i + step[0]; int nextJ = v.j + step[1]; if (checkCeil(nextI, nextJ, n, m)){ color[nextI][nextJ] = curPlayer; if (v.dist + 1 >= s[curPlayer] * curMove){ nextQueue.addFirst(new Vertex(nextI, nextJ, v.dist + 1, curMove + 1)); c = 0; }else{ q[curPlayer].add(new Vertex(nextI, nextJ, v.dist + 1, curMove)); } } } } while (nextQueue.size() > 0) q[curPlayer].add(nextQueue.pollLast()); curPlayer++; c++; } for (int i=0; i<n; ++i){ for (int j=0; j<m; ++j){ if (color[i][j] != -1) count[color[i][j]]++; } } for (int a: count) out.print(a + " "); } boolean checkCeil(int i, int j, int n, int m){ return i >= 0 && i < n && j >=0 && j < m && color[i][j] == -1 && grid[i][j] != '#'; } class SegmentTree{ long[] t; int n; SegmentTree(long[] arr, int n){ t = new long[n*4]; build(arr, 1, 1, n); } void build(long[] arr, int v, int tl , int tr){ if (tl == tr) { t[v] = arr[tl]; return; } int tm = (tl + tr) / 2; build(arr, 2 * v, tl, tm); build(arr, 2 * v + 1, tm + 1, tr); t[v] = Math.max(t[2*v], t[2*v + 1]); } long get(int v, int tl , int tr, int l , int r){ if (l > r) return -1; if (tl == l && tr == r) return t[v]; int tm = (tl + tr) / 2; long val1 = get(2 * v, tl, tm, l, Math.min(tm, r)); long val2 = get(2 * v + 1, tm + 1, tr, Math.max(tm + 1, l), r); return Math.max(val1, val2); } } void brute(){ int n = 10; int[] arr = new int[n]; int[] b = new int[n]; for (int it=0; it < 100; ++it){ for (int i=0; i< n; ++i) { arr[i] = rnd.nextInt(100); b[i] = arr[i]; } Arrays.sort(b); for (int k=0; k<n; ++k){ int ans = orderStatistic(arr, k, 0, n-1); if (ans != b[k]) { out.println("HACK!!!"); out.println(n +" " + (k+1)); for (int i: arr) out.print(i +" "); out.println(); out.println(b[k] + " " + ans); } } } } int orderStatistic(int[] arr, int k, int l , int r){ int part = partition(arr, l , r); if (part == k) return arr[part]; if (part > k) return orderStatistic(arr, k, l, part); return orderStatistic(arr, k, part, r); } int partition(int[] arr, int l, int r){ int i = l; int j = r; if (i == j) return i; int pivot = arr[l + rnd.nextInt(r - l)]; while (true){ while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (j <= i) return j; int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; j--; i++; } } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } class Fenwik { int[] t; int n; Fenwik(int n){ t = new int[n]; this.n = n; } void inc(int r, int delta){ for (; r < n; r = r | (r + 1)) t[r] += delta; } int getSum(int r){ int res = 0; for (; r >=0; r = (r & (r + 1) ) - 1) res += t[r]; return res; } } boolean isPrime(int n){ for (int i=2; i*i<=n; ++i){ if (n%i==0) return false; } return true; } class Number implements Comparable<Number>{ int x, cost; Number(int x, int cost){ this.x = x; this.cost = cost; } @Override public int compareTo(Number o) { return Integer.compare(this.cost, o.cost); } } /////////////////////////////////////////////////////////////////////////////////////////// class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ 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] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } class Edge{ int to, dist; public Edge(int to, int dist) { this.to = to; this.dist = dist; } } class Vertex{ int i, j, dist, move; public Vertex(int i, int j, int dist, int move) { this.i = i; this.j = j; this.dist = dist; this.move = move; } } //////////////////////////////////////////////////////////// int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } double binPow(double a, int pow){ if (pow == 0) return 1; if (pow % 2 == 1) { return a * binPow(a, pow - 1); } else { double c = binPow(a, pow / 2); return c * c; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new B().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; B() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } int[] readIntArrayWithDecrease (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt() - 1; } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
080c724c7ead8fe6148b3c63a2f705f5
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
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.util.ArrayDeque; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); int[] s = new int[p + 1]; for (int i = 1; i <= p; i++) { s[i] = in.nextInt(); } char[][] field = new char[n][]; int[][] fieldRes = new int[n][m]; player[] players = new player[p + 1]; for (int i = 1; i <= p; i++) { players[i] = new player(i, s[i]); } for (int i = 0; i < n; i++) { field[i] = in.next().toCharArray(); for (int j = 0; j < m; j++) { if (field[i][j] == '.') { fieldRes[i][j] = 0; } else if (field[i][j] == '#') { fieldRes[i][j] = -1; } else { fieldRes[i][j] = field[i][j] - '0'; players[field[i][j] - '0'].set(j, i); } } } boolean play = true; while (play) { play = false; for (int i = 1; i <= p; i++) { if (players[i].play(fieldRes) > 0) { play = true; } } } out.println(ans(fieldRes, p)); } String ans(int[][] steps, int len) { int n = steps.length, m = steps[0].length; int[] ans = new int[len + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (steps[i][j] >= 0) { ans[steps[i][j]]++; } } } StringBuilder res = new StringBuilder(); for (int i = 1; i <= len; i++) { res.append(ans[i]); res.append(" "); } res.setLength(res.length() - 1); return res.toString(); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class player { private ArrayDeque<Integer> xQlast = new ArrayDeque<>(); private ArrayDeque<Integer> yQlast = new ArrayDeque<>(); private ArrayDeque<Integer> stepCntQlast = new ArrayDeque<>(); private ArrayDeque<Integer> xQ; private ArrayDeque<Integer> yQ; private ArrayDeque<Integer> stepCntQ; private int numb; private int speed; player(int n, int s) { numb = n; speed = s; } void set(int x, int y) { xQlast.addLast(x); yQlast.addLast(y); stepCntQlast.addLast(speed); } int play(int[][] field) { int steps = 0; xQ = xQlast; xQlast = new ArrayDeque<>(); yQ = yQlast; yQlast = new ArrayDeque<>(); stepCntQ = stepCntQlast; stepCntQlast = new ArrayDeque<>(); while (!xQ.isEmpty()) { int curX = xQ.removeFirst(); int curY = yQ.removeFirst(); int stepCnt = stepCntQ.removeFirst(); if (stepCnt == 0) { xQlast.addLast(curX); yQlast.addLast(curY); stepCntQlast.addLast(speed); continue; } if (curX > 0 && field[curY][curX - 1] == 0) { field[curY][curX - 1] = numb; xQ.addLast(curX - 1); yQ.addLast(curY); stepCntQ.addLast(stepCnt - 1); steps++; } if (curY > 0 && field[curY - 1][curX] == 0) { field[curY - 1][curX] = numb; xQ.addLast(curX); yQ.addLast(curY - 1); stepCntQ.addLast(stepCnt - 1); steps++; } if (curX < field[0].length - 1 && field[curY][curX + 1] == 0) { field[curY][curX + 1] = numb; xQ.addLast(curX + 1); yQ.addLast(curY); stepCntQ.addLast(stepCnt - 1); steps++; } if (curY < field.length - 1 && field[curY + 1][curX] == 0) { field[curY + 1][curX] = numb; xQ.addLast(curX); yQ.addLast(curY + 1); stepCntQ.addLast(stepCnt - 1); steps++; } } return steps; } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
6b2b3cb96d0041af33861ebc82df6a4d
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; public class KilaniGameJava { static final int BLOCKED = -1; static final int EMPTY = 0; static final int[] dx = {1, 0, 0, -1}; static final int[] dy = {0, 1, -1, 0}; static class Field { int x; int y; int status; int distance; Field(int i, int j, char entity) { this.x = i; this.y = j; this.distance = 0; switch (entity) { case '#': this.status = BLOCKED; break; case '.': this.status = EMPTY; break; default: this.status = entity - '0'; players.get(status - 1).castles.add(this); } } public boolean isFree() { return status == EMPTY; } } private static class Player { private int id; private int maxDistance; private Queue<Field> castles; public Player(int id, int maxDistance) { this(id); this.maxDistance = maxDistance; this.castles = new LinkedList<>(); } public Player(int id) { this.id = id; } private void addCastle(Field castle, int distance) { castle.status = id; castle.distance = distance; castles.add(castle); } } private static class Board { int rows; int cols; List<List<Field>> fields; public Board(int rows, int cols) { this.rows = rows; this.cols = cols; this.fields = new ArrayList<>(); } private void build() throws IOException { for (int i = 0; i < rows; i++) { fields.add(buildRow(i)); } } private List<Field> buildRow(int i) throws IOException { List<Field> row = new ArrayList<>(); char[] entities = next().toCharArray(); for (int j = 0; j < cols; j++) { row.add(new Field(i, j, entities[j])); } return row; } private boolean containsField(int i, int j) { return i >= 0 && i < rows && j >= 0 && j < cols; } private Field getField(int i, int j) { return fields.get(i).get(j); } } private static void playGame() { boolean isGame = true; while(isGame) { for (Player player : players) { for (Field castle : player.castles) { castle.distance = 0; } Queue<Field> newCastles = new LinkedList<>(); while (!player.castles.isEmpty()) { Field castle = player.castles.poll(); if (castle.distance == player.maxDistance) { newCastles.add(castle); continue; } for (int j = 0; j < 4; j++) { int x = castle.x + dx[j]; int y = castle.y + dy[j]; if (board.containsField(x, y) && board.getField(x, y).isFree()) { player.addCastle(board.getField(x, y), castle.distance + 1); } } } player.castles = newCastles; } isGame = false; for (Player player : players) { if (!player.castles.isEmpty()) { isGame = true; } } } } private static void writeGameResult() { int[] result = new int[players.size() + 1]; for (List<Field> fields : board.fields) { for (Field field : fields) { if (field.status != BLOCKED) { result[field.status]++; } } } for (int i = 1; i <= players.size(); i++) { System.out.print(result[i] + " "); } } private static Board board; private static List<Player> players = new ArrayList<>(); private static StringTokenizer st; private static BufferedReader br; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); int p = nextInt(); for (int i = 1; i < p + 1; i++) { players.add(new Player(i, nextInt())); } board = new Board(n, m); board.build(); playGame(); writeGameResult(); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
0316ef76d05d429b5c92a40fe6819155
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; public class B { // DO IN C++ static int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}}; public static void main(String...args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int[] speed = new int[p]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < p; i++){ speed[i] = Integer.parseInt(st.nextToken()); } char[][] map = new char[n][m]; ArrayList<Coor>[] q = new ArrayList[p]; for(int i = 0; i < p; i++) q[i] = new ArrayList<>(); for(int i = 0; i < n; i++){ map[i] = br.readLine().toCharArray(); for(int j = 0; j < m; j++){ if(map[i][j] >= '0' && map[i][j] <= '9'){ q[map[i][j]-'0'-1].add(new Coor(i,j)); } } } //bfs boolean[] cancontinue = new boolean[p]; Arrays.fill(cancontinue, true); int ps = p; int turn = 0; //int[] qfrom = new int[p]; while(ps > 0){ while(!cancontinue[turn]) { turn = (turn + 1) % p; } for(int t = 0; t < speed[turn]; t++){ ArrayList<Coor> next = new ArrayList<>(); for(int qp = 0; qp < q[turn].size(); qp++){ Coor c = q[turn].get(qp); for(int[] d: dir){ int x = c.x + d[0], y = c.y + d[1]; if(x >= 0 && y >= 0 && x < n && y < m && map[x][y] == '.'){ map[x][y] = (char)(turn + '0'+1); next.add(new Coor(x, y)); } } } if(next.isEmpty()){ cancontinue[turn] = false; ps--; break; } q[turn] = next; } turn = (turn + 1) % p; } int[] res = new int[p]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] != '.' && map[i][j] != '#'){ int d = (map[i][j]-1 - '0'); res[d]++; } } } StringBuilder sb = new StringBuilder(); for(int r: res){ sb.append(r+" "); } System.out.println(sb.toString().trim()); } public static class Coor{ int x, y; public Coor(int x, int y){ this.x = x; this.y = y; } public String toString(){ return x+","+y; } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
38c59d028a60e30e10098cdf28f4b486
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Gymaya { static int[] pl; static char[][] g; static Queue<node>[]pp; static boolean[][]vis; static int[][]dis; static int[] dx={0,0,1,-1},dy={1,-1,0,0}; static void bfs(Queue<node>q,int speed){ for (node x:q){ dis[x.x][x.y]=0; } while (!q.isEmpty()) { node x= q.poll(); for (int i = 0; i < 4; i++) { int xx = x.x + dx[i]; int yy = x.y + dy[i]; if (xx >= 0 && xx < vis.length && yy >= 0 && yy < vis[0].length && !vis[xx][yy]) { vis[xx][yy] = true; dis[xx][yy]=1+dis[x.x][x.y]; if (dis[xx][yy]<speed) { q.add(new node(xx, yy, x.p)); pp[x.p].add(new node(xx, yy, x.p)); }else { if (dis[xx][yy]==speed) pp[x.p].add(new node(xx, yy, x.p)); } } } } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int p = sc.nextInt(); pl = new int[p + 1]; g = new char[n][m]; dis= new int[n][m]; node[] start = new node[p + 1]; int[] speed = new int[p + 1]; for (int i = 1; i <= p; i++) speed[i] = sc.nextInt(); pp= new Queue[p+1]; for (int i = 1; i <= p; i++) { pp[i]= new LinkedList<>(); } vis = new boolean[n][m]; for (int i = 0; i < n; i++) { g[i] = sc.nextLine().toCharArray(); for (int j = 0; j < m; j++) { if (g[i][j] == '#') vis[i][j] = true; else if (g[i][j] != '.') { vis[i][j] = true; pp[g[i][j]-'0'].add(new node(i, j, g[i][j] - '0')); } } } int c=0; for (int i =1;;i++) { if (i==p+1){ i=1; c=0; } Queue<node>qq= new LinkedList<>(); pl[i]+=pp[i].size(); while (!pp[i].isEmpty())qq.add(pp[i].poll()); if (qq.isEmpty())c++; bfs(qq,speed[i]); if (c==p)break; // System.err.println(i); } for (int i = 1; i <= p; i++) { pw.print(pl[i] + " "); } pw.println(); pw.flush(); } static class node { int x, y, p; node(int a, int b, int c) { x = a; y = b; p = c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
3847bb90df528265eee7f10abab24917
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class MainS { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; static int dx[] = new int[]{0,0,1,-1}; static int dy[] = new int[]{1,-1,0,0}; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int n,m,p,s[]; static char c[][]; static LinkedList<Integer> queuex[], queuey[]; static int mindis[][]; static long iter = 0; static void magic() throws IOException{ reader = new FastReader(); writer = new PrintWriter(System.out, true); n = reader.nextInt(); m = reader.nextInt(); p = reader.nextInt(); s = new int[p+1]; queuex = new LinkedList[p+1]; queuey = new LinkedList[p+1]; mindis = new int[n][m]; for(int i=0;i<p;++i) { s[i+1] = reader.nextInt(); queuex[i+1] = new LinkedList<>(); queuey[i+1] = new LinkedList<>(); } for(int i=0;i<n;++i) { Arrays.fill(mindis[i], -1); } c = new char[n][m]; for(int i=0;i<n;++i) { c[i] = reader.next().toCharArray(); for(int j=0;j<m;++j) { if(c[i][j]=='.' || c[i][j]=='#') { continue; } int player = c[i][j] - '0'; queuex[player].add(i); queuey[player].add(j); mindis[i][j] = 0; } } while(true) { iter++; int cnt = 0; for(int i=1;i<=p;++i) { if(expand(i)) { cnt++; } } if(cnt==0) { break; } } int ans[] = new int[p+1]; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(c[i][j]=='.' || c[i][j]=='#') { continue; } ans[c[i][j]-'0']++; } } for(int i=1;i<=p;++i) { writer.print(ans[i]+" "); } writer.println(); } static boolean expand(int player) { LinkedList<Integer> newqueuex = new LinkedList<>(); LinkedList<Integer> newqueuey = new LinkedList<>(); while(!queuex[player].isEmpty()) { int x = queuex[player].pollFirst(), y = queuey[player].pollFirst(); if(mindis[x][y]==1L * iter * s[player]) { continue; } for(int i=0;i<4;++i) { int nx = x + dx[i]; int ny = y + dy[i]; if(nx>=0 && nx<n && ny>=0 && ny<m && c[nx][ny]=='.') { queuex[player].add(nx); queuey[player].add(ny); newqueuex.add(nx); newqueuey.add(ny); c[nx][ny] = (char)('0' + player); mindis[nx][ny] = 1+mindis[x][y]; } } } int size = newqueuex.size(); while(!newqueuex.isEmpty()) { queuex[player].add(newqueuex.pollFirst()); queuey[player].add(newqueuey.pollFirst()); } return size>0; } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
504e557c87e26998eac6bd938d18f732
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.io.*; //import javafx.util.Pair; public class Main implements Runnable { static class Pair implements Comparable <Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair p) { return Integer.compare(x,p.x); } } public static void main(String[] args) { new Thread(null, new Main(), "rev", 1 << 29).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1,in,out); out.close(); } static class Task { Queue <Pair>q[]; int di[]={0,0,-1,1}; int dj[]={-1,1,0,0}; int [][]dp; int a[],a1[]; int n,m,p,ct=0; boolean isvalid(int i,int j) { return i>=0 && i<n && j>=0 && j<m; } void bfs(int x) { int ct1=0,i,j; Pair p; while(!q[x].isEmpty()) { p=q[x].poll(); i=p.x; j=p.y; if(i==-1) { ct1++; if(q[x].isEmpty()) return; q[x].add(new Pair(-1,-1)); if(ct1==a[x]) return; } for(int k=0;k<4;k++) if(isvalid(i+di[k],j+dj[k]) && dp[i+di[k]][j+dj[k]]==0) { ct++; dp[i+di[k]][j+dj[k]]=x; q[x].add(new Pair(i+di[k],j+dj[k])); } } } void check() { int ct1; while(true) { ct1=0; for(int i=1;i<=p;i++) { if(!q[i].isEmpty()) bfs(i); else ct1++; } if(ct1==p) return; } } void solve(int testNumber, InputReader in, PrintWriter out) { n=in.nextInt(); m=in.nextInt(); p=in.nextInt(); q=new Queue[p+1]; for(int i=1;i<=p;i++) q[i]=new LinkedList<>(); dp=new int[n][m]; a=in.nextIntArray(p+1); a1=new int[p+1]; String s; char ch; for(int i=0;i<n;i++) { s=in.nextString(); for(int j=0;j<m;j++) { ch=s.charAt(j); if(ch=='.') dp[i][j]=0; else if(ch=='#') { dp[i][j]=-1; ct++; } else { dp[i][j]=(int)(ch-'0'); q[dp[i][j]].add(new Pair(i,j)); ct++; } } } for(int i=1;i<=p;i++) q[i].add(new Pair(-1,-1)); Pair p1; check(); /*for(int i=0;i<n;i++) { for(int j=0;j<m;j++) out.print(dp[i][j]+" "); out.println(); }*/ for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(dp[i][j]!=-1) a1[dp[i][j]]++; for(int i=1;i<=p;i++) out.print(a1[i]+" "); } } /*static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for(int i=0;i<objects.length;i++) { if (i!=0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }*/ static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if(snumChars==-1) throw new InputMismatchException(); if(curChar>=snumChars) { curChar=0; try { snumChars = stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(snumChars<=0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while(isSpaceChar(c)) c=snext(); int sgn=1; if(c=='-') { sgn = -1; c = snext(); } int res=0; do { if(c<'0' || c>'9') throw new InputMismatchException(); res*=10; res+=c-'0'; c=snext(); }while(!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while(isSpaceChar(c)) c=snext(); int sgn=1; if(c=='-') { sgn=-1; c=snext(); } long res=0; do{ if (c<'0' || c>'9') throw new InputMismatchException(); res*=10; res+=c-'0'; c=snext(); }while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[]=new int[n]; for(int i=1; i<n; i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) { long a[]=new long[n]; for(int i=1; i<n; i++) a[i]=nextLong(); return a; } public String nextString() { int c=snext(); while(isSpaceChar(c)) c=snext(); StringBuilder res=new StringBuilder(); do{ res.appendCodePoint(c); c = snext(); }while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
930a957231397126d03d25b50c3e0d22
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
/* Code for task B by detestmaths */ import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.System.*; public class Solver { static FastScanner in; static PrintWriter out; static int s[], c[][], n, m, p; static PriorityQueue<id> bfs; static PriorityQueue<id> ids; static void scan() throws IOException { n = in.nextInt(); m = in.nextInt(); bfs = new PriorityQueue<>(new id_comp_par()); ids = new PriorityQueue<>(new id_comp_par()); c = new int[n][m]; p = in.nextInt(); s = new int[p]; for (int i = 0; i < p; i++) s[i] = in.nextInt(); for (int i = 0; i < n; i++) { String ss = in.next(); for (int j = 0; j < m; j++) { if (ss.charAt(j) == '.') c[i][j] = -1; else if (ss.charAt(j) == '#') c[i][j] = -2; else { c[i][j] = ss.charAt(j) - '0' - 1; bfs.add(new id(i, j, 0,c[i][j])); } } } } static void solve() { int x[] = {1, -1, 0, 0}; int y[] = {0, 0, 1, -1}; while (!bfs.isEmpty()) { while (!bfs.isEmpty()) { ids.add(bfs.poll()); } while (!ids.isEmpty()) { id now = ids.poll(); for (int i = 0; i < 4; i++) { if (now.i + x[i] >= 0 && now.i + x[i] < n && now.j + y[i] >= 0 && now.j + y[i] < m){ int i_id = now.i+x[i]; int j_id = now.j + y[i]; if(c[i_id][j_id] != -1)continue; else{ int stps = now.steps; if(stps == s[c[now.i][now.j]])bfs.add(new id(now.i,now.j,0,now.par)); else{ c[i_id][j_id] = c[now.i][now.j]; ids.add(new id(i_id,j_id,stps+1,now.par)); } } } } } } } static void print(){ int ans[] = new int[p]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(c[i][j] < 0)continue; ans[c[i][j]]++; } } for (int i = 0; i < p; i++) { out.print(ans[i] + " "); } out.close(); } public static void main(String[] args) throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out); scan(); solve(); print(); } } class id { int i, j, steps, par; id(int i, int j,int steps, int par) { this.i = i; this.j = j; this.steps = steps; this.par = par; } } class id_comp_par implements Comparator<id> { @Override public int compare(id o1, id o2) { if (Solver.c[o1.i][o1.j] != Solver.c[o2.i][o2.j]) return Integer.compare(Solver.c[o1.i][o1.j], Solver.c[o2.i][o2.j]); if(o1.steps != o2.steps)return Integer.compare(o1.steps,o2.steps); if (o1.i != o2.i) return Integer.compare(o1.i, o2.i); return Integer.compare(o1.j, o2.j); } } class FastScanner { BufferedReader br; StringTokenizer st = new StringTokenizer(""); public FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public FastScanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } public String next() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
b335f67f17244926cc5dbbe7df1af05a
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { void problem() { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); int[] s = new int[p]; for (int i = 0; i < p; i++) { s[i] = in.nextInt(); } int[][] f = new int[n][m]; for (int i = 0; i < n; i++) { String s1 = in.nextToken(); for (int j = 0; j < m; j++) { switch (s1.charAt(j)) { case '.': f[i][j] = 0; break; case '#': f[i][j] = -1; break; default: f[i][j] = s1.charAt(j) - 48; } } } LinkedList<Point>[] q = new LinkedList[p]; for (int i = 0; i < p; i++) { q[i] = new LinkedList(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (f[i][j] > 0) { int id = f[i][j] - 1; if (i > 0) { q[id].addLast(new Point(i - 1, j, 1)); } if (i + 1 < n) { q[id].addLast(new Point(i + 1, j, 1)); } if (j > 0) { q[id].addLast(new Point(i, j - 1, 1)); } if (j + 1 < m) { q[id].addLast(new Point(i, j + 1, 1)); } } } } boolean flag = true; long it = 1; while (flag) { flag = false; for (int id = 0; id < p; id++) { long maxd = it * s[id]; while (!q[id].isEmpty() && q[id].getFirst().d <= maxd) { Point first = q[id].poll(); int i = first.x; int j = first.y; if (f[i][j] == 0) { flag = true; f[i][j] = id + 1; if (i > 0) { q[id].addLast(new Point(i - 1, j, first.d + 1)); } if (i + 1 < n) { q[id].addLast(new Point(i + 1, j, first.d + 1)); } if (j > 0) { q[id].addLast(new Point(i, j - 1, first.d + 1)); } if (j + 1 < m) { q[id].addLast(new Point(i, j + 1, first.d + 1)); } } } } it++; } int[] res = new int[p]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (f[i][j] > 0) { res[f[i][j] - 1]++; } } } for (int i = 0; i < p; i++) { out.print(res[i] + " "); } } class Point { int x; int y; int d; public Point(int x, int y, int d) { this.x = x; this.y = y; this.d = d; } } static int N = 998244353; //static int N = (int) 1e9 + 7; public static long modPower(int x, int y) { if (y == 0) return 1; long z = modPower(x, y / 2); if ((y % 2) == 0) return (z * z) % N; else return (x * z * z) % N; } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); problem(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } // public FastScanner(String s) { // try { // br = new BufferedReader(new FileReader(s)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Main().run(); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
d3a16b41b784d399557131d1f997e874
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.ArrayList; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.OutputStreamWriter; import java.util.LinkedList; import java.io.OutputStream; import java.util.stream.LongStream; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.Objects; import java.util.List; import java.util.stream.Stream; import java.io.Writer; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); DKilaniAndTheGame solver = new DKilaniAndTheGame(); solver.solve(1, in, out); out.close(); } static class DKilaniAndTheGame { private static int n; private static int m; private static int p; private static long[] s; private static String[] b; private static long[] ans; private static boolean[][] searched; private static List<Queue<Vec2i>> q0 = new ArrayList<>(9); private static List<Queue<Vec2i>> q1 = new ArrayList<>(9); public void solve(int testNumber, LightScanner in, LightWriter out) { n = in.ints(); m = in.ints(); p = in.ints(); s = in.longs(p); b = in.string(n); ans = new long[p]; q0.clear(); q1.clear(); for (int i = 0; i < p; i++) { q0.add(null); q1.add(new LinkedList<>()); } searched = new boolean[n][m]; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { char ch = b[y].charAt(x); if (ch == '#') { searched[y][x] = true; } else if (ch != '.') { int pn = ch - '1'; //領有 ans[pn]++; searched[y][x] = true; //次に取れそうなところ GeoWalker.forEach4i(x, y, (nx, ny) -> { if (nx == -1 || ny == -1 || nx == m || ny == n || searched[ny][nx] || b[ny].charAt(nx) != '.') { } else { q1.get(pn).add(new Vec2i(nx, ny)); } }); } } } boolean[] empty = new boolean[p]; int ec = 0; for (int i = 0; ec < p; i++) { if (empty[i % p]) { continue; } else if (q1.get(i % p).isEmpty()) { empty[i % p] = true; ec++; continue; } int w = i % p; q0.set(w, new LinkedList<>()); bfs(w, q1.get(w)); q1.set(w, q0.get(w)); } for (int i = 0; i < p; i++) { out.ans(ans[i]); } out.ln(); } private static void bfs(int w, Queue<Vec2i> initial) { //領有済み -> 諦める Queue<Pair<Long, Vec2i>> q = new LinkedList<>(); while (!initial.isEmpty()) { Vec2i v = initial.poll(); q.add(new Pair<>(1L, new Vec2i(v.x, v.y))); } while (!q.isEmpty()) { Pair<Long, Vec2i> ent = q.poll(); int x = ent.value.x, y = ent.value.y; if (searched[y][x]) { continue; } ans[w]++; searched[y][x] = true; GeoWalker.forEach4i(x, y, (nx, ny) -> { if (nx == -1 || ny == -1 || nx == m || ny == n || searched[ny][nx] || b[ny].charAt(nx) != '.') { } else { if (ent.key == s[w]) { q0.get(w).add(new Vec2i(nx, ny)); } else { q.offer(new Pair<>(ent.key + 1, new Vec2i(nx, ny))); } } }); } } } static class Vec2i { public final int x; public final int y; public Vec2i(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vec2i vec2i = (Vec2i) o; return x == vec2i.x && y == vec2i.y; } public int hashCode() { return 31 * x + y; } public String toString() { return "(" + x + ", " + y + ")"; } } static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(key, pair.key) && Objects.equals(value, pair.value); } public int hashCode() { return Objects.hash(key, value); } public String toString() { return "Pair{" + "x=" + key + ", y=" + value + '}'; } } static interface BiIntConsumer { void accept(int t, int u); } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public String[] string(int length) { return IntStream.range(0, length).mapToObj(x -> string()).toArray(String[]::new); } public int ints() { return Integer.parseInt(string()); } public long longs() { return Long.parseLong(string()); } public long[] longs(int length) { return IntStream.range(0, length).mapToLong(x -> longs()).toArray(); } } static final class GeoWalker { private static final int[] DX = {1, 0, -1, 0, 1, 1, -1, -1}; private static final int[] DY = {0, 1, 0, -1, 1, -1, -1, 1}; private GeoWalker() { } public static void forEach4i(int x, int y, BiIntConsumer receiver) { for (int i = 0; i < 4; i++) { receiver.accept(x + DX[i], y + DY[i]); } } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(long l) { return ans(Long.toString(l)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
e1765d6fe115d4a6098e6965e48644ec
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Queue; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Wolfgang Beyer */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[][] grid; int[] result; int[] speed; int rows; int cols; public void solve(int testNumber, InputReader in, PrintWriter out) { rows = in.nextInt(); cols = in.nextInt(); int p = in.nextInt(); speed = in.readIntArray(p); result = new int[p]; Queue<Coords>[] q = new LinkedList[p]; for (int i = 0; i < p; i++) { q[i] = new LinkedList<>(); } grid = new int[rows][cols]; for (int i = 0; i < rows; i++) { grid[i] = new int[cols]; String s = in.next(); for (int j = 0; j < cols; j++) { char c = s.charAt(j); switch (c) { case '.': grid[i][j] = -1; break; case '#': grid[i][j] = -2; break; default: grid[i][j] = Character.getNumericValue(c) - 1; q[grid[i][j]].add(new Coords(i, j, speed[grid[i][j]])); result[grid[i][j]]++; } } } boolean movesLeft = true; while (movesLeft) { movesLeft = false; for (int pl = 0; pl < p; pl++) { q[pl] = move(pl, q[pl]); if (q[pl].size() > 0) movesLeft = true; } } for (int i = 0; i < p; i++) { out.print(result[i] + " "); } } Queue<Coords> move(int pl, Queue<Coords> q) { Queue<Coords> outQ = new LinkedList<>(); while (q.size() > 0) { Coords coords = q.poll(); if (coords.row > 0) { change(coords.row - 1, coords.col, coords.moves, pl, q, outQ); // if (grid[coords.row - 1][coords.col] == -1) { // grid[coords.row - 1][coords.col] = pl; // result[pl]++; // if (coords.moves > 1) { // q.add(new Coords(coords.row - 1, coords.col, coords.moves - 1)); // } else { // outQ.add(new Coords(coords.row - 1, coords.col, speed[pl])); // } // } } if (coords.row < rows - 1) { change(coords.row + 1, coords.col, coords.moves, pl, q, outQ); } if (coords.col > 0) { change(coords.row, coords.col - 1, coords.moves, pl, q, outQ); } if (coords.col < cols - 1) { change(coords.row, coords.col + 1, coords.moves, pl, q, outQ); } } return outQ; } public void change(int r, int c, int moves, int pl, Queue<Coords> q, Queue<Coords> outQ) { if (grid[r][c] == -1) { grid[r][c] = pl; result[pl]++; if (moves > 1) { q.add(new Coords(r, c, moves - 1)); } else { outQ.add(new Coords(r, c, speed[pl])); } } } class Coords { int row; int col; int moves; public Coords(int r, int c, int m) { row = r; col = c; moves = m; } } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
bc2edd155e9ee8709f50193ef56df08e
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { new Main().work(); } Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); class Node { int x, y, s; Node(int _x, int _y, int _s) { x = _x; y = _y; s = _s; } } int[][] dir = {{1,0}, {-1,0}, {0,-1}, {0,1}}; void work() { int n = in.nextInt(), m = in.nextInt(), p = in.nextInt(); int[] a = new int[p+10]; for(int i = 0; i < p; i++) a[i] = in.nextInt(); char[][] mp = new char[n+10][m+10]; Queue<Node> Q[] = new LinkedList[p+10]; for(int i = 0; i < p; i++) Q[i] = new LinkedList(); for(int i = 0; i < n; i++) { mp[i] = in.next().toCharArray(); for(int j = 0; j < m; j++) if(mp[i][j]!='.' && mp[i][j]!='#') { int t = mp[i][j]-'1'; Q[t].offer(new Node(i, j, a[t])); } } boolean stop = false; while(!stop) { stop = true; for(int i = 0; i < p; i++) { boolean flag = false; while(!Q[i].isEmpty()) { Node t = Q[i].poll(); if(t.s == 0) { flag = true; t.s = a[i]; Q[i].offer(t); continue; } else if(flag) { Q[i].offer(t); break; } for(int j = 0; j < 4; j++) { Node tt = new Node(t.x, t.y, t.s-1); tt.x += dir[j][0]; tt.y += dir[j][1]; if(tt.x >= 0 && tt.x < n && tt.y >= 0 && tt.y < m && mp[tt.x][tt.y] == '.') { stop = false; mp[tt.x][tt.y] = (char)(i+'1'); Q[i].offer(tt); } } } } } int[] ans = new int[p+10]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) if(mp[i][j]!='.' && mp[i][j]!='#') { ans[mp[i][j]-'1']++; } } for(int i = 0; i < p; i++) out.printf("%d%c", ans[i], i==p-1?'\n':' '); out.close(); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
50e650cd231a0c5fc02be3673260ef09
train_003.jsonl
1547985900
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { public static class Pair { int y_pos; int x_pos; int far; public Pair(int y_pos, int x_pos, int far) { this.y_pos = y_pos; this.x_pos = x_pos; this.far = far; } public Pair(int y_pos, int x_pos) { this.y_pos = y_pos; this.x_pos = x_pos; } } static char[][] map; static int n; static int m; static int[] dy = { -1, 1, 0, 0 }; static int[] dx = { 0, 0, -1, 1 }; static Queue<Pair> q = new LinkedList<Pair>(); static Queue<Pair> move_q = new LinkedList<Pair>(); public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); int P = Integer.parseInt(st.nextToken()); map = new char[n][m]; int[] S = new int[P+1]; StringTokenizer st1 = new StringTokenizer(br.readLine()); for (int i = 1; i <= P; i++) { S[i] = Integer.parseInt(st1.nextToken()); } for (int i = 0; i < n; i++) { String s = br.readLine(); for (int j = 0; j < m; j++) { map[i][j] = s.charAt(j); } } for (int p = 1; p <= P; p++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == (p + '0')) q.add(new Pair(i, j)); } } } while (!q.isEmpty()) { Pair t = q.poll(); int ynow = t.y_pos; int xnow = t.x_pos; int player_num = map[ynow][xnow] - '0'; int far = S[player_num]; move_q.add(new Pair(ynow, xnow)); while(!q.isEmpty()) { Pair a = q.peek(); if(map[ynow][xnow] == map[a.y_pos][a.x_pos]) { Pair b = q.poll(); move_q.add(new Pair(b.y_pos, b.x_pos)); } else break; } bfs(ynow, xnow, far, player_num); } int[] players_castle = new int[P+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] >= '1' && map[i][j] <= '9') { players_castle[map[i][j] - '0']++; } } } for (int i = 1; i <= P; i++) { System.out.print(players_castle[i] + " "); } } private static void bfs(int ynow, int xnow, int far, int player_num) { int cnt = far; while(cnt > 0) { int qsize = move_q.size(); if(qsize == 0) return; while (qsize > 0) { Pair p = move_q.poll(); int y_now = p.y_pos; int x_now = p.x_pos; for (int d = 0; d < 4; d++) { int ynext = y_now + dy[d]; int xnext = x_now + dx[d]; if (ynext >= 0 && xnext >= 0 && ynext < n && xnext < m && map[ynext][xnext] == '.') { map[ynext][xnext] = (char) (player_num + '0'); move_q.add(new Pair(ynext, xnext)); if(cnt == 1) { q.add(new Pair(ynext, xnext)); } } } qsize--; } cnt--; } move_q.clear(); } }
Java
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
2 seconds
["6 3", "1 4 3 3"]
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
Java 8
standard input
[ "graphs", "implementation", "dfs and similar", "shortest paths" ]
015d7871f6560b90d9efe3375f91cce7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
1,900
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
standard output
PASSED
c9a10cb56648cb00762be0526fd3eef5
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
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.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.stream.Stream; public class TestClass implements Runnable { static final double time = 1e9; static final int MOD = (int) 1e9 + 7; static final long mh = Long.MAX_VALUE; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new TestClass(), "persefone", 1 << 28).start(); } @Override public void run() { long start = System.nanoTime(); solve(); printf(); long elapsed = System.nanoTime() - start; // out.println("stamp : " + elapsed / time); // out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS)); close(); } void solve() { int[] a = in.next().chars().map(i -> i - 48).toArray(); int n = a.length; int[] f = new int[n]; f[0] = (a[0] % 3 == 0) ? 1 : 0; int[] id = new int[] { -1, -1, -1 }; id[a[0] % 3] = 0; int sum = a[0]; for (int i = 1; i < n; i++) { f[i] = f[i - 1]; sum += a[i]; int x = sum % 3; if (a[i] % 3 == 0 || x == 0 && f[i] == 0) f[i]++; else { int d = id[x]; if (d != -1 && f[d] + 1 > f[i]) f[i] = f[d] + 1; } id[x] = i; } printf(f[n - 1]); } public interface Hash { public void computeHashArray(); public void computeModArray(); } class StringHash implements Hash { // length of string s private final long MH = Long.MAX_VALUE; private int n; private char[] ch; private long[] hash, mod; StringHash(char[] ch) { this.ch = ch; n = ch.length; hash = new long[n + 1]; mod = new long[n + 1]; computeHashArray(); computeModArray(); } StringHash(String s) { this(s.toCharArray()); } StringHash(CharSequence s) { this(s.toString()); } @Override public void computeModArray() { mod[0] = 1; for (int i = 1; i <= n; i++) mod[i] = (mod[i - 1] * 53) % MH; } @Override public void computeHashArray() { for (int i = 0; i < n; i++) hash[i + 1] = (hash[i] * 53 + ch[i] - 'a') % MH; } public long getHash(int i, int j) { return (hash[j] - hash[i] * mod[j - i] + MH * MH) % MH; } public long getHash(String s) { long h = 0; for (int i = 0; i < s.length(); i++) h = (h * 53 + s.charAt(i) - 'a') % MH; return h; } public long[] getHashArray() { return hash; } public long[] getModArray() { return mod; } } public interface Manacher { public void oddPalindrome(); public void evenPalindrome(); } class Palindrome implements Manacher { private int n; private char[] ch; private int[] oddPal, evenPal; public Palindrome() {} public Palindrome(String s) { this(s.toCharArray()); } public Palindrome(char[] ch) { this.ch = ch; n = ch.length; oddPal = new int[ch.length]; evenPal = new int[ch.length]; oddPalindrome(); evenPalindrome(); } @Override public void oddPalindrome() { for (int i = 0, l = 0, r = -1; i < n; i++) { int k = i > r ? 1 : Math.min(oddPal[r + l - i], r - i); while (0 <= i - k && i + k < n && ch[i - k] == ch[i + k]) k++; oddPal[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } } @Override public void evenPalindrome() { for (int i = 0, l = 0, r = -1; i < n; i++) { int k = i > r ? 0 : Math.min(evenPal[r + l - i + 1], r - i + 1); while (0 <= i - k - 1 && i + k < n && ch[i - k - 1] == ch[i + k]) k++; evenPal[i] = k--; if (i + k > r) { l = i - k - 1; r = i + k; } } } } void printf() { out.print(answer); } void close() { out.close(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][])obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][])obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][])obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T min(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) < 0) m = t[i]; return m; } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T max(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) > 0) m = t[i]; return m; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } // c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c; int[] ext_gcd(int a, int b) { if (b == 0) return new int[] {a, 1, 0 }; int[] vals = ext_gcd(b, a % b); int d = vals[0]; // gcd int p = vals[2]; // int q = vals[1] - (a / b) * vals[2]; return new int[] { d, p, q }; } // find any solution of the equation: ax + by = c using extends gcd boolean find_any_solution(int a, int b, int c, int[] root) { int[] vals = ext_gcd(Math.abs(a), Math.abs(b)); if (c % vals[0] != 0) return false; printf(vals); root[0] = c * vals[1] / vals[0]; root[1] = c * vals[2] / vals[0]; if (a < 0) root[0] *= -1; if (b < 0) root[1] *= -1; return true; } int mod(int x) { return x % MOD; } int mod(int x, int y) { return mod(mod(x) + mod(y)); } long mod(long x) { return x % MOD; } long mod (long x, long y) { return mod(mod(x) + mod(y)); } int lw(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } int lw(int[] f, int l, int r, int k) { // int R = r, m = 0; while (l <= r) { int m = l + r >> 1; // if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } long calc(int base, int exponent) { if (exponent == 0) return 1; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long power(int base, int exponent) { if (exponent == 0) return 1; long m = power(base, exponent >> 1); if (exponent % 2 == 0) return m * m; return base * m * m; } void swap(int[] a, int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparable<Pair<K, V>> { private K k; private V v; Pair() {} Pair(K k, V v) { this.k = k; this.v = v; } K getK() { return k; } V getV() { return v; } void setK(K k) { this.k = k; } void setV(V v) { this.v = v; } void setKV(K k, V v) { this.k = k; this.v = v; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Pair)) return false; Pair<K, V> p = (Pair<K, V>) o; return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0; } @Override public int hashCode() { int hash = 31; hash = hash * 89 + k.hashCode(); hash = hash * 89 + v.hashCode(); return hash; } @Override public int compareTo(Pair<K, V> pair) { return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k); } @Override public Pair<K, V> clone() { return new Pair<K, V>(this.k, this.v); } @Override public String toString() { return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n"); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
db55dd29e284c4efd8d6def7c9f01130
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF1005D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String d = scanner.next(); int rem = 0; int[] cMods = new int[d.length()]; for (int i = 0; i < d.length(); i++) { cMods[d.length() - i - 1] = ((d.charAt(d.length() - 1 - i) - 48) * (i == 0 ? 1 : 10) + rem) % 3; rem = cMods[d.length() - i - 1]; } boolean[] prev = new boolean[]{true, false, false}; int result = 0; int last = 0; for (int i = cMods.length - 1; i >= 0; i--) { if (prev[(3 + cMods[i] - last) % 3]) { result++; prev = new boolean[]{true, false, false}; last = cMods[i]; } else { prev[(3 + cMods[i] - last) % 3] = true; } } System.out.println(result); } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
e5bf3e51aadca85b8e0253cb8e53ed8b
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s=sc.next(); char num[]=s.toCharArray(); int number[]=new int[num.length]; for(int i=0;i<number.length;i++) { number[i]=num[i]-'0'; } int dp[]=new int[number.length]; if(number[0]%3==0)dp[0]=1; else dp[0]=0; for(int i=1;i<number.length;i++) { if(number[i]%3==0)dp[i]=dp[i-1]+1; else { dp[i]=dp[i-1];//预处理 int team=number[i]; for(int j=i-1;j>=0;j--) { if(dp[j]!=dp[i]) {break;} else if(j>0) { if(dp[j]==dp[i]) { team+=number[j]; if(team%3==0) {dp[i]=dp[j-1]+1;break;} } } else if(j==0) { team+=number[j]; if(team%3==0) {dp[i]=dp[j]+1;break;} } } } } System.out.println(dp[number.length-1]); } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
541ece06b7ea50a70f95f6bf2ca5f25e
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.util.*; import java.util.Map.Entry; public class CODE2{ private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; static int BIT[]; public final static int INF = (int) 1E9; static ArrayList<Integer> adj[]; static boolean Visited[]; static HashSet<Integer> exc; static long oddsum[]=new long[1000001]; static long co=0,ans=0; static int parent[]; static int size[],color[],res[],k; static ArrayList<Integer> al[]; static long MOD = (long)1e9 + 7; static int[] levl,dist; static int[] eat; static int nm = 1000007; static boolean divisor[]; static int[] phi; static int mod = (int)1e9 + 7; static HashSet<Integer> div ; static double maxvector = 1.5 * (1e6); public static void solve(){ char c[] = nextLine().toCharArray(); int digit[] = new int[c.length]; for(int i=0;i<c.length;i++) digit[i] = (c[i] - '0')%3; int n = c.length; int sum =0; //int prev = 0; int res =0; int lc=0; int rc =0; for(int i=0;i<n;i++) { if(digit[i]==0) { res++; sum=0; lc =0; rc =0; } else { if(digit[i]==2) { if(lc!=0 || rc>=2) { lc =0;rc=0; res++; } else rc++; } else if(digit[i]==1) { if(rc!=0 || lc>=2) { res++; lc =0; rc =0; } else lc++; } } } pw.println(res); } public static void main(String args[]) { InputReader(System.in); pw = new PrintWriter(System.out); new Thread(null ,new Runnable(){ public void run(){ try{ solve(); pw.close(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static StringBuilder sb; public static void test(){ sb=new StringBuilder(); int t=nextInt(); while(t-->0){ solve(); } pw.println(sb); } public static long pow(long n, long p,long mod) { if(p==0) return 1; if(p==1) return n%mod; if(p%2==0){ long temp=pow(n, p/2,mod); return (temp*temp)%mod; }else{ long temp=pow(n,p/2,mod); temp=(temp*temp)%mod; return(temp*n)%mod; } } public static long pow(long n, long p) { if(p==0) return 1; if(p==1) return n; if(p%2==0){ long temp=pow(n, p/2); return (temp*temp); }else{ long temp=pow(n,p/2); temp=(temp*temp); return(temp*n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } private static void buildgraph(int n){ adj=new ArrayList[n+1]; Visited=new boolean[n+1]; levl=new int[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); } } static void sprime() { spf=new int[nm+1]; for(int i=2;i<nm;i++) { if(spf[i]!=0) continue; for(int j=i;j<nm;j+=i) { spf[j] = i; } } } static void toposort(int i) { Visited[i] = true; for(int j : adj[i]) { if(!Visited[j]) toposort(j); } } static void comp(int n) { for(int i=1;i<=Math.sqrt(n);i++) { if(n%i==0) { if(i==n/i) div.add(i); else { div.add(i); div.add(n/i); } } } } static void calculatephi() { int end = (int)1e6 + 5; for(int i=1;i<end;i++) phi[i] = i; for(int i=2;i<end;i++) { if(phi[i]==i) { phi[i] = i - 1; for(int j=2 * i;j<end;j=j+i) { phi[j] = (phi[j]/i) * (i-1); } } } } static void randomize( long arr[], int n) { Random r = new Random(); for (int i = n-1; i > 0; i--) { int j = r.nextInt(i); long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } static class pa implements Comparator<Integer> { public int compare(Integer a,Integer b) { return b-a; } } static class node implements Comparable<node> { long r;long i; node(long r,long i) { this.r = r; this.i = i; } public int compareTo(node other) { return Long.compare(this.r,other.r); } } /* static void BITupdate(int x,int val) { while(x<=n) { BIT[x]+=val; x+= x & -x; } }*/ /* static void update(int x,long val) { val=val%MOD; while(x<=n) { // System.out.println(x); BIT[x]=(BIT[x]+val)%MOD; x+=(x & -x); } // System.out.println("dfd"); }*/ static int BITsum(int x) { int sum=0; while(x>0) { sum+=BIT[x]; x-= (x & -x); } return sum; } /* static long sum(int x) { long sum=0; while(x>0) { sum=(sum+BIT[x])%MOD; x-=x & -x; } return sum; }*/ static boolean union(int x,int y) { int xr=find(x); int yr=find(y); if(xr==yr) return false; if(size[xr]<size[yr]) { size[yr]+=size[xr]; parent[xr]=yr; } else { size[xr]+=size[yr]; parent[yr]=xr; } return true; } static int find(int x) { if(parent[x]==x) return x; else { parent[x]=find(parent[x]); return parent[x]; } } public static class Edge implements Comparable<Edge> { long x;int i; public Edge(long x,int i) { this.x = x; this.i = i; //this.s = s; } public int hashCode() { return Objects.hash(); } public int compareTo(Edge other) { return Long.compare(this.x,other.x); } } static int col[]; static int no_vert=0; public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return (sb.toString()); } static int indeg[]; /* private static void kahn(int n){ PriorityQueue<Integer> q=new PriorityQueue<Integer>(); for(int i=1;i<=n;i++){ if(indeg[i]==0){ q.add(i); } } while(!q.isEmpty()){ int top=q.poll(); st.push(top); for(Node i:adj[top]){ indeg[i.to]--; if(indeg[i.to]==0){ q.add(i.to); } } } } static int state=1; static long no_exc=0,no_vert=0; static Stack<Integer> st; static HashSet<Integer> inset; private static void topo(int curr){ Visited[curr]=true; inset.add(curr); for(int x:adj[curr]){ if(adj[x].contains(curr) || inset.contains(x)){ state=0; return; } if(state==0) return; } st.push(curr); inset.remove(curr); }*/ static HashSet<Integer> hs; static boolean prime[]; static int spf[]; public static void sieve(int n){ prime=new boolean[n+1]; spf=new int[n+1]; Arrays.fill(spf, 1); Arrays.fill(prime, true); prime[1]=false; spf[2]=2; for(int i=2;i*i<=n;i++){ if(prime[i]){ spf[i]=i; for(int j=2*i;j<=n;j+=i){ prime[j]=false; } } } } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static long[][] next2dArray(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextLong(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
0b18df3529a8f93d83068fefa1ca7e82
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int arr[]=new int [300000]; public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s=sc.next(); int n=s.length(); for(int i=0;i<n;i++) { arr[i+1]=(s.charAt(i)-'0')%3; } int ans=0; int sum=0; int num=0; for(int i=1;i<=n;i++){ sum+=arr[i]; num++; if(arr[i]==0||sum==3||num==3){ sum=0; num=0; ans++; } } System.out.println(ans); } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
56253225facbacdd66855387da87000d
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class PolycarpAndDiv3 { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { long mod = (long)(1000000007); public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { while(testNumber-->0){ String a = in.next(); int first = 0; int second = 0; int third = 0; long count = 0; for(int i=0;i<a.length();i++){ int x = a.charAt(i) - '0'; if(x%3==0){ count++; first = 0; second = 0; third = 0; } else{ third = second; second = first; first = x%3; if(first+second == 3){ count++; first = 0; second = 0; third = 0; } else if((first + second + third)%3 == 0){ count++; first = 0; second = 0; third = 0; } } } out.println(count); } } public void dfs(ArrayList<ArrayList<Integer>> a , int index , int visited[] , int distance[] , int parent[]){ if(visited[index] == 1) return; visited[index] = 1; int l = a.get(index).size(); for(int i=0;i<l;i++){ if(visited[a.get(index).get(i)] == 1) continue; parent[a.get(index).get(i)] = index; distance[a.get(index).get(i)] = 1 + distance[index]; dfs(a , a.get(index).get(i) , visited , distance , parent); } } public void sieve(int a[]){ a[0] = a[1] = 1; int i; for(i=2;i*i<=a.length;i++){ if(a[i] != 0) continue; a[i] = i; for(int k = (i)*(i);k<a.length;k+=i){ if(a[k] != 0) continue; a[k] = i; } } } public int [][] matrixExpo(int c[][] , int n){ int a[][] = new int[c.length][c[0].length]; int b[][] = new int[a.length][a[0].length]; for(int i=0;i<c.length;i++) for(int j=0;j<c[0].length;j++) a[i][j] = c[i][j]; for(int i=0;i<a.length;i++) b[i][i] = 1; while(n!=1){ if(n%2 == 1){ b = matrixMultiply(a , a); n--; } a = matrixMultiply(a , a); n/=2; } return matrixMultiply(a , b); } public int [][] matrixMultiply(int a[][] , int b[][]){ int r1 = a.length; int c1 = a[0].length; int c2 = b[0].length; int c[][] = new int[r1][c2]; for(int i=0;i<r1;i++){ for(int j=0;j<c2;j++){ for(int k=0;k<c1;k++) c[i][j] += a[i][k]*b[k][j]; } } return c; } public long nCrPFermet(int n , int r , long p){ if(r==0) return 1l; long fact[] = new long[n+1]; fact[0] = 1; for(int i=1;i<=n;i++) fact[i] = (i*fact[i-1])%p; long modInverseR = pow(fact[r] , p-2 , 1l , p); long modInverseNR = pow(fact[n-r] , p-2 , 1l , p); long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p; return w; } public long pow(long a , long b , long res , long mod){ if(b==0) return res; if(b==1) return (res*a)%mod; if(b%2==1){ res *= a; res %= mod; b--; } // System.out.println(a + " " + b + " " + res); return pow((a*a)%mod , b/2 , res , mod); } public long pow(long a , long b , long res){ if(b == 0) return res; if(b==1) return res*a; if(b%2==1){ res *= a; b--; } return pow(a*a , b/2 , res); } public void swap(int a[] , int p1 , int p2){ int x = a[p1]; a[p1] = a[p2]; a[p2] = x; } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ long value; long delete; Combine(long val , long delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(b == 0) return 0; if(a%b==0) return b; return gcd(b , a%b); } public void print2d(long a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
e67188b08233c989abb3c61eed1c8f6f
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.util.*; import java.io.*; public class Main { static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static InputReader in = new InputReader(inputStream); static OutputWriter out = new OutputWriter(outputStream); static Scanner inn=new Scanner(System.in); static int n=0; static int[] number=new int[200010]; static int[] sum=new int[200010]; public static void main(String[] args){ String a=in.next(); for(int i=0;i<a.length();++i) { number[i]=a.charAt(i)-'0'; } int l=a.length(); int ptr=-1; long sum=0,ctr=0; for(int i=0;i<l;++i) { sum=0; for(int j=i;j>ptr;--j) { sum+=number[j]; if(sum%3==0) { ctr++; ptr=i; } } } out.println(ctr); out.close(); } static int min(int a ,int b) { return a>b?a:b; } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } 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 nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
864072d985980ae6044e6abca9154bb1
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); String str = in.next(); int cnt=0,t=0; String num=""; for(int i=0 ;i<str.length() ;i++){ if((str.charAt(i)+"").matches("[0369]")) {cnt++;num="";t=0;} else { num += str.charAt(i); t+= str.charAt(i)-'0'; if(t%3==0) {cnt++;num="";t=0;} else if(check(num,t)) {cnt++;num="";t=0;} } } System.out.println(cnt); } static boolean check(String s,int sum){ for(int i=0 ;i<s.length()-1; i++){ sum -= s.charAt(i)-'0'; if(sum%3==0) return true; } return false; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
7193b3d1db7ef212925145cab3e2e12c
train_003.jsonl
1531150500
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.max; import static java.lang.Math.min; public class Solution implements Runnable { public static void main(String[] args) throws IOException, InterruptedException { // System.setIn(new FileInputStream("input.txt")); // System.setOut(new PrintStream(new FileOutputStream("output.txt"))); Thread t = new Thread(null, new Solution(), "solutionThread", 1 << 28); t.start(); } @Override public void run() { Scanner sc = new Scanner( System.in ); String s = sc.next(); int n = s.length(), ans = 0; int[] ar = new int[n]; for ( int i = 0; i < n; i++ ) { int a = s.charAt( i ) - '0'; ar[i] = a%3; if ( ar[i]%3==0 ) { ans++; } else if ( i > 0 && (ar[i] + ar[i - 1]) % 3 == 0 ) { ans++; ar[i] = 0; ar[i-1] = 0; } else if ( i > 1 && ar[i] == 1 && ar[i - 1] == 1 && ar[i - 2] == 1 ) { ans++; ar[i] = 0; ar[i-1] = 0; ar[i-2] = 0; } else if ( i > 1 && ar[i] == 2 && ar[i - 1] == 2 && ar[i - 2] == 2 ) { ans++; ar[i] = 0; ar[i-1] = 0; ar[i-2] = 0; } } System.out.println(ans); // System.out.println(totalCall); } }
Java
["3121", "6", "1000000000000000000000000000000000", "201920181"]
3 seconds
["2", "1", "33", "4"]
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
Java 8
standard input
[ "dp", "number theory", "greedy" ]
3b2d0d396649a200a73faf1b930ef611
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
1,500
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
standard output
PASSED
722adc86f7e0c44ab7a50f83e01b9b70
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner ob=new Scanner(System.in); int sieve[]=new int[1000001]; for(int i=2;i<=1000000;i++) { sieve[i]=i; } for(int i=2;i*i<=1000000;i++) { if(sieve[i]==i) { for(int j=i*i;j<=1000000;j+=i) { if(sieve[j]==j) sieve[j]=i; } } } int n=ob.nextInt(); ArrayList<Integer> a=new ArrayList<Integer>(); int c=1; for(int i=2;i<=n+1;i++) { if(sieve[i]==i) a.add(1); else a.add(2); } if(n>=3) { System.out.println("2"); for(int i:a) System.out.print(i+" "); } if(n==2) { System.out.println("1"); System.out.println("1 1"); } if(n==1) { System.out.println("1"); System.out.println("1"); } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
0d1664bc9c222803137a247a9d36f44c
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
//PROBLEM LINK: https://codeforces.com/contest/776/problem/B import java.util.Scanner; import java.lang.Math; import java.util.*; public class Codeforces{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.nextLine()); int[] res = new int[n]; for(int i=0; i<n;i++) res[i]=1; boolean[] prime = new boolean[n]; int max=1, count=1; for(int i=0;i<n-1;i++) { if(prime[i]==false) { for(int j=(i+2)*2; j<=(n+1);j+=(i+2)) { prime[j-2]=true; if(res[i]==res[j-2]) res[j-2]++; if(res[j-2]>max) { max=res[j-2]; count++; } } } } System.out.println(count); for(int i=0; i<n;i++) System.out.print(res[i]+" "); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
6acc014bf23c6354b5f5f3a0d392a1ea
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.io.*; import java.lang.String; import java.util.*; public class Main { private static int BinarySearch(int a[], int low, int high, int target) { if (low > high) return -1; int mid = low + (high - low) / 2; if (a[mid] == target) return mid; if (a[mid] > target) high = mid - 1; if (a[mid] < target) low = mid + 1; return BinarySearch(a, low, high, target); } static String printPermutn(String str, String ans) { if (str.length() == 0) { System.out.print(ans + " "); return str; } for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); String ros = str.substring(0, i) + str.substring(i + 1); printPermutn(ros, ans + ch); } return str; } static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { if (index == r) { for (int j = 0; j < r; j++) System.out.print(data[j] + " "); System.out.println(""); return; } if (i >= n) return; data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); combinationUtil(arr, n, r, index, data, i + 1); } static void printCombination(int arr[], int n, int r) { int data[] = new int[r]; combinationUtil(arr, n, r, 0, data, 0); } private static void printArray(int[] input) { System.out.print('\n'); for (int i = 0; i < input.length; i++) { System.out.print(input[i]); } } private static void swapArray(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } static void printPermutation(int[] arr, int n) { if (n == arr.length - 1) System.out.println(); else { for (int i = 0; i < n - 1; i++) { swapArray(arr, n - 1, i); printPermutation(arr, n - 1); } printPermutation(arr, n - 1); } } static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final int MAXN = 100001; static int pf[] = new int[MAXN]; static boolean [] sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int i = 2; i * i <= n; i++) { if (prime[i] == true) { for (int p = i * i; p <= n; p += i) prime[p] = false; } } return prime; } static void sieve() { pf[1] = 1; for (int i = 2; i < MAXN; i++) pf[i] = i; for (int t = 4; t < MAXN; t += 2) pf[t] = 2; for (int i = 3; i * i < MAXN; i++) { if (pf[i] == i) { for (int j = i * i; j < MAXN; j += i) { if (pf[j] == j) pf[j] = i; } } } /*for (int n:pf) System.out.println(n);*/ } static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(pf[x]); x = x / pf[x]; } return ret; } static long divisors(long n) { long count = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0) { if (n / i == i) count++; else count += 2; } } return count; } public static void primeFactor() { FastReader f = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int n = f.nextInt(); //int[] a = new int[n]; int[] facto = new int[1000001]; facto[1] = 1; int count = 0; for (int i = 0; i < n; i++) { int x = f.nextInt(); while (x % 2 == 0) { x /= 2; count++; } if (count > 0) facto[2]++; count = 0; for (int j = 3; j * j <= x; j += 2) { if (x % j == 0) { while (x % j == 0) { x /= j; count++; } if (count > 0) facto[j]++; count = 0; } } if (x > 2) facto[x]++; } int max = 1; for (int i = 0; i < 100001; i++) { max = Math.max(facto[i], max); } if (n == 1) max = 1; pw.print(max); pw.close(); } static void primeFactors(int n) { while (n % 2 == 0) { System.out.println(2); n /= 2; } for (int i = 3; i * i <= n; i += 2) { while (n % i == 0) { System.out.println(i); n /= i; } } if (n > 2) System.out.println(n); } public static void main(String[] args) { Scanner input = new Scanner(System.in); FastReader f = new FastReader(); PrintWriter pw = new PrintWriter(System.out); StringBuilder stb = new StringBuilder(); sieve(); int n = f.nextInt(); boolean [] aa=sieveOfEratosthenes(n+1); int[] a = new int[n]; if (n==1 || n==2){ pw.println(1); if (n==1){ pw.print(1); } else pw.print(1+" "+1); }else { if (n > 2) pw.println(2); else pw.println(1); for (int i = 2; i <= n + 1; i++) { if (aa[i]) { pw.print(1 + " "); } else pw.print(2 + " "); } } pw.close(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
aedfd92618355098a52a53df0f64aec1
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; import java.io.*; public class sherlock_and_primes { static final int mod=(int)1e9+7; static final int inf=(int)1e9; static final long INF=(long)1e18; public static void main(String[] args) { FastScanner fs=new FastScanner(); boolean arr[]=new boolean[(int)1e5+2]; int n=fs.nextInt(); if(n<=2) { System.out.println(1); } else { System.out.println(2); } int ans[]=new int[n+2]; ans[0]=ans[1]=inf; for(int i=2;i*i<=n+1;i++) { if(arr[i]==false) { ans[i]=1; for(int j=i*i;j<=n+1;j+=i) { ans[j]=2; arr[j]=true; } } } for(int i=2;i<ans.length;i++) { if(ans[i]==0) System.out.print(1+" "); else System.out.print(ans[i]+" "); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } long pow(long x,long n) { long res=1; while(n>0) { if(n%2!=0) { res=(res*x);n--; } else { x=(x*x);n/=2; } } return res; } int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } long longgcd(long a,long b) { if(b==0) { return a; } return longgcd(b,a%b); } int[] sort(int arr[]) { ArrayList<Integer> list = new ArrayList<Integer>(); for(int i:arr)list.add(i); Collections.sort(list); for(int i=0;i<arr.length;i++) { arr[i]=list.get(i); } return arr; } char[] charsort(char arr[]) { ArrayList<Character> list = new ArrayList<>(); for(char c:arr)list.add(c); Collections.sort(list); for(int i=0;i<list.size();i++) { arr[i]=list.get(i); } return arr; } long[] longsort(long arr[]) { ArrayList<Long> list = new ArrayList<Long>(); for(long i:arr)list.add(i); Collections.sort(list); for(int i=0;i<arr.length;i++) { arr[i]=list.get(i); } return arr; } public int nextInt() { return Integer.parseInt(next()); } public int[] readArray(int n) { int[] arr=new int[n]; for (int i=0; i<n; i++) arr[i]=nextInt(); return arr; } public long nextLong() { return Long.parseLong(next()); } public long[] longreadArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
d09e5f391faa8e541f36d2b4b8a4bf67
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); if(n<3) { System.out.println(1); } else { System.out.println(2); } for(int i = 1; i<=n ;i++) { if(isPrime(i+1)) { System.out.print(1+" "); } else { System.out.print(2+" "); } } } public static boolean isPrime(int n) { int x = (int)Math.sqrt(n); boolean isPrime = false; if(n == 1) { return false; } for(int i = 2; i<=x; i++) { if(n%i == 0) { return false; } } return true; } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
1e89cb18d336e244b938f0851fd200e0
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ar { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (final IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (final IOException e) { e.printStackTrace(); } return str; } } static boolean[] seen; static Map<Integer, Integer> map; static Set<Character> charset; static Set<Integer> set; static int[] arr; static int[][] dp; static int rem = (int) 1e9 + 7; static List<List<Integer>> graph; static int[][] kmv ={{2,1},{1,2},{2,-1},{-1,2},{-2,1},{1,-2},{-1,-2},{-2,-1}}; static int MAX=(int)1e6+1; static boolean[] primes = new boolean[MAX]; static void Sieve(){ primes[0]=true; primes[1]=true; for(int i=2;i*i<MAX;i++){ if(!primes[i]){ for(int j=i*i;j<MAX;j+=i){ primes[j]=true; } } } } public static void main( String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int n=scn.nextInt(); Sieve(); if (n > 2) { System.out.print(2 + "\n"); } else System.out.print(1 + "\n"); for(int i=2;i<=n+1;i++){ if(!primes[i]){ System.out.print(1+" "); }else{ System.out.print(2+" "); } } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
e34e18b1064ef43922c16012545f84e5
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; import java.io.*; public class Sherlock_And_His_Girlfriend { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); int n = t.nextInt(); soe(n + 1); } private static void soe(int n) { PrintWriter o = new PrintWriter(System.out); boolean prime[] = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } if (n <= 3) { o.println(1); for (int i = 0; i < n - 1; i++) o.print(1 + " "); } else { o.println(2); for (int i = 0; i < n - 1; i++) { if (prime[i + 2]) o.print(1 + " "); else o.print(2 + " "); } } o.flush(); o.close(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
82d4de3c815c6b6c35b17752abf044ff
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc=new Scanner(System.in); long t=sc.nextLong(); long prime[]=new long[100000+2]; Arrays.fill(prime,1); long ans=0; for(int i=2;i*i<=100000;i++) { if(prime[i]==1) { for(int j=2*i;j<prime.length;j+=i) { prime[j]=2; } } } if(t<=2) { System.out.println("1"); } else { System.out.println("2"); } for(int i=2;i<=t+1;i++) { System.out.print(prime[i]+" "); } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
127e47b46209ae230990974d03fa41e6
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.Scanner; public class Solution { static boolean isPrime(int n) { if(n==0) return false; if(n==1) return false; if(n==2) return true; for(int i=2;i*i<=n;i++) { if(n%i==0) return false; } return true; } public static void main (String[] args) { Scanner sc = new Scanner(System.in); try{ int n = sc.nextInt(); if(n == 1){ System.out.println(1); System.out.println(1); }else if(n == 2){ System.out.println(1); System.out.println(1+" "+1); }else{ System.out.println(2); for(int i=2;i<=n+1;i++){ if(isPrime(i)){ System.out.print(1+" "); }else{ System.out.print(2+" "); } } System.out.println(); } }catch(Exception e){ } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
e760193f58ce7cdd970d3c0ebc4c5a9c
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class _H6_FindPrime { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] ans = new int[N + 2]; Arrays.fill(ans, 1); for (int i = 2; (i * i) < N + 2; i++) { if (ans[i] == 1) { for (int j = i * i; j < N + 2; j += i) { ans[j] = 2; } } } System.out.println(N <= 2 ? 1 : 2); for (int i = 2; i < N + 2; i++) { System.out.print(ans[i] + " "); } System.out.println(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
a3e400882238c8f42e7cd9d3817a0b3a
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; public class CodeForcesCompetetive { public static void main(String[] args) throws IOException,NumberFormatException { try { FastScanner sc=new FastScanner(); int n=sc.nextInt(); int a[]=new int[n]; int count=2; for(int i=0;i<n;i++) { a[i]=count; count++; } boolean ans=false; for(int i=0;i<n;i++) { if(isPrime(a[i])) { a[i]=1; } else a[i]=2; } if(n<=2) { System.out.println(1); } else { System.out.println(2); } for(int i=0;i<n;i++) { System.out.print(a[i]+" "); } } catch(Exception e) { return; } } public static boolean isPrime(int n) { if(n==1) { return false; } for(int i=2;i*i<=n;i++) { if(n%i==0) { return false; } } return true; } public static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
0d1d11d4c47664defacc87a4f0e10f3d
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); //int t = fs.nextInt(); for (int k = 1; k <= 1; k++) { int n = fs.nextInt(); //Prime_Seive ps = new Prime_Seive(); int arr[]=new int[n+2]; int result[]=prime_seive(n+1, arr); if(n==2||n==1){ out.println(1); } else{ out.println(2); } for(int i=2;i<=n+1;i++){ out.print(result[i]+" "); } out.println(); // out.println(); } out.close(); } public static Long solver(Long arr[], int n) { Long min = Long.MAX_VALUE; Long working = arr[0]; Long operations = 0L; boolean dec = false; Long max = Long.MIN_VALUE; for (int i = 0; i < n; i++) { max = Math.max(max, arr[i]); if (arr[i] < max) { // System.out.println("max "+max+" "+arr[i]); dec = true; } } for (int i = 1; i <= n; i++) { if (i < n - 1 && arr[i] <= arr[i + 1] && !dec) { // System.out.println(arr[i]+" "+arr[i+1]); continue; } if (i < n - 1 && arr[i] <= arr[i + 1]) { working = arr[i + 1]; } Long h = (i == n) ? Long.MAX_VALUE : arr[i]; min = Math.min(min, h); if (h >= working && h != Long.MAX_VALUE) { System.out.println(working + " " + min + " " + operations); operations += working - min; System.out.println(operations); working = h; min = Long.MAX_VALUE; } } /* * Stack<Long> stack=new Stack<>(); stack.push(arr[0]); Long operations=0L; * boolean dec=false; for(int i=1;i<=n;i++){ * if(!stack.isEmpty()&&i<n&&arr[i]<stack.peek()){ dec=true; } Long * h=(i==n)?Long.MAX_VALUE:arr[i]; while(stack.size()>1&&dec&&stack.peek()<h){ * operations++; Long element=stack.pop(); element++; * if(element!=stack.peek()&&element!=h){ stack.push(element); } } * if(stack.peek()>h){ stack.push(h); } else * if(stack.peek()<h&&h!=Long.MAX_VALUE){ stack.pop(); stack.push(h); } } */ return operations; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static int[] prime_seive(int n, int[] arr) { int limit=(int)Math.sqrt(n); Arrays.fill(arr,1); int result[]=new int[n+2]; for (int i = 2; i <=n; i ++) { if (arr[i] == 1) { //primes.add(i); result[i]=1; //System.out.println(i); for (int j = 2 * i; j <= n; j += i) { arr[j] = 0; result[j]=2; } } } arr[1] = arr[0]=0; return result; } static int gcdCoeff(int a, int b, int arr[])// euclidean gcd + extended euclidean { if (b == 0) return a; int tmp[] = { 1, 1 };// must be 1,1, because at base step b=0, a=anything, 1.0+ 1.a=a int result = gcdCoeff(b, a % b, tmp); arr[0] = tmp[1];// x=y1 arr[1] = (tmp[0] - (a / b) * tmp[1]);// y=(x1-(a/b)*y1) return result; } static class PairIndex { long val; long index; public PairIndex(long val, long index) { this.val = val; this.index = index; } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } Long[] readLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
33193613c00aa2bb9ea71b2efe3a2bdd
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; import java.io.*; public class cf { public static void main(String[] args) { FastReader in = new FastReader(); int n = in.nextInt(); boolean p[] = new boolean[n+2]; int colors[] = new int[n+2]; int ans = (n>2)?2:1; sieve(p,colors); System.out.println(ans); for(int i=2;i<n+2;i++) System.out.print(colors[i]+" "); } static void sieve(boolean[] p,int[] colors) { int n = p.length-1; for(int i=0;i<=n;i++) p[i] = true; p[0] = p[1] = false; for(int i=2;i<=n;i++) { if(p[i]) { p[i] = false; colors[i] = 1; for(int j=i+i;j<=n;j+=i) { colors[j]= 2; p[j] = false; } } } } static int gcd(int a, int b){ return (b==0) ? a : gcd(b, a%b); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return next().charAt(0); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] arr = new int[n]; String[] str = nextLine().split(" "); for(int i=0;i<n;i++) arr[i] = Integer.parseInt(str[i]); return arr; } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
46706d83f3902836923db77415107148
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { static void sieveOfEratosthenes(int n) { int prime[]=new int[n+3]; for(int i=0;i<n+3;i++) prime[i]=1; for(int i=2;i*i<=n+2;i++) { if(prime[i]==1) { for(int j=i*i;j<=n+2;j+=i) prime[j]=2; } } for(int i=2;i<=n+1;i++) { int e=prime[i]; System.out.print(e+" "); } } public static void main (String[] args) throws java.lang.Exception { try{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); if(n>2) System.out.println("2"); else System.out.println("1"); sieveOfEratosthenes(n); } catch(Exception e) {} } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
b6a617724442f9c79b507d830e6f5b2d
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
//package com.company; import java.io.*; import java.util.*; //public class Sherlockandhisgirlfriend { public class Main { static int n=1000000; static boolean prime[] = new boolean[n+1]; public static void sieveOfEratosthenes() { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); MyScanner sc = new MyScanner();//start int till=sc.nextInt(); out.println(till>2?2:1); sieveOfEratosthenes();till+=2; for (int z = 2; z < till; z++) { out.print((prime[z]?1:2)+" "); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
aad4cd548d4cdf289ae652701a35a59e
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; public class hef { public static int[] prime(int n) { int a[] = new int[n]; ArrayList<Integer> k = new ArrayList<>(); for (int i = 2; i * i <a.length; i++) { if (a[i]==0) { for (int j = 2 * i; j < a.length; j += i) { a[j]= a[i]+1; } } } return a; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a[] = prime(n+2); HashSet<Integer> h = new HashSet<>(); for(int i=2;i<a.length;i++) { h.add(a[i]+1); } System.out.println(h.size()); for(int i=2;i<a.length;i++) { System.out.print((a[i]+1)+" "); } System.out.println(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
140dcee82334afdd7034ce8daf19dfc8
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; public class hef { public static int[] prime(int n) { int a[] = new int[n]; ArrayList<Integer> k = new ArrayList<>(); for (int i = 2; i * i <a.length; i++) { if (a[i]==0) { for (int j = 2 * i; j < a.length; j += i) { a[j]=1; } } } return a; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a[] = prime(n+2); if(n<=2) { System.out.println(1); } else System.out.println(2); for(int i=2;i<a.length;i++) { System.out.print((a[i]+1)+" "); } System.out.println(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
5eadb467136ce95446fe36a420325118
train_003.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.util.*; import java.io.*; public class B { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); boolean[] primes = new boolean[n+2]; Arrays.fill(primes, true); for(int i = 2; i*i <= n+1; i++){ if(primes[i]){ for(int j = i*i; j <= n+1; j += i){ primes[j] = false; } } } if(n > 2){ System.out.println(2); } else{ System.out.println(1); } for(int i = 2; i <= n+1; i++){ if(!primes[i]){ System.out.print(2 + " "); } else{ System.out.print(1 + " "); } } } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
6f124b4a58c0b056ecd71f6bd1518053
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class SydneyTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); int size = input.nextInt(); List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); List<Integer> list3 = new ArrayList<>(); for (int x = 0; x < size; x++) { list1.add(input.nextInt()); } size--; for (int x = 0; x < size; x++) { list2.add(input.nextInt()); } size--; for (int x = 0; x < size; x++) { list3.add(input.nextInt()); } int num1 = list1.stream().mapToInt(Integer::intValue).sum(); int num2 = list2.stream().mapToInt(Integer::intValue).sum(); int num3 = list3.stream().mapToInt(Integer::intValue).sum(); System.out.println(num1 - num2); System.out.println(num2 - num3); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
15313a4e1ffb310c2ed992985dd7c646
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.*; public class CompileError2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); long sum1 = 0; long sum2 = 0; long sum3 = 0; for(int i=0; i<x; i++) sum1 += sc.nextInt(); for(int i=0; i<x-1; i++) sum2 += sc.nextInt(); for(int i=0; i<x-2; i++) sum3 += sc.nextInt(); System.out.println(sum1-sum2); System.out.println(sum2-sum3); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
2ecf724e23fb37de38b786409f0cf218
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class EasyTask { public static void main(String args[]) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public int min(int a, int b) { return a < b ? a : b; } public int max(int a, int b) { return a < b ? b : a; } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a[] = new int[3]; for (int i = 0; i < 3; ++i) for (int j = 0; j < n-i; ++j) a[i] += in.nextInt(); out.println(a[0] - a[1]); out.println(a[1] - a[2]); } } class InputReader { BufferedReader in; StringTokenizer st; public InputReader(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); eat(""); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public String next() { while (!st.hasMoreTokens()) eat(nextLine()); return st.nextToken(); } public String nextLine() { try { return in.readLine(); } catch (IOException e) { throw new InputMismatchException(); } } public void eat(String str) { if (str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
caf32f74aa63a82c30f476ecd16cc90b
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class EasyTask { public static void main(String args[]) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public int min(int a, int b) { return a < b ? a : b; } public int max(int a, int b) { return a < b ? b : a; } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a[][] = new int[3][n]; for (int i = 0; i < 3; ++i) for (int j = 0; j < n-i; ++j) a[i][j] = in.nextInt(); Arrays.sort(a[0]); Arrays.sort(a[1]); Arrays.sort(a[2]); for (int i = n-1; i >= 0; --i) if (a[0][i] != a[1][i]) { out.println(a[0][i]); break; } for (int i = n-1; i >= 0; --i) if (a[1][i] != a[2][i]) { out.println(a[1][i]); break; } } } class InputReader { BufferedReader in; StringTokenizer st; public InputReader(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); eat(""); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public String next() { while (!st.hasMoreTokens()) eat(nextLine()); return st.nextToken(); } public String nextLine() { try { return in.readLine(); } catch (IOException e) { throw new InputMismatchException(); } } public void eat(String str) { if (str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
38a359d2f82ff65f657e820ac4a9617d
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class P519B { public static void main(String []args)throws Exception{ String str = ""; Scanner sc = new Scanner(System.in); double inf = Double.POSITIVE_INFINITY; int inf1 = (int ) inf ; int numb = sc.nextInt(); int [] array1 = new int [numb]; for(int i =0 ; i< numb ; i++){ array1[i] = sc.nextInt(); } Arrays.sort(array1); int [] array3 = new int [numb]; for(int i = 0 ; i<numb-1;i++){ array3[i] = sc.nextInt(); } array3[numb-1]= inf1; Arrays.sort(array3); int [] array4 = new int [numb]; for(int i = 0; i<numb-2;i++){ array4[i] = sc.nextInt(); } array4 [numb-1]=inf1; array4[numb-2]= inf1; Arrays.sort(array4); int numb1pos = 0 ; for(int i = 0 ; i<numb ;i++){ if(array1[i]!=array3[i]){ System.out.println(array1[i]); break; } } for(int i = 0 ; i<numb ;i++){ if(array3[i]!=array4[i]){ System.out.println(array3[i]); break; } } }}
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
3c0eb21c3c6d6c75938d5009d5dc248a
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.*; public class Compilation { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long sum=0l; for(int i=0;i<n;i++) { int a=sc.nextInt(); sum=sum+a; } long s1=sum; for(int i=0;i<n-1;i++) { s1=s1-sc.nextInt(); } long s2=sum-s1; for(int i=0;i<n-2;i++) { s2=s2-sc.nextInt(); } System.out.print(s1+"\n"+s2); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
2715eeec68cfa377748c16fe8e0b490d
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.io.*; import java.util.*; public class ab2 { public static void main(String agrs[]) { int flag=0; int n; Scanner s=new Scanner (System.in); n=s.nextInt(); int sum1=0; int sum2=0; int sum3=0; int ar1[]=new int[n]; int ar2[]=new int[n-1]; int ar3[]=new int[n-2]; for(int i=0;i<n;i++) { ar1[i]=s.nextInt(); } for(int i=0;i<n;i++) { sum1=sum1+ar1[i]; } for(int i=0;i<n-1;i++) { ar2[i]=s.nextInt(); } for(int i=0;i<n-1;i++) { sum2=sum2+ar2[i]; } for(int i=0;i<n-2;i++) { ar3[i]=s.nextInt(); } for(int i=0;i<n-2;i++) { sum3=sum3+ar3[i]; } System.out.println(sum1-sum2); System.out.println(sum2-sum3); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
44b73d3c2c49e4fc3ae077e86eebaa4b
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.HashMap; import java.util.Map.Entry; import java.util.Objects; import java.util.Scanner; /** * * @author arabtech */ public class BePositive { public static boolean[] visited; /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<Integer,Integer> originalFreq=new HashMap<>(); HashMap<Integer,Integer> finalFreq=new HashMap<>(); HashMap<Integer,Integer> finalFrequency=new HashMap<>(); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); if(!originalFreq.containsKey(arr[i])){ originalFreq.put(arr[i], 1); } else{ int value=originalFreq.get(arr[i]); originalFreq.put(arr[i], value+1); } finalFreq.put(arr[i], 0); finalFrequency.put(arr[i], 0); } for(int i=0;i<n-1;i++){ int num=sc.nextInt(); int value=finalFreq.get(num); finalFreq.put(num, value+1); } for(Integer entry:finalFreq.keySet()){ if(!Objects.equals(originalFreq.get(entry), finalFreq.get(entry)) ){ System.out.println(entry); break; } } for(int i=0;i<n-2;i++){ int num=sc.nextInt(); int value=finalFrequency.get(num); finalFrequency.put(num, value+1); } for(Integer entry:finalFrequency.keySet()){ if(!Objects.equals(finalFreq.get(entry), finalFrequency.get(entry))){ System.out.println(entry); break; } } } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
6c66b38c344259a41eb9d2269f0126ff
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import javafx.print.Printer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class Ej9 { public static void main(String[] args) { Scanner teclado =new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int numeroErrores= Integer.parseInt(teclado.nextLine()); String[] linea1 = teclado.nextLine().split(" "); String[] linea2 = teclado.nextLine().split(" "); String[] linea3 = teclado.nextLine().split(" "); int a = 0, b = 0, c = 0; a = Stream.of(linea1).mapToInt(Integer::parseInt).sum(); b = Stream.of(linea2).mapToInt(Integer::parseInt).sum(); c = Stream.of(linea3).mapToInt(Integer::parseInt).sum(); /*for (int i = 0; i < numeroErrores; i++){ a +=teclado.nextInt(); } for (int i = 0; i < numeroErrores - 1; i++) { b += teclado.nextInt(); } for (int i = 0; i < numeroErrores - 2; i++) { c += teclado.nextInt(); }*/ out.print(a - b); out.print(" "+ (b - c)); out.flush(); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
4288709754a246b7ee5e9ecd48537889
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import javafx.print.Printer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class Ej9 { public static void main(String[] args) { Scanner teclado =new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int numeroErrores= Integer.parseInt(teclado.nextLine()); String[] linea1 = teclado.nextLine().split(" "); String[] linea2 = teclado.nextLine().split(" "); String[] linea3 = teclado.nextLine().split(" "); int a = 0, b = 0, c = 0; a = Stream.of(linea1).parallel().mapToInt(Integer::parseInt).sum(); b = Stream.of(linea2).parallel().mapToInt(Integer::parseInt).sum(); c = Stream.of(linea3).parallel().mapToInt(Integer::parseInt).sum(); /*for (int i = 0; i < numeroErrores; i++){ a +=teclado.nextInt(); } for (int i = 0; i < numeroErrores - 1; i++) { b += teclado.nextInt(); } for (int i = 0; i < numeroErrores - 2; i++) { c += teclado.nextInt(); }*/ out.print(a - b); out.print(" "+ (b - c)); out.flush(); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
03d70f15a59387a6c6d33b915859b491
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import javafx.print.Printer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class Ej9 { public static void main(String[] args) { Scanner teclado =new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int numeroErrores= Integer.parseInt(teclado.nextLine()); // String[] linea1 = teclado.nextLine().split(" "); // String[] linea2 = teclado.nextLine().split(" "); // String[] linea3 = teclado.nextLine().split(" "); int a = 0, b = 0, c = 0; // a = Stream.of(linea1).parallel().mapToInt(Integer::parseInt).sum(); // b = Stream.of(linea2).parallel().mapToInt(Integer::parseInt).sum(); // c = Stream.of(linea3).parallel().mapToInt(Integer::parseInt).sum(); for (int i = 0; i < numeroErrores; i++){ a +=teclado.nextInt(); } for (int i = 0; i < numeroErrores - 1; i++) { b += teclado.nextInt(); } for (int i = 0; i < numeroErrores - 2; i++) { c += teclado.nextInt(); } out.print(a - b); out.print(" "+ (b - c)); out.flush(); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
184cdfc8d530c7f24330cbd122983e6e
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import javafx.print.Printer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Ej9 { public static void main(String[] args) { Scanner teclado =new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int numeroErrores=teclado.nextInt(); int n, t; int a = 0, b = 0, c = 0; for (int i = 0; i < numeroErrores; i++) { a +=teclado.nextInt(); } for (int i = 0; i < numeroErrores - 1; i++) { b += teclado.nextInt(); } for (int i = 0; i < numeroErrores - 2; i++) { c += teclado.nextInt(); } out.print(a - b); out.print(" "+ (b - c)); out.flush(); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
f9713495df1f97c6b1f8c901cc6ba788
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
//package Codeforces; import java.io.*; import java.util.*; /** * * @author Muxammad Habibullayev */ public class B_519 { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); TreeMap<Integer, Integer> x = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> y = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> z = new TreeMap<Integer, Integer>(); int a, b, c; for(int i = 1; i <= n; i++){ a = sc.nextInt(); if(!x.containsKey(a)){ x.put(a, 1); }else{ x.put(a, x.get(a) + 1); } } y.putAll(x); for(int i = 1; i < n; i++){ a = sc.nextInt(); if(y.get(a)==1){ y.remove(a); }else{ y.put(a, y.get(a) - 1); } } int d = 0; for(Integer i : y.keySet()){ System.out.println(i); d = i; } z.putAll(x); for(int i = 1; i < n - 1; i++){ a = sc.nextInt(); if(z.get(a)==1){ z.remove(a); }else{ z.put(a, z.get(a) - 1); } } int cnt = 0; for(Integer i : z.keySet()){ if(z.get(i) == 2){ System.out.println(i); }else{ if(i != d){ System.out.println(i); } } } } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
8fa28b154f61af88491207f8967a2c05
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.*; //http://codeforces.com/problemset/problem/519/B public class Main { @SuppressWarnings({ "unused", "resource" }) public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int e1 = 0; for(int i=0; i<n; i++){ e1 += s.nextInt(); } int e2 = 0; for(int i=0; i<n-1; i++){ e2 += s.nextInt(); } int e3 = 0; for(int i=0; i<n-2; i++){ e3 += s.nextInt(); } System.out.println(e1 - e2); System.out.println(e2 - e3); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
b28f6e5cf39dc5c1462bab0d0e9ca418
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.*; //Ejercicio 8 --> http://codeforces.com/problemset/problem/519/B public class Main { @SuppressWarnings({ "resource" }) public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int e1 = 0; for(int i=0; i<n; i++){ e1 += s.nextInt(); } int e2 = 0; for(int i=0; i<n-1; i++){ e2 += s.nextInt(); } int e3 = 0; for(int i=0; i<n-2; i++){ e3 += s.nextInt(); } System.out.println(e1 - e2); System.out.println(e2 - e3); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
cfdff74ef175899a6fe320dae9b36c16
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int a=0,b=0,c=0; int n=s.nextInt(); int x; for (int i = 0; i <((n*3)-3); i++) { x=s.nextInt(); if(i>=0&&i<=n-1){ a+=x; } else if(i>=n&&i<=((n+n)-2)){ b+=x; } else if(i>=((n+n)-2)){ c+=x; } } System.out.println(Math.abs(a-b)); System.out.println(Math.abs(b-c)); } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
637b80095e878a445f84abd176ab884e
train_003.jsonl
1425128400
A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?
256 megabytes
import java.util.*; import static java.lang.Math.*; public class codeforces3 { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { problem_9 a = new problem_9(); } static class problem_1 { problem_1() { int n = sc.nextInt(); double ans = 0; for (int i = 0; i < n; i++) { ans += sc.nextDouble(); } System.out.printf("%.10f", ans / (double) n); } } static class problem_2 { problem_2() { int n = sc.nextInt(); String[] s = new String[2]; s[0] = "I hate"; s[1] = "I love"; for (int i = 0; i < n; i++) { System.out.print(s[i % 2] + ((i != n - 1) ? " that " : " it")); } } } static class problem_3 { problem_3() { int n = sc.nextInt(); int maxn = sc.nextInt(), minn = maxn; int ans = 0; for (int i = 0; i < n - 1; i++) { int t = sc.nextInt(); if (t > maxn) { ans++; maxn = t; } if (t < minn) { ans++; minn = t; } } System.out.print(ans); } } static class problem_4 { problem_4() { int ans = 0; int past = -5; boolean b = true; for (int i = 0; i < 5; i++) { int n = sc.nextInt(); if (past != -5 && past != n) { b = false; } past = n; ans += n; } System.out.printf("%d", (ans % 5 != 0 || b && past == 0) ? -1 : ans / 5); } } static class problem_5 { problem_5() { int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int ans = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { if (k >= i && k <= j) { sum += 1 - a[k]; } else { sum += a[k]; } } ans = max(ans, sum); } } System.out.printf("%d", ans); } } static class problem_6 { problem_6() { int m = sc.nextInt(), n = sc.nextInt(); if (m * 9 < n || (n == 0 && m != 1)) { System.out.printf("%s", "-1 -1"); return; } if (n == 0 && m == 1) { System.out.printf("%s", "0 0 "); return; } int x = n; String maxn = ""; String minn = ""; for (int i = 0; i < m; i++) { for (int j = 9; j >= 0; j--) { if (j <= x) { x -= j; maxn += String.valueOf(j); if (x == 0 && j != 0 && i != m - 1) { minn = String.valueOf(j - 1) + minn; } else if (x == 0 && j == 0 && i == m - 1) { minn = "1" + minn; } else if (x == 0 && j == 0 && i != m - 1) { minn = "0" + minn; } else { minn = String.valueOf(j) + minn; } break; } } } System.out.printf("%s %s", minn, maxn); } } static class problem_7 { problem_7() { int n = sc.nextInt(); int ans = 0; int add = 1; int add2 = 1; for (int i = 0; i < n; i++) { ans += add; add += add2++; } System.out.printf("%d", ans); } } static class problem_8 { problem_8() { int n = sc.nextInt(); int map[][] = new int[10][10]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { map[i][j] = 1; } else { map[i][j] = map[i - 1][j] + map[i][j - 1]; } } } System.out.println(map[n - 1][n - 1]); } } static class problem_9 { problem_9() { int n = sc.nextInt(); int a[] = new int[n], b[] = new int[n - 1], c[] = new int[n - 2]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<n-1;i++) { b[i]=sc.nextInt(); } for(int i=0;i<n-2;i++) { c[i]=sc.nextInt(); } Arrays.sort(a); Arrays.sort(b); Arrays.sort(c); for(int i=0;i<n;i++) { if(i==n-1) { System.out.printf("%d\n",a[i]); break; } if(a[i]==b[i]) { continue; } System.out.printf("%d\n",a[i]); break; } for(int i=0;i<n-1;i++) { if(i==n-2) { System.out.printf("%d\n",b[i]); break; } if(b[i]==c[i]) { continue; } System.out.printf("%d\n",b[i]); break; } } } }
Java
["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"]
2 seconds
["8\n123", "1\n3"]
NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Java 8
standard input
[ "data structures", "implementation", "sortings" ]
1985566215ea5a7f22ef729bac7205ed
The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
1,100
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
standard output
PASSED
e4d743a329c55e4ebcd4c941a0ae9ee8
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Minimise { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); StringBuilder res = new StringBuilder(); while (t-- > 0) { int c = in.nextInt(); int sum = in.nextInt(); int rem = sum%c; int[] a = new int[c]; for (int i=0;i<c;i++) a[i] = sum/c; for (int i=0;i<rem;i++) a[i] += 1; int sol = 0; for (int i=0;i<c;i++) sol = sol + a[i]*a[i]; res.append(sol).append("\n"); } System.out.println(res); } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
a1a12310693925fb193d8f29f6e36d5a
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Heating { InputStream is; PrintWriter pw; String INPUT = ""; long L_INF = (1L << 60L); void solve() { int n, m,c=ni(),sum=ni(); long div = sum/c; long x = sum%c; pw.println((c-x)*(div*div)+x*(div+1)*(div+1)); } void run() throws Exception { // is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); is = System.in; pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = ni(); while (t-- > 0) solve(); pw.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Heating().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
9165e3e88b4ea532abc28b449d68f196
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class template { public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("fpot.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Task solver = new Task(); int t = scan.nextInt(); //int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter pw) { int a =sc.nextInt(); int b = sc.nextInt(); long sum = 0; if(a>b){ pw.println(b);return; } for(int i=0;i<a;){ int temp = b/a; sum+=temp*temp; b-=temp; a--; } pw.println(sum); } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
6b6aeed89c443f5b880e83071dec1bff
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.*; import java.util.Scanner; @SuppressWarnings("Duplicates") public class ProblemA { public static void main(String[] args) throws IOException{ //Reader sc = new Reader(); PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tests = sc.nextInt(); for (int test = 0; test < tests; test++) { long c = sc.nextLong(); long sum = sc.nextLong(); long div = sum/c; long mod = sum%c; long sol = ((div+1)*(div+1)*mod)+(div*div*(c-mod)); pw.println(sol); } pw.flush(); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
d2e5c69aa41f4463f328582646c6fffe
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.*; public class First { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t > 0) { int c = s.nextInt(); int sum = s.nextInt(); int[] a = new int[c]; int m = sum/c ; int n = sum%c ; for(int i = 0; i < c;i++) { a[i] = m; } for(int i = 0; i < n;i++) { a[i] = a[i] + 1; } int ans = 0; for(int i = 0; i < c;i++) { ans = ans + a[i]*a[i]; } System.out.println(ans); t--; } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
38f1865c21c19f9db2d352d39fca46a2
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); for(int i=0;i<n;i++) { int c,sum,x=0,y,k; c = s.nextInt(); sum = s.nextInt(); int ans; if(c>=sum) ans=sum; else { ans = sum/c; y=ans; k=c; if(sum%c > 0) { x=sum%c; c-=x; } ans = c*(int)Math.pow(ans, 2); k-=c; //System.out.println(k); if(k>0) ans += k*(int)Math.pow((y+1),2); } System.out.println(ans); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
c1c577964220421a1433dbd73fab6118
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
/* *created by Kraken on 28-05-2020 at 14:59 */ import java.util.*; import java.io.*; public class A { public static void main(String[] args) { FastReader sc = new FastReader(); int q = sc.nextInt(); while (q-- > 0) { int c = sc.nextInt(); int sum = sc.nextInt(); long res = 0; long qu = sum / c; long re = sum % c; c -= re; res += c * (qu * qu); res += re * ((qu + 1) * (qu + 1)); System.out.println(res); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
538f47eab5d18bffd22cf8068d8d07c8
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.*; public class heating { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=0;i<n;i++) { int a = sc.nextInt(); int b = sc.nextInt(); if(a==1 || b==1) { System.out.println(b*b); continue; } if(b%a == 0) { System.out.println((b*b)/a); continue; } else { int val = (int) Math.ceil((double)b/a); int res = ((b%a) * val * val) + ((a-(b%a))*(val-1)*(val-1)); System.out.println(res); continue; } } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
ab8f67ca71a8e631f0f848e7d5c4c596
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; public class Main { static BufferedReader input = new BufferedReader( new InputStreamReader(System.in) ); public static void main(String[] args) throws IOException { short tests = Short.parseShort(input.readLine()); while (tests-- > 0) { String[] x = input.readLine().split(" "); short radiators = Short.parseShort(x[0]); short sections = Short.parseShort(x[1]); System.out.println(solve(radiators, sections)); } } public static int solve(short r, short s) { int remain = s % r; int div = s / r; return (int) (remain * Math.pow(div + 1, 2) + (r - remain) * Math.pow(div, 2)); } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
9cf052606a8f81cfb750e09fa69d635e
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Collections; import java.util.*; public class Heaters{ public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int N = sc.nextInt(); int [][] heaters = new int [N][2]; for (int i = 0; i < N; i++) { heaters[i][0] = sc.nextInt(); heaters[i][1] = sc.nextInt(); } for (int i = 0; i < N; i++) { int max = heaters[i][0]; double min_cost = Double.MAX_VALUE; while (max > 0) { int num = heaters[i][1] / max; int remainder = heaters[i][1] - max * num; double result = Math.pow(num + 1, 2) * remainder + Math.pow(num, 2) * (max - remainder); if (result < min_cost) { min_cost = result; } max--; } out.println((int) min_cost); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
37bd68eb9a1f7a1a2f7d06a5c76ea145
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.*; public class CF { public static void main(String[] args) { Scanner input=new Scanner(System.in); long t=input.nextLong(); while(t-->0){ long c=input.nextLong(),sum=input.nextLong(); System.out.println((sum/c)*(sum/c)*c + 2*(sum/c)*(sum%c)+(sum%c)); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
59ac538177a335265815f3df8d07604f
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int roomCount = scanner.nextInt(); for (int r = 1; r <= roomCount; r++) { int maxCount = scanner.nextInt(); int sum = scanner.nextInt(); int[] count = new int[maxCount]; int med = sum / maxCount; for (int i = 0; i < count.length; i++) { count[i] = med; } int remainder = sum % maxCount; for (int i = 0; i < remainder; i++) { count[i]++; } int result = 0; for (int i = 0; i < count.length; i++) { result += count[i] * count[i]; } System.out.println(result); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
b8071bc2ea981dc86334c35f678278d7
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { long c = sc.nextLong(); long sum = sc.nextLong(); long ans = (sum/c + 1)*(sum/c + 1)*(sum % c) + (c - sum%c)*(sum/c)*(sum/c); System.out.println(ans); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
f2215b9a2715b60715086ccc0f7fe2a1
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner SC = new Scanner(System.in); int t = SC.nextInt(); double sum, tmp; int c, cost; for(int i=0; i<t; i++){ c=SC.nextInt(); sum=SC.nextInt(); cost=0; while(c!=0){ tmp=(int)Math.ceil((double)(sum/c)); sum-=tmp; c--; cost+=Math.pow(tmp, 2); } System.out.println(cost); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
9916dffb4951ccf24252719b9c6eb668
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
256 megabytes
import java.util.*; public class Solution { public static void main(String args[]) { Scanner s = new Scanner(System.in); int n = s.nextInt(); for(int i = 0 ; i < n ; i++) { int a = s.nextInt(); int b = s.nextInt(); int arr[] = new int[a]; int x = 0; while(b > 0) { arr[x % a]++; b--; x++; } long ans = 0; for(int j = 0 ; j < a ; j++) { ans += Math.pow(arr[j], 2); } System.out.println(ans); } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output
PASSED
06f2e97deb3714e282bb3ece90b7e48a
train_003.jsonl
1574862600
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); long[] c = new long[n]; long[] sum = new long[n]; for (int i = 0; i < n; i++) { c[i] = in.nextLong(); sum[i] = in.nextLong(); } for (int i = 0; i < n; i++) { long[] a = new long[(int) c[i]]; for (int j = 0; j < a.length; j++) { a[j] = sum[i] / c[i]; } long remainder = sum[i] % c[i]; long ans = 0; for (int j = 0; j < remainder; j++) { a[j]++; } for (int j = 0; j < a.length; j++) { ans += a[j] * a[j]; } out.println(ans); } } } }
Java
["4\n1 10000\n10000 1\n2 6\n4 6"]
1 second
["100000000\n1\n18\n10"]
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.
Java 11
standard input
[ "math" ]
0ec973bf4ad209de9731818c75469541
The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.
1,000
For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.
standard output