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
sequencelengths
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
56b2bca7b6b4ab315de2181e081cf66e
train_000.jsonl
1291046400
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β€” one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * * * 3 2 3 5 * -2 -1 4 -1 2 7 3 * * * @author pttrung */ public class D { public static long MOD = 1000000007; public static int[][][] dp; public static int[] x = {-1, -1}; public static int[] y = {1, -1}; 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); int n = in.nextInt(); int m = in.nextInt(); if ((n % 2 != 0 && m % 2 != 0) || (n == 1 && m > 2) || (m == 1 && n > 2)) { out.println(1); out.println(n + " " + m + " " + 1 + " " + 1); int x = 1; int y = 1; int add = 1; for (int i = 0; i < n * m; i++) { out.println(x + " " + y); y += add; if (y > m || y < 1) { y -= add; add = -add; x++; } } out.println(1 + " " + 1); } else if (n % 2 == 0) { out.println(0); int x = 1; int y = 1; int add = 1; while (x <= n) { out.println(x + " " + y); y += add; if (y > m || y < 2) { y -= add; add = -add; x++; } } boolean ok = false; x--; if (y != 1) { ok = true; y--; } while (x > 0) { if (ok) { out.println(x + " " + y); } ok = true; x--; } } else if (m % 2 == 0) { out.println(0); int x = 1; int y = 1; int add = 1; while (y <= m) { out.println(x + " " + y); x += add; if (x > n || x < 2) { x -= add; add = -add; y++; } } boolean ok = false; if (x != 1) { ok = true; x--; } y--; while (y > 0) { if (ok) { out.println(x + " " + y); } y--; ok = true; } } out.close(); } public static int cal(int have, int i, int j, int k, int[][] map) { if (dp[have][i][j] != -2) { return dp[have][i][j]; } int val = have + map[i][j]; if (i == 0) { if (val % (k + 1) == 0) { return dp[have][i][j] = val; } return dp[have][i][j] = -1; } int result = -1; for (int z = 0; z < 2; z++) { int a = x[z] + i; int b = y[z] + j; if (b >= 0 && b < map[0].length) { int tmp = cal(val, a, b, k, map); result = Math.max(result, tmp); } } return dp[have][i][j] = result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { int[] data; FT(int n) { data = new int[n]; } public void update(int index, int value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public int get(int index) { int result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["2 2", "3 3"]
2 seconds
["0\n1 1\n1 2\n2 2\n2 1\n1 1", "1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a98622d5b6d6d139df90b6fee3baa544
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100, 2 ≀  n Β· m) β€” the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
2,000
On the first line output integer k β€” the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each β€” the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
standard output
PASSED
ccad61507afb6d965f948571eb3a8f9a
train_000.jsonl
1291046400
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β€” one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(), m = nextInt(); if(n * m == 2) { writer.println(0); writer.println("1 1"); writer.println(n + " " + m); writer.println("1 1"); } else if(n * m % 2 == 1) { writer.println(1); writer.println(String.format("%d %d 1 1", n, m)); for(int row = 1; row <= n; row++) { for(int column = row % 2 == 1 ? 1 : m; column > 0 && column <= m; column += row % 2 == 1 ? 1 : -1) { writer.println(row + " " + column); } } writer.println("1 1"); } else if(n == 1 || m == 1) { writer.println(1); writer.println(String.format("%d %d 1 1", n, m)); for(int i = 0; i < n * m; i++) { writer.println(String.format("%d %d", i % n + 1, i % m + 1)); } writer.println("1 1"); } else if(n % 2 == 0) { writer.println(0); writer.println("1 1"); for(int row = 1; row <= n; row++) { for(int column = row % 2 == 1 ? 2 : m; column > 1 && column <= m; column += row % 2 == 1 ? 1 : -1) { writer.println(row + " " + column); } } for(int row = n; row > 0; row--) { writer.println(row + " 1"); } } else {//m % 2 == 0 writer.println(0); writer.println("1 1"); for(int column = 1; column <= m; column++) { for(int row = column % 2 == 1 ? 2 : n; row > 1 && row <= n; row += column % 2 == 1 ? 1 : -1) { writer.println(row + " " + column); } } for(int column = m; column > 0; column--) { writer.println("1 " + column); } } writer.close(); } public static void main(String[] args) throws IOException { // new D().test(); new D().solve(); } }
Java
["2 2", "3 3"]
2 seconds
["0\n1 1\n1 2\n2 2\n2 1\n1 1", "1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a98622d5b6d6d139df90b6fee3baa544
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100, 2 ≀  n Β· m) β€” the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
2,000
On the first line output integer k β€” the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each β€” the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
standard output
PASSED
7196dea8fa8369a74e6c2fc42b90b567
train_000.jsonl
1291046400
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β€” one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); StringTokenizer str=new StringTokenizer(r.readLine()); int n=Integer.parseInt(str.nextToken()); int m=Integer.parseInt(str.nextToken()); if(n==1&&m==2) { pr.println(0); pr.println("1 1"); pr.println("1 2"); pr.println("1 1"); } else if(n==2&&m==1) { pr.println(0); pr.println("1 1"); pr.println("2 1"); pr.println("1 1"); }else if(n%2==1&&m%2==1) { pr.println(1); pr.println(n+" "+m+" 1 1"); int i=1,j=1; int flag=0; while(i!=n||j!=m) { pr.println(i+" "+j); if(flag==0) { if(i<n) { i++; } else if(i==n) { j++; flag=1; } } else { if(i>1) { i--; } else if(i==1) { j++; flag=0; } } } pr.println(i+" "+j); pr.println("1 1"); } else if(n%2==0||m%2==0) { if(n==1||m==1) { pr.println(1); pr.println(n +" "+m+" 1 1"); if(n==1) { for(int i=1;i<=m;i++) { pr.println(1+" "+i); } pr.println("1 1"); } else { for(int i=1;i<=n;i++) { pr.println(i+" "+1); } pr.println("1 1"); } } else { pr.println(0); if(n%2==0) { int i=1,j=1; int flag=0; while(i!=n||j!=2) { pr.println(i+" "+j); if(flag==0) { if(j<m) { j++; } else if(j==m) { i++; flag=1; } } else { if(j>2) { j--; } else if(j==2) { i++; flag=0; } } } pr.println(i+" "+j); for(int k=n;k>=1;k--) { pr.println(k+" "+1); } } else { int i=1,j=1; int flag=0; while(i!=2||j!=m) { pr.println(i+" "+j); if(flag==0) { if(i<n) { i++; } else if(i==n) { j++; flag=1; } } else { if(i>2) { i--; } else if(i==2) { j++; flag=0; } } } pr.println(i+" "+j); for(int k=m;k>=1;k--) { pr.println(1+" "+k); } } } } pr.flush(); pr.close(); } }
Java
["2 2", "3 3"]
2 seconds
["0\n1 1\n1 2\n2 2\n2 1\n1 1", "1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a98622d5b6d6d139df90b6fee3baa544
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100, 2 ≀  n Β· m) β€” the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
2,000
On the first line output integer k β€” the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each β€” the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
standard output
PASSED
912009c069e85e2a00d05e24f9aa63a3
train_000.jsonl
1291046400
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β€” one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final long INF = Long.MAX_VALUE; private final double PI = Math.acos(-1.0); private final int SIZEN = (int)(1e5); private final int MOD = (int)(1e9 + 7); private final long MODH = 10000000007L, BASE = 10007; private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; private ArrayList<Integer>[] edge; public void foo() { int n = scan.nextInt(); int m = scan.nextInt(); if(1 == n) { if(2 == m) { out.println(0); } else { out.println(1); out.println("1 " + m + " 1 1"); } for(int i = 1;i <= m;++i) { out.println("1 " + i); } out.println("1 1"); } else if(1 == m) { if(2 == n) { out.println(0); } else { out.println(1); out.println(n + " 1 1 1"); } for(int i = 1;i <= n;++i) { out.println(i + " 1"); } out.print("1 1"); } else { if(0 == n * m % 2) { out.println(0); } else { out.println(1); out.println(n + " 1 1 1"); } for(int i = 1;i <= m;++i) { out.println("1 " + i); } if(0 == n % 2) { for(int i = 2;i <= n;++i) { out.println(i + " " + m); } for(int i = n;i >= 2;--i) { if(0 == (n - i) % 2) { for(int j = m - 1;j >= 1;--j) { out.println(i + " " + j); } } else { for(int j = 1;j <= m - 1;++j) { out.println(i + " " + j); } } } } else { for(int i = m;i >= 1;--i) { if(0 == (m - i) % 2) { for(int j = 2;j <= n;++j) { out.println(j + " " + i); } } else { for(int j = n;j >= 2;--j) { out.println(j + " " + i); } } } } out.println("1 1"); } } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * 1---Get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } /** * 2---Get the distance from a point to a line * @param x1 the x coordinate of one endpoint of the line * @param y1 the y coordinate of one endpoint of the line * @param x2 the x coordinate of the other endpoint of the line * @param y2 the y coordinate of the other endpoint of the line * @param x the x coordinate of the point * @param y the x coordinate of the point * @return the distance from a point to a line */ public double getDist(long x1, long y1, long x2, long y2, long x, long y) { long a = y2 - y1; long b = x1 - x2; long c = y1 * (x2 - x1) - x1 * (y2 - y1); return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } /** * 3---Get the distance from one point to a segment (not a line) * @param x1 the x coordinate of one endpoint of the segment * @param y1 the y coordinate of one endpoint of the segment * @param x2 the x coordinate of the other endpoint of the segment * @param y2 the y coordinate of the other endpoint of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return the distance from one point to a segment (not a line) */ public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y) { double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1); if(cross <= 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); if(cross >= d) { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } double r = cross / d; double px = x1 + (x2 - x1) * r; double py = y1 + (y2 - y1) * r; return (x - px) * (x - px) + (y - py) * (y - py); } /** * 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } /** * 5---Get the hash code of a String * @param s: input string * @return hash code */ public long hash(String s) { long key = 0, t = 1; for(int i = 0;i < s.length();++i) { key = (key + s.charAt(i) * t) % MODH; t = t * BASE % MODH; } return key; } class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.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 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 & 15; 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 & 15) * m; c = read(); } } return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["2 2", "3 3"]
2 seconds
["0\n1 1\n1 2\n2 2\n2 1\n1 1", "1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a98622d5b6d6d139df90b6fee3baa544
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100, 2 ≀  n Β· m) β€” the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
2,000
On the first line output integer k β€” the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each β€” the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
standard output
PASSED
826952c3c456e2b2c267b88077801352
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; 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 Main(), "persefone", 1 << 28).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int n = in.nextInt(); int m = 100001; List<Integer>[] listOfVotersGroupByPartySupport = new ArrayList[m + 1]; for (int i = 1; i <= m; i++) listOfVotersGroupByPartySupport[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { int party = in.nextInt() + 1; int cost = in.nextInt(); if (listOfVotersGroupByPartySupport[party] == null) listOfVotersGroupByPartySupport[party] = new ArrayList<>(); listOfVotersGroupByPartySupport[party].add(cost); } int[][] arrayOfVotersGroupByPartySupport = new int[m + 1][]; for (int i = 1; i <= m; i++) { if (listOfVotersGroupByPartySupport[i] != null) { int size = listOfVotersGroupByPartySupport[i].size(); arrayOfVotersGroupByPartySupport[i] = listOfVotersGroupByPartySupport[i].stream().mapToInt(Integer::intValue).toArray(); } } for (int i = 1; i <= m; i++) { if (arrayOfVotersGroupByPartySupport[i] != null) { Arrays.sort(arrayOfVotersGroupByPartySupport[i]); } } /* do ternary search for unimodal function */ int low = 1, high = n, mid = 0; while (low < high) { mid = low + high >> 1; if (getCost(arrayOfVotersGroupByPartySupport, n, m, mid) < getCost(arrayOfVotersGroupByPartySupport, n, m, mid + 1)) high = mid; else low = mid + 1; } printf(getCost(arrayOfVotersGroupByPartySupport, n, m, low)); } long getCost(int[][] arr, int n, int m, int finalVotes) { int needed = finalVotes - arr[1].length; if (needed < 0) return 0; long cost = 0; int[] remains = new int[n]; int start = 0; for (int i = 2; i <= m; i++) { int size = arr[i].length; for (int j = 0; j < size; j++) { if (j + finalVotes <= size) { needed--; cost += arr[i][j]; continue; } remains[start++] = arr[i][j]; } } if (needed > 0) { Arrays.sort(remains, 0, start); for (int i = 0; i < needed; i++) { cost += remains[i]; } } return cost; } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } 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; } 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(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()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
4457ac915c97051a6fa69892c74c4e20
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.util.List; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { long seed = 0xdead; int n = in.nextInt(); seed = seed * 57L + n; int c0 = 0; ArrayList<Integer>[] adds = new ArrayList[n + 1]; for (int i = 0; i < adds.length; ++i) adds[i] = new ArrayList<>(); int[] who = new int[n]; int[] costs = new int[n]; ArrayList<ii>[] members = new ArrayList[218 * 1000]; for (int i = 0; i < members.length; ++i) members[i] = new ArrayList<>(); for (int i = 0; i < n; ++i) { who[i] = in.nextInt(); seed = seed * 57L + who[i]; costs[i] = in.nextInt(); seed = seed * 57L + costs[i]; if (who[i] == 0) ++c0; else { members[who[i]].add(new ii(costs[i], i)); } } Random random = new Random(seed); for (int i = 0; i < members.length; ++i) { if (members[i].isEmpty()) continue; adds[members[i].size()].add(i); Collections.shuffle(members[i], random); Collections.sort(members[i]); Collections.reverse(members[i]); } int h = 2; while (h <= 57000) h *= 2; SegmentTreeAddSum sums = new SegmentTreeAddSum(h); SegmentTreeAddSum counts = new SegmentTreeAddSum(h); for (int i = 0; i < n; ++i) { if (who[i] != 0) { sums.add(costs[i] + 1, costs[i]); counts.add(costs[i] + 1, 1); } } counts.add(49000, 10000000); long res = (long) 1E18; long cost = 0; int excess = c0; ArrayList<Integer> front = new ArrayList<>(); for (int i = n; i > 0; --i) { for (int x : adds[i]) front.add(x); for (int x : front) { int el = members[x].get(i - 1).second; cost += costs[el]; ++excess; sums.add(costs[el] + 1, -costs[el]); counts.add(costs[el] + 1, -1); } long cur = cost; int need = i - excess; if (need > 0) { int ind = counts.lower_bound(1, 50000, need); // Should fit in int. int sum = ind <= 1 ? 0 : sums.sum(1, ind - 1); int cnt = ind <= 1 ? 0 : counts.sum(1, ind - 1); cur += sum; cur += (long) (need - cnt) * (long) (ind - 1); } if (cur < res) res = cur; } out.printLine(res); } } class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) return -1; } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } 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 ii implements Comparable<ii> { public int first; public int second; public ii() { } public ii(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ii ii = (ii) o; if (first != ii.first) return false; if (second != ii.second) return false; return true; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public int compareTo(ii o) { if (first != o.first) { return first < o.first ? -1 : 1; } if (second != o.second) { return second < o.second ? -1 : 1; } return 0; } } class SegmentTreeAddSum { final int[] s; final int n; public SegmentTreeAddSum(int n) { this.n = n; s = new int[4 * n]; buildTree(1, 0, n - 1); } void buildTree(int node, int left, int right) { if (left != right) { int mid = (left + right) >> 1; buildTree(node * 2, left, mid); buildTree(node * 2 + 1, mid + 1, right); s[node] = s[node * 2] + s[node * 2 + 1]; } } public void add(int i, int value) { add(i, value, 1, 0, n - 1); } void add(int i, int value, int node, int left, int right) { if (left == right) { s[node] += value; return; } int mid = (left + right) >> 1; if (i <= mid) add(i, value, node * 2, left, mid); else add(i, value, node * 2 + 1, mid + 1, right); s[node] = s[node * 2] + s[node * 2 + 1]; } public int sum(int a, int b) { return sum(a, b, 1, 0, n - 1); } int sum(int a, int b, int node, int left, int right) { if (left >= a && right <= b) return s[node]; int mid = (left + right) >> 1; int res = 0; if (a <= mid) res += sum(a, b, node * 2, left, mid); if (b > mid) res += sum(a, b, node * 2 + 1, mid + 1, right); return res; } // Returns min(p | p<=b && sum[a,p]>=sum) public int lower_bound(int a, int b, int sum) { return lower_bound(a, b, sum, 1, 0, n - 1); } int lower_bound(int a, int b, int sum, int node, int left, int right) { if (left > b || right < a) return ~0; if (left >= a && right <= b && s[node] < sum) return ~s[node]; if (left == right) return left; int mid = (left + right) >> 1; int res1 = lower_bound(a, b, sum, node * 2, left, mid); if (res1 >= 0) return res1; res1 = ~res1; int res2 = lower_bound(a, b, sum - res1, node * 2 + 1, mid + 1, right); if (res2 >= 0) return res2; res2 = ~res2; return ~(res1 + res2); } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
3863a72e9f8b925dfb535c22e3a614d8
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import java.util.logging.Level; import java.util.logging.Logger; // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display //<editor-fold defaultstate="collapsed" desc="Main"> public class Main { private void run() { Locale.setDefault(Locale.US); boolean oj = true; try { oj = System.getProperty("MYLOCAL") == null; } catch (Exception e) { } if (oj) { sc = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } else { try { sc = new FastScanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException e) { MLE(); } } Solver s = new Solver(); s.sc = sc; s.out = out; s.solve(); if (!oj) { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); } out.flush(); } private void show(int[] arr) { for (int v : arr) { err.print(" " + v); } err.println(); } public static void MLE() { int[][] arr = new int[1024 * 1024][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[1024 * 1024]; } } public static void main(String[] args) { new Main().run(); } long timeBegin = System.currentTimeMillis(); FastScanner sc; PrintWriter out; PrintStream err = System.err; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="FastScanner"> class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader reader) { br = new BufferedReader(reader); st = new StringTokenizer(""); } String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException ex) { Main.MLE(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } //</editor-fold> class Solver { FastScanner sc; PrintWriter out; PrintStream err = System.err; int n; ArrayList<Integer>[] cost = new ArrayList[(int) 1e5 + 1]; { for (int i = 0; i < cost.length; i++) { cost[i] = new ArrayList<>(); } } int f(int cntOf0) { int ans = 0; ArrayList<Integer> ts = new ArrayList<>(); int cntTake = 0; for( int id = 1; id < cost.length; ++id ){ for( int i = 0; i < cost[id].size(); ++i ){ if( cost[id].size()-i < cntOf0 ){ ts.add( cost[id].get(i) ); //err.println( cntOf0 + " " + cost[id].get(i) ); } else{ ans += cost[id].get(i); ++cntTake; } } } if( cntTake + ts.size() + cost[0].size() != n ) Main.MLE(); Collections.sort(ts); int need = cntOf0 - cost[0].size() - cntTake; for( int ind = 0; 0 < need; --need, ++ind ){ ans += ts.get(ind); } return ans; } void solve() { n = sc.nextInt(); for (int i = 0; i < n; i++) { int idCand = sc.nextInt(); int money = sc.nextInt(); cost[idCand].add(money); } for (int i = 0; i < cost.length; i++) { Collections.sort(cost[i]); } int l = cost[0].size(), r = n; while ( l + 10 < r ) { int m1 = l + (r - l) / 3, m2 = r - (r - l) / 3; if (f((int)m1) > f((int)m2)) { l = m1; } else { r = m2; } } int ans = Integer.MAX_VALUE; for( int i = l; i <= r; ++i ){ ans = min( ans, f(i) ); // err.printf( "%d %d\n", i, f(i) ); // err.printf( "%d %d\n", i, f(i) ); // err.println(); } out.println( ans ); } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
b41641cf66543bf3c4e2639607374455
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.io.*; import java.util.*; public class Main { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(), m = 0; int[] from = new int[n], to = new int[n]; for(int i = 0; i < n; i++) { from[i] = scn.nextInt(); to[i] = scn.nextInt(); m = Math.max(m, from[i] + 1); } int[][] arr = packD(m, from, to); for(int i = 0; i < m; i++) { Arrays.sort(arr[i]); } int[] table = new int[n]; int lo = Math.max(1, arr[0].length), hi = n; while(lo < hi) { int mid = (lo + hi) >> 1; if(f(mid, m, arr, table) > f(mid + 1, m, arr, table)) { lo = mid + 1; } else { hi = mid; } } long ans = f(hi, m, arr, table); out.println(ans); } long f(int w, int m, int[][] arr, int[] table) { int need = w - arr[0].length; int pos = 0; long rv = 0; for(int i = 1; i < m; i++) { for(int j = 0; j <= arr[i].length - w; j++) { need--; rv += arr[i][j]; } for(int j = Math.max(0, arr[i].length - w + 1); j < arr[i].length; j++) { table[pos++] = arr[i][j]; } } int q = 0; Arrays.sort(table, 0, pos); while(need-- > 0) { rv += table[q++]; } return rv; } int[][] packD(int n, int[] from, int[] to) { n++; int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; } return g; } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new Main().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
12e2bfa8881b30c73a938bb4756bbe2f
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.util.LinkedList; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.AbstractSequentialList; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.OutputStream; import java.util.Iterator; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Arrays; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.Comparator; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int[] vote = new int[count]; int[] bribe = new int[count]; IOUtils.readIntArrays(in, vote, bribe); IntList[] voters = new IntList[100001]; for (int i = 0; i <= 100000; i++) { voters[i] = new IntArrayList(); } for (int i = 0; i < count; i++) { voters[vote[i]].add(i); } LinkedList<IntList> candidates = new LinkedList<>(); for (int i = 0; i <= 100000; i++) { if (voters[i].size() != 0) { voters[i].inPlaceSort(new IntComparator() { @Override public int compare(int first, int second) { return bribe[second] - bribe[first]; } }); candidates.add(voters[i]); } } int curVotes = count; int curCost = (int) ArrayUtils.sumArray(bribe); int answer = curCost; Heap freeVoters = new Heap(count, 10001 ); for (int i = 0; i < count - 1; i++) { for (Iterator<IntList> iterator = candidates.iterator(); iterator.hasNext();) { IntList current = iterator.next(); if (current.size() <= i) { iterator.remove(); } else { curVotes--; curCost -= bribe[current.get(i)]; freeVoters.add(bribe[current.get(i)]); } } while (curVotes < i + 2) { curCost += freeVoters.poll(); curVotes++; } answer = Math.min(answer, curCost); } out.printLine(answer); } } 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 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 OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } abstract class IntList extends IntCollection implements Comparable<IntList> { private static final int INSERTION_THRESHOLD = 16; public abstract int get(int index); public abstract void set(int index, int value); public IntIterator iterator() { return new IntIterator() { private int size = size(); private int index = 0; public int value() throws NoSuchElementException { if (!isValid()) throw new NoSuchElementException(); return get(index); } public void advance() throws NoSuchElementException { if (!isValid()) throw new NoSuchElementException(); index++; } public boolean isValid() { return index < size; } }; } private void swap(int first, int second) { if (first == second) return; int temp = get(first); set(first, get(second)); set(second, temp); } public IntSortedList inPlaceSort(IntComparator comparator) { quickSort(0, size() - 1, (Integer.bitCount(Integer.highestOneBit(size()) - 1) * 5) >> 1, comparator); return new IntSortedArray(this, comparator); } private void quickSort(int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(from, to, comparator); return; } if (remaining == 0) { heapSort(from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = get(pivotIndex); swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(get(i), pivot); if (value < 0) swap(storeIndex++, i); else if (value == 0) swap(--equalIndex, i--); } quickSort(from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) swap(storeIndex++, i); quickSort(storeIndex, to, remaining, comparator); } private void heapSort(int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) siftDown(i, to, comparator, from); for (int i = to; i > from; i--) { swap(from, i); siftDown(from, i - 1, comparator, from); } } private void siftDown(int start, int end, IntComparator comparator, int delta) { int value = get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) return; int childValue = get(child); if (child + 1 <= end) { int otherValue = get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) return; swap(start, child); start = child; } } private void insertionSort(int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(get(j), value) <= 0) break; swap(j, j + 1); } } } public int hashCode() { int hashCode = 1; for (IntIterator i = iterator(); i.isValid(); i.advance()) hashCode = 31 * hashCode + i.value(); return hashCode; } public boolean equals(Object obj) { if (!(obj instanceof IntList)) return false; IntList list = (IntList)obj; if (list.size() != size()) return false; IntIterator i = iterator(); IntIterator j = list.iterator(); while (i.isValid()) { if (i.value() != j.value()) return false; i.advance(); j.advance(); } return true; } public int compareTo(IntList o) { IntIterator i = iterator(); IntIterator j = o.iterator(); while (true) { if (i.isValid()) { if (j.isValid()) { if (i.value() != j.value()) { if (i.value() < j.value()) return -1; else return 1; } } else return 1; } else { if (j.isValid()) return -1; else return 0; } i.advance(); j.advance(); } } } class IntArrayList extends IntList { private int[] array; private int size; public IntArrayList() { this(10); } public IntArrayList(int capacity) { array = new int[capacity]; } public IntArrayList(IntList list) { this(list.size()); addAll(list); } public int get(int index) { if (index >= size) throw new IndexOutOfBoundsException(); return array[index]; } public void set(int index, int value) { if (index >= size) throw new IndexOutOfBoundsException(); array[index] = value; } public int size() { return size; } public void add(int value) { ensureCapacity(size + 1); array[size++] = value; } public void ensureCapacity(int newCapacity) { if (newCapacity > array.length) { int[] newArray = new int[Math.max(newCapacity, array.length << 1)]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } } } abstract class IntCollection { public abstract IntIterator iterator(); public abstract int size(); public abstract void add(int value); public void addAll(IntCollection values) { for (IntIterator it = values.iterator(); it.isValid(); it.advance()) { add(it.value()); } } } abstract class IntSortedList extends IntList { protected final IntComparator comparator; protected IntSortedList(IntComparator comparator) { this.comparator = comparator; } public void set(int index, int value) { throw new UnsupportedOperationException(); } public void add(int value) { throw new UnsupportedOperationException(); } public IntSortedList inPlaceSort(IntComparator comparator) { if (comparator == this.comparator) return this; throw new UnsupportedOperationException(); } protected void ensureSorted() { int size = size(); if (size == 0) return; int last = get(0); for (int i = 1; i < size; i++) { int current = get(i); if (comparator.compare(last, current) > 0) throw new IllegalArgumentException(); last = current; } } } interface IntComparator { public static final IntComparator DEFAULT = new IntComparator() { public int compare(int first, int second) { if (first < second) return -1; if (first > second) return 1; return 0; } }; public int compare(int first, int second); } class ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } } class Heap { private IntComparator comparator; private int size = 0; private int[] elements; private int[] at; public Heap(int maxElement) { this(10, maxElement); } public Heap(IntComparator comparator, int maxElement) { this(10, comparator, maxElement); } public Heap(int capacity, int maxElement) { this(capacity, IntComparator.DEFAULT, maxElement); } public Heap(int capacity, IntComparator comparator, int maxElement) { this.comparator = comparator; elements = new int[capacity]; at = new int[maxElement]; Arrays.fill(at, -1); } public boolean isEmpty() { return size == 0; } public int add(int element) { ensureCapacity(size + 1); elements[size] = element; at[element] = size; shiftUp(size++); return at[element]; } public void shiftUp(int index) { // if (index < 0 || index >= size) // throw new IllegalArgumentException(); int value = elements[index]; while (index != 0) { int parent = (index - 1) >>> 1; int parentValue = elements[parent]; if (comparator.compare(parentValue, value) <= 0) { elements[index] = value; at[value] = index; return; } elements[index] = parentValue; at[parentValue] = index; index = parent; } elements[0] = value; at[value] = 0; } public void shiftDown(int index) { if (index < 0 || index >= size) throw new IllegalArgumentException(); while (true) { int child = (index << 1) + 1; if (child >= size) return; if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) child++; if (comparator.compare(elements[index], elements[child]) <= 0) return; swap(index, child); index = child; } } private void swap(int first, int second) { int temp = elements[first]; elements[first] = elements[second]; elements[second] = temp; at[elements[first]] = first; at[elements[second]] = second; } private void ensureCapacity(int size) { if (elements.length < size) { int[] oldElements = elements; elements = new int[Math.max(2 * elements.length, size)]; System.arraycopy(oldElements, 0, elements, 0, this.size); } } public int poll() { if (isEmpty()) throw new IndexOutOfBoundsException(); int result = elements[0]; at[result] = -1; if (size == 1) { size = 0; return result; } elements[0] = elements[--size]; at[elements[0]] = 0; shiftDown(0); return result; } } interface IntIterator { public int value() throws NoSuchElementException; /* * @throws NoSuchElementException only if iterator already invalid */ public void advance() throws NoSuchElementException; public boolean isValid(); } class IntSortedArray extends IntSortedList { private final int[] array; public IntSortedArray(int[] array) { this(array, IntComparator.DEFAULT); } public IntSortedArray(IntCollection collection) { this(collection, IntComparator.DEFAULT); } public IntSortedArray(int[] array, IntComparator comparator) { super(comparator); this.array = array; ensureSorted(); } public IntSortedArray(IntCollection collection, IntComparator comparator) { super(comparator); array = new int[collection.size()]; int i = 0; for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance()) array[i++] = iterator.value(); ensureSorted(); } public int get(int index) { return array[index]; } public int size() { return array.length; } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
814f1cfba15981d1ef846484125cb1e0
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.io.*; import java.util.*; public class C { public void solve() { int n = in.nextInt(); int our = 0; Map<Integer, List<Citizen>> voters = new HashMap<>(); List<Citizen> all = new ArrayList<>(); for (int i = 0; i < n; i++) { int a = in.nextInt(), b = in.nextInt(); if (a == 0) { our++; } else { if (!voters.containsKey(a)) { voters.put(a, new ArrayList<Citizen>()); } Citizen cur = new Citizen(b, a, i); voters.get(a).add(cur); all.add(cur); } } voters.put(Integer.MAX_VALUE, new ArrayList<Citizen>()); Collections.sort(all); int[] pos = new int[n]; SegmentTree tree = new SegmentTree(n); for (int i = 0; i < all.size(); i++) { pos[all.get(i).id] = i; tree.addValue(i, all.get(i).cost, 1); } int ans = Integer.MAX_VALUE; PriorityQueue<List<Citizen>> pq = new PriorityQueue<>(voters.size(), new Comparator<List<Citizen>>() { @Override public int compare(List<Citizen> o1, List<Citizen> o2) { return -Integer.compare(o1.size(), o2.size()); } }); for (int i : voters.keySet()) { List<Citizen> list = voters.get(i); Collections.sort(list); Collections.reverse(list); pq.add(list); } int curCost = 0; for (int toWin = n; toWin >= 1; toWin--) { while (pq.size() > 0 && pq.peek().size() >= toWin) { List<Citizen> list = pq.poll(); Citizen bribe = list.get(list.size() - 1); tree.addValue(pos[bribe.id], -bribe.cost, -1); our++; curCost += bribe.cost; list.remove(list.size() - 1); pq.add(list); } int needMore = Math.max(0, toWin - our); if (needMore <= tree.count[0]) { int add = tree.getFirstK(needMore); ans = Math.min(ans, curCost + add); } } out.println(ans); } class SegmentTree { int size; int[] sum, count; public SegmentTree(int n) { this.size = n; sum = new int[4 * n]; count = new int[4 * n]; } void addValue(int pos, int toSum, int toCount) { addValue(0, size, pos, toSum, toCount, 0); } private void addValue(int left, int right, int pos, int toSum, int toCount, int i) { if (left + 1 == right) { sum[i] += toSum; count[i] += toCount; return; } int mid = (left + right) >> 1; if (pos < mid) { addValue(left, mid, pos, toSum, toCount, 2 * i + 1); } else { addValue(mid, right, pos, toSum, toCount, 2 * i + 2); } sum[i] = sum[2 * i + 1] + sum[2 * i + 2]; count[i] = count[2 * i + 1] + count[2 * i + 2]; } int getFirstK(int k) { return getFirstK(0, size, k, 0); } private int getFirstK(int left, int right, int k, int i) { if (k == 0) { return 0; } if (left + 1 == right) { return sum[i]; } int mid = (left + right) >> 1; if (count[2 * i + 1] <= k) { return sum[2 * i + 1] + getFirstK(mid, right, k - count[2 * i + 1], 2 * i + 2); } else { return getFirstK(left, mid, k, 2 * i + 1); } } } class Citizen implements Comparable<Citizen> { int cost, vote, id; public Citizen(int cost, int vote, int id) { super(); this.cost = cost; this.vote = vote; this.id = id; } @Override public int compareTo(Citizen o) { return Integer.compare(cost, o.cost); } } FastScanner in; PrintWriter out; public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String name) { try { br = new BufferedReader(new FileReader(name)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } 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 C().run(); } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
2dcf6a78521efc73bf5805816e31c0fc
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author Rubanenko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Pair implements Comparable<Pair> { int num, cost; public int compareTo(Pair rhs) { return cost > rhs.cost ? -1 : cost == rhs.cost ? 0 : 1; } public Pair(int num, int cost) { this.num = num; this.cost = cost; } } Pair[] a; int[] b = new int[100333]; int n; boolean[] used; int get(int votes) { Arrays.fill(b, 0); Arrays.fill(used, false); int res = 0; for (int i = 0; i < n; i++) { if (a[i].num == 0) { b[0]++; used[i] = true; continue; } if (b[a[i].num] + 1 == votes) { res += a[i].cost; b[0]++; used[i] = true; } else { b[a[i].num]++; } } for (int i = n - 1; i >= 0 && b[0] < votes; i--) { if (used[i]) continue; res += a[i].cost; b[0]++; } return res; } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); a = new Pair[n]; used = new boolean[n]; for (int i = 0; i < n; i++) { int num = in.nextInt(); int cost = in.nextInt(); a[i] = new Pair(num, cost); } Arrays.sort(a); int l = 1; int r = n; while (l + 2 < r) { int m = (r - l) / 3; int c1 = l + m; int c2 = r - m; int f1 = get(c1); int f2 = get(c2); if (f1 < f2) r = c2; else l = c1; } int ans = get(l); l++; while (l <= r) { ans = Math.min(ans, get(l)); l++; } out.println(ans); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String nextLine() { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
81f3fc7ec4c4cf329330cb8ab019c2a1
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.io.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static class Voter implements Comparable<Voter> { int id, vote, cost; public Voter(int id, int vote, int cost) { this.id = id; this.vote = vote; this.cost = cost; } @Override public int compareTo(Voter o) { return Integer.compare(cost, o.cost); } } class Node { Node left, right; int l, r; int count, sum; public Node(int l, int r) { this.l = l; this.r = r; if (r - l > 1) { int mid = (l + r) >> 1; left = new Node(l, mid); right = new Node(mid, r); } } void add(int pos, int cost) { if (l == pos && pos + 1 == r) { count = 1; sum = cost; return; } (pos < left.r ? left : right).add(pos, cost); count = left.count + right.count; sum = left.sum + right.sum; } int get(int k) { if (k <= 0) { return 0; } if (count == k) { return sum; } if (k <= left.count) { return left.get(k); } else { return left.sum + right.get(k - left.count); } } } void solve() throws IOException { int n = nextInt(); List<Voter> all = new ArrayList<Voter>(n); List<Voter>[] byWho = new List[100000]; for (int i = 0; i < 100000; i++) { byWho[i] = new ArrayList<>(0); } int have = 0; for (int i = 0; i < n; i++) { int who = nextInt(); int cost = nextInt(); if (who == 0) { have++; } else { Voter tmp = new Voter(all.size(), who - 1, cost); all.add(tmp); byWho[who - 1].add(tmp); } } Collections.sort(all); int[] sortOrd = new int[n]; for (int i = 0; i < all.size(); i++) { sortOrd[all.get(i).id] = i; } Arrays.sort(byWho, new Comparator<List<Voter>>() { @Override public int compare(List<Voter> o1, List<Voter> o2) { return -Integer.compare(o1.size(), o2.size()); } }); for (int i = 0; i < 100000; i++) { Collections.sort(byWho[i]); } Node root = new Node(0, all.size()); int needPay = 0; int countNeedPay = 0; for (int i = 0; i < 100000; i++) { int from = Math.max(byWho[i].size() - Math.max(have - 1, 0), 0); for (int j = from; j < byWho[i].size(); j++) { Voter v = byWho[i].get(j); root.add(sortOrd[v.id], v.cost); } // System.err.println(byWho[i].size() + " " + from); for (int j = 0; j < from; j++) { needPay += byWho[i].get(j).cost; countNeedPay++; } } int ans; if (have == 0) { ans = Integer.MAX_VALUE; } else { ans = needPay; } for (int res = have + 1; res <= n; res++) { if (res != 1) { for (int j = 0; j < 100000; j++) { if (byWho[j].size() < res - 1) { break; } // System.err.println(res); Voter v = byWho[j].get(byWho[j].size() - res + 1); needPay -= v.cost; countNeedPay--; root.add(sortOrd[v.id], v.cost); } } // System.err.println(res + " " + countNeedPay); // System.err.println(root.count); ans = Math.min(ans, needPay + root.get(res - have - countNeedPay)); } out.println(ans); } C() 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 C(); } 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
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
1eee946071b75afd4629c4505b57d6e7
train_000.jsonl
1407690000
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
256 megabytes
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Voter { boolean bribed = false; boolean forced = false; int who; int cost; }; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Voter[] voters = new Voter[n]; for (int i = 0; i < n; ++i) { voters[i] = new Voter(); voters[i].who = in.nextInt(); voters[i].cost = in.nextInt(); } int numCandidate = 0; for (Voter voter : voters) { numCandidate = Math.max(numCandidate, voter.who + 1); } int[] cntVoter = new int[numCandidate]; for (Voter voter : voters) { ++cntVoter[voter.who]; } Arrays.sort(voters, (x, y) -> x.cost - y.cost); Voter[][] whoVote = new Voter[numCandidate][]; for (int i = 0; i < numCandidate; ++i) whoVote[i] = new Voter[cntVoter[i]]; Arrays.fill(cntVoter, 0); for (Voter voter : voters) { whoVote[voter.who][cntVoter[voter.who]++] = voter; } Arrays.sort(whoVote, 1, whoVote.length, (x, y) -> y.length - x.length); Voter[] nonzero = new Voter[n - cntVoter[0]]; int totalCost = 0; int ptr = 0; for (Voter voter : voters) { if (voter.who != 0) { nonzero[ptr++] = voter; voter.bribed = true; totalCost += voter.cost; } } int answer = Integer.MAX_VALUE; int upTo = 0; for (int votesForMe = n; votesForMe >= Math.max(1, cntVoter[0]); --votesForMe) { if (votesForMe < n) { while (ptr > 0 && nonzero[ptr - 1].forced) { --ptr; } if (ptr > 0) { nonzero[ptr - 1].bribed = false; totalCost -= nonzero[ptr - 1].cost; --ptr; } } while (upTo + 1 < whoVote.length && whoVote[upTo + 1].length >= votesForMe) { ++upTo; } for (int i = 1; i <= upTo; ++i) { Voter need = whoVote[i][whoVote[i].length - votesForMe]; need.forced = true; if (!need.bribed) { need.bribed = true; totalCost += need.cost; while (ptr > 0 && nonzero[ptr - 1].forced) { --ptr; } if (ptr > 0) { nonzero[ptr - 1].bribed = false; totalCost -= nonzero[ptr - 1].cost; --ptr; } } } answer = Math.min(answer, totalCost); } out.println(answer); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"]
2 seconds
["3", "2", "0"]
null
Java 8
standard input
[ "data structures", "ternary search" ]
2a0362376ddeaf3548d5419d1e70b4d3
First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).
2,100
Print one integer β€” smallest amount of money you need to spend to win the elections.
standard output
PASSED
7b6dcbcc2b2a45a606180c60f4d908e5
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; import java.awt.geom.*; public class Main{ public static void main(String[] args){ Scanner ir=new Scanner(System.in); int n=ir.nextInt(); double X=ir.nextDouble(),Y=ir.nextDouble(); double[] x=new double[n],y=new double[n]; double ma=0.0,mi=1e18; for(int i=0;i<n;i++){ x[i]=ir.nextDouble()-X; y[i]=ir.nextDouble()-Y; ma=ma=Math.max(ma,x[i]*x[i]+y[i]*y[i]); } for(int i=0;i<n;i++){ Line2D.Double l=new Line2D.Double(x[i],y[i],x[(i+1)%n],y[(i+1)%n]); mi=Math.min(mi,l.ptSegDistSq(0.0,0.0)); } System.out.printf("%.9f\n",(ma-mi)*Math.PI); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
f859550592c79ac32da1cc863f464b07
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; import java.awt.geom.*; import java.text.DecimalFormat; public class Main{ static PrintWriter out; static InputReader ir; static void solve(){ int n=ir.nextInt(); double[] co=new double[2]; for(int i=0;i<2;i++) co[i]=ir.nextDouble(); double[][] ps=new double[n][]; for(int i=0;i<n;i++){ ps[i]=new double[]{ir.nextDouble()-co[0],ir.nextDouble()-co[1]}; } Line2D.Double[] ls=new Line2D.Double[n]; for(int i=0;i<n;i++){ ls[i]=new Line2D.Double(ps[i][0],ps[i][1],ps[(i+1)%n][0],ps[(i+1)%n][1]); } double ma=0.0,mi=1e18; for(int i=0;i<n;i++){ double x=ps[i][0],y=ps[i][1]; ma=Math.max(ma,x*x+y*y); } for(int i=0;i<n;i++){ mi=Math.min(mi,ls[i].ptSegDistSq(0.0,0.0)); } DecimalFormat df=new DecimalFormat("0.0000000000"); out.println(df.format((ma-mi)*Math.PI)); } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public BigInteger nextBigInteger(){return new BigInteger(next());} public int[] nextIntArray(int n){ int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n){ long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
46eaefe0be0bc01c53a799dc6f5afe03
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); long px = in.nextLong(), py = in.nextLong(); long[] x = new long[n], y = new long[n]; double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; for (int i = 0; i < n; i++) { x[i] = in.nextLong() - px; y[i] = in.nextLong() - py; } int j = n - 1; for (int i = 0; i < n; j = i, i++) { double len = Math.sqrt(x[i] * x[i] + y[i] * y[i]); min = Math.min(min, len); max = Math.max(max, len); double lo = 0, hi = 1; for (int itr = 0; itr < 50; itr++) { double mid1 = (2 * lo + hi) / 3; double mid2 = (lo + 2 * hi) / 3; double ax = x[i] + (x[j] - x[i]) * mid1; double ay = y[i] + (y[j] - y[i]) * mid1; double bx = x[i] + (x[j] - x[i]) * mid2; double by = y[i] + (y[j] - y[i]) * mid2; double val1 = Math.sqrt(ax * ax + ay * ay); double val2 = Math.sqrt(bx * bx + by * by); if (val1 > val2) lo = mid1; else hi = mid2; } double xx = x[i] + (x[j] - x[i]) * (lo + hi) / 2; double yy = y[i] + (y[j] - y[i]) * (lo + hi) / 2; double val = Math.sqrt(xx * xx + yy * yy); min = Math.min(min, val); max = Math.max(max, val); } System.out.println(Math.PI * (max * max - min * min)); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
f4f78a1e3b6f4ffc3889718ed674238c
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; import java.awt.geom.*; /** * Problem statement: http://codeforces.com/problemset/problem/614/C */ public class FindTheBug9 { private static class Point { private int x; private int y; Point(int x, int y) { this.x = x; this.y = y; } long norm2() { return x * x + y * y; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int xOrigin = scanner.nextInt(); int yOrigin = scanner.nextInt(); List<Line2D> lines = new ArrayList<>(); int xCurrent = Integer.MAX_VALUE; int yCurrent = Integer.MAX_VALUE; int xPrev = Integer.MAX_VALUE; int yPrev = Integer.MAX_VALUE; int xFirst = Integer.MAX_VALUE; int yFirst = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { xCurrent = scanner.nextInt() - xOrigin; yCurrent = scanner.nextInt() - yOrigin; if(xPrev != Integer.MAX_VALUE && yPrev != Integer.MAX_VALUE) { lines.add(new Line2D.Double(xPrev, yPrev, xCurrent, yCurrent)); } else { xFirst = xCurrent; yFirst = yCurrent; } xPrev = xCurrent; yPrev = yCurrent; } lines.add(new Line2D.Double(xPrev, yPrev, xFirst, yFirst)); System.out.println(getSnowCleared(lines)); } private static double getSnowCleared(List<Line2D> polygon) { // We're going to clear a circle of snow centered at the origin, but // with a smaller circle cut out of the middle. Let R be the radius // of the outer circle and r be the radius of the inner circle. Then // the amount of snow cleared is pi*R^2 - pi*r^2 = pi(R^2 - r^2). I // claim that the outer circle's radius is the same as the distance // from the origin to the point furthest from it on the polygon, and // that the inner circle's radius is the same as the distance from // the origin to the point closest to it on the polygon. double outer = Double.NEGATIVE_INFINITY; double inner = Double.POSITIVE_INFINITY; for (Line2D line : polygon) { //System.out.println(line.getP1() + "-" + line.getP2() + ": " + line.ptSegDist(0,0)); double in_candidate = line.ptSegDistSq(0,0); double out_candidate = line.getP1().distanceSq(0, 0); //Only need p1 since all points will be p1 and p2 eventually outer = Math.max(outer, out_candidate); inner = Math.min(inner, in_candidate); } return Math.PI * (outer - inner); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
38ca7382eae6fddd4074e202ca93f525
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.awt.*; import java.awt.geom.*; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.stream.Collector; /** * Created by ribra on 11/15/2015. */ public class Main { private static InputReader sc = new InputReader(System.in); private static PrintWriter pw = new PrintWriter(System.out); public static void main(String [] args) { int n = sc.nextInt(); Point2D p = new Point2D.Double((double) sc.nextInt(), (double) sc.nextInt()); Point2D[] arr = new Point2D[n]; for (int i = 0; i < n; i++) { arr[i] = new Point2D.Double((double) sc.nextInt(), (double) sc.nextInt()); } double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for (int i = 0; i < n; i++) { int j = (i + 1) % n; Line2D line = new Line2D.Double(arr[i], arr[j]); min = Math.min(min, line.ptSegDist(p)); min = Math.min(min, p.distance(arr[i])); min = Math.min(min, p.distance(arr[j])); max = Math.max(max, line.ptSegDist(p)); max = Math.max(max, p.distance(arr[i])); max = Math.max(max, p.distance(arr[j])); } pw.print(Math.PI * (max * max - min * min)); terminate(); } public static void terminate() { pw.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Graph { private int V; private int E; private Set<Integer>[] adj; public Graph(int V) { this.V = V; this.E = 0; adj = new HashSet[V]; for (int i = 0; i < V; i++) adj[i] = new HashSet<>(); } public int V() { return V; } public int E() { return E; } public void addEdge(int v, int w) { adj[v].add(w); adj[w].add(v); E++; } public Iterable<Integer> adj(int v) { return adj[v]; } public static int degree(Graph g, int v) { int degree = 0; for (int w : g.adj(v)) degree++; return degree; } public static int maxDegree(Graph g) { int max = 0; for (int i = 0; i < g.V(); i++) max = Math.max(degree(g, i), max); return max; } public static int avgDegree(Graph g) { int sum = 0; for (int i = 0; i < g.V(); i++) sum += degree(g, i); return sum / g.V(); } public static int avgDegreeEfficient(Graph g) { // g.E = sum degree of every graph // 2 * g.E - because if v is connected to w, then w is connected to v as well // and divide by number of vertices return 2 * g.E() / g.V(); } public static int numberOfSelfLoops(Graph g) { int count = 0; for (int i = 0; i < g.V(); i++) for (int w : g.adj(i)) if (i == w) count++; return count / 2; } public String toString() { String s = V() + " vertices, " + E() + " edges\n"; for (int v = 0; v < V(); v++) { s += v + ": "; for (int w : this.adj(v)) s += w + " "; s += "\n"; } return s; } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
ef027fb1cf87f02521917389cb0f5eb9
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
/** * Created by Anna on 18.01.2016. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class TaskC { BufferedReader in; PrintWriter out; StringTokenizer st; public static void main(String[] args) throws IOException { TaskC solver = new TaskC(); solver.open(); solver.solve(); solver.close(); } private void solve() throws IOException { int n = nextInt(); double x = nextLong(); double y = nextLong(); double[] X = new double[n]; double[] Y = new double[n]; double min = 30000000; double max = 0; for (int i = 0; i < n; i++) { double a = nextLong(), b = nextLong(); X[i] = a - x; Y[i] = b - y; double sqrt = Math.sqrt(X[i] * X[i] + Y[i] * Y[i]); max = Math.max(sqrt, max); min = Math.min(sqrt, min); } x = y = 0; for (int i = 0; i < n; i++) { int cur = i; int next = (i + 1) % n; if (X[cur] == X[next] && Math.max(Y[cur], Y[next]) >= 0 && Math.min(Y[cur], Y[next]) <= 0) min = Math.min(min, X[cur]); else if (Y[cur] == Y[next] && Math.max(X[cur], X[next]) >= 0 && Math.min(X[cur], X[next]) <= 0) min = Math.min(min, Y[cur]); else { double nX, nY; nX = -(Y[cur] - Y[next]) * (X[cur] * Y[next] - Y[cur] * X[next]) / ((X[cur] - X[next]) * (X[cur] - X[next]) + (Y[cur] - Y[next]) * (Y[cur] - Y[next])); nY = -nX * (X[cur] - X[next]) / (Y[cur] - Y[next]); if (Math.min(X[cur], X[next]) <= nX && nX <= Math.max(X[cur], X[next]) && Math.min(Y[cur], Y[next]) <= nY && nY <= Math.max(Y[cur], Y[next])) min = Math.min(min, Math.sqrt(nX * nX + nY * nY)); } } out.println(Math.PI * (max * max - min * min)); } private void close() throws IOException { out.close(); } private void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; st = new StringTokenizer(str); } return st.nextToken(); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
e19c3e36d113e03b22c523caaab7ddc1
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Point { double x; double y; public Point(double x, double y) { this.x = x; this.y = y; } } class Task { private List<Point> points = new ArrayList<>(); private double circle(double r) { return 3.1415926535*r*r; } public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int x1 = in.nextInt(); int y1 = in.nextInt(); double max = 0; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); points.add(new Point(x,y)); max = Math.max(max, dist(x1, y1, x, y)); } points.add(points.get(0)); double min = Double.MAX_VALUE; for(int i=0;i<n;i++) { Point p1 = points.get(i); Point p2 = points.get(i+1); min = Math.min(min,dist(p1.x,p1.y, x1, y1)); min = Math.min(min, dist(p2.x, p2.y, x1, y1)); double squaredNorm = (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y); double t = ((x1-p1.x) * (p2.x-p1.x) + (y1-p1.y) * (p2.y-p1.y)) / squaredNorm; if(Double.compare(t,0.0) > 0 && Double.compare(t,1.0) < 0) { Point projection = new Point(p1.x+t*(p2.x-p1.x), p1.y+t*(p2.y-p1.y)); min = Math.min(min, dist(projection.x, projection.y,x1,y1)); } } System.out.println((circle(max)-circle(min))); } private double dist(double x1, double y1, double x, double y) { return Math.sqrt((x-x1)*(x-x1) + (y-y1) * (y-y1)); } private int getNumberOfZeros(String number) { return number.length()-1; } private boolean isBeautiful(String number) { int countOnes = 0; for(int i=0;i<number.length();i++) { if(number.charAt(i) == '1') countOnes++; else if(number.charAt(i) != '0') return false; } return countOnes<=1; } } 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 boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if ( line == null ) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next());} } 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(); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
47463a779118e55a7129858d056b0b0d
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.awt.geom.Line2D; import java.io.*; import java.util.*; public class C { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(); px = in.nextDouble(); py = in.nextDouble(); x1 = in.nextDouble(); y1 = in.nextDouble(); x0 = x1; y0 = y1; for (int i = 2; i <= n; i++) { x2 = in.nextDouble(); y2 = in.nextDouble(); dis(); x1 = x2; y1 = y2; } x2 = x0; y2 = y0; dis(); out.println(Math.PI * (maxd * maxd - mind * mind)); } private static void dis() { double d2 = d(x2, y2, px, py); double d = Line2D.ptSegDist(x1, y1, x2, y2, px, py); mind = Math.min(mind, d); maxd = Math.max(maxd, d2); } private static double d(double x, double y, double xx, double yy) { double dx = xx - x; double dy = yy - y; return Math.sqrt(dx * dx + dy * dy); } private static double mind = Double.MAX_VALUE, maxd = -1; private static double px, py, x0, y0, x1, y1, x2, y2; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
37ef426eaf50b19dd0e8172a66475db4
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; /** * Problem statement: http://codeforces.com/problemset/problem/614/C */ public class FindTheBug9 { private static class Point { private long x; private long y; Point(long x, long y) { this.x = x; this.y = y; } double norm2() { return (double)x * x + (double)y * y; } double distance2FromOrigin(Point other) { double lineDist = Math.pow((double)other.x*this.y - other.y*this.x, 2) / (Math.pow((double)other.y-this.y, 2) + Math.pow((double)other.x-this.x, 2)); double r_numerator = ((double)this.x)*(this.x-other.x) + ((double)this.y)*(this.y-other.y); double r_denomenator = ((double)other.x-this.x)*(other.x-this.x) + ((double)other.y-this.y)*(other.y-this.y); double r = r_numerator / r_denomenator; if (r >= 0 && r <= 1) return lineDist; else return Math.min(this.norm2(), other.norm2()); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int xOrigin = scanner.nextInt(); int yOrigin = scanner.nextInt(); List<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) { long xCurrent = (long) scanner.nextInt() - xOrigin; long yCurrent = (long) scanner.nextInt() - yOrigin; points.add(new Point(xCurrent, yCurrent)); } System.out.println(getSnowCleared(points)); } private static double getSnowCleared(List<Point> polygon) { // We're going to clear a circle of snow centered at the origin, but // with a smaller circle cut out of the middle. Let R be the radius // of the outer circle and r be the radius of the inner circle. Then // the amount of snow cleared is pi*R^2 - pi*r^2 = pi(R^2 - r^2). I // claim that the outer circle's radius is the same as the distance // from the origin to the point furthest from it on the polygon, and // that the inner circle's radius is the same as the distance from // the origin to the point closest to it on the polygon. double outer = Double.NEGATIVE_INFINITY; double inner = Double.POSITIVE_INFINITY; for (int i = 0; i < polygon.size(); i++) { Point vertex1 = polygon.get(i); Point vertex2 = polygon.get((i+1)%polygon.size()); double norm2 = vertex1.norm2(); outer = Math.max(outer, norm2); double distToLine = vertex1.distance2FromOrigin(vertex2); inner = Math.min(inner, distToLine); } //System.out.println("Inner: "+ inner); return Math.PI * (outer - inner); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
897199518a49fc18c8bc73cd915486f5
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by Shahjahan on 6/22/2017. * http://codeforces.com/contest/614/problem/C */ public class C614_C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] split1 = br.readLine().split(" "); int n = Integer.parseInt(split1[0]); int x = Integer.parseInt(split1[1]); int y = Integer.parseInt(split1[2]); Point center = new Point(x, y); ArrayList<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) { String[] split2 = br.readLine().split(" "); int px = Integer.parseInt(split2[0]); int py = Integer.parseInt(split2[1]); Point point = new Point(px, py); points.add(point); } double upper = 0.0; double lower = Double.MAX_VALUE; for (int i = 0; i < points.size(); i++) { int index1, index2; if (i == points.size() - 1) { index1 = 0; index2 = points.size() - 1; } else { index1 = i; index2 = i + 1; } Point p1 = points.get(index1); Point p2 = points.get(index2); double distance = distance(p1.x, p1.y, p2.x, p2.y, center.x, center.y); if (distance < lower) { lower = distance; } double euclDist = euclideanDistance(center, points.get(i)); if (euclDist > upper) { upper = euclDist; } } double upperCircle = Math.PI * upper * upper; double lowerCircle = Math.PI * lower * lower; double result = upperCircle - lowerCircle; System.out.printf("%.18f", result); } private static double euclideanDistance(Point p1, Point p2) { double deltaY = p2.y - p1.y; double deltaX = p2.x - p1.x; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); } private static double distance(double x1, double y1, double x2, double y2, double x3, double y3) { double px = x2 - x1; double py = y2 - y1; double temp = (px * px) + (py * py); double u = ((x3 - x1) * px + (y3 - y1) * py) / (temp); if (u > 1) { u = 1; } else if (u < 0) { u = 0; } double x = x1 + u * px; double y = y1 + u * py; double dx = x - x3; double dy = y - y3; return Math.sqrt(dx * dx + dy * dy); } } class Point { Integer x; Integer y; Point(Integer x, Integer y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { Point other = (Point) o; return other.x.equals(this.x) && other.y.equals(this.y); } @Override public int hashCode() { return x.hashCode() + (31 * y.hashCode()); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
6688486335b75bbd4c8ca8a31f1eb115
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * Created by Shahjahan on 6/22/2017. * http://codeforces.com/contest/614/problem/C */ public class C614_C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] split1 = br.readLine().split(" "); int n = Integer.parseInt(split1[0]); Point center = new Point(Integer.parseInt(split1[1]), Integer.parseInt(split1[2])); ArrayList<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) { String[] split2 = br.readLine().split(" "); points.add(new Point(Integer.parseInt(split2[0]), Integer.parseInt(split2[1]))); } double upperRadius = 0.0; double lowerRadius = Double.MAX_VALUE; for (int i = 0; i < points.size(); i++) { Point p1 = points.get(i); Point p2 = points.get((i + 1) % points.size()); double distance = minDistanceOfLineFromAPoint(p1, p2, center); if (distance < lowerRadius) { lowerRadius = distance; } double euclideanDistance = euclideanDistance(center, points.get(i)); if (euclideanDistance > upperRadius) { upperRadius = euclideanDistance; } } double upperCircleArea = Math.PI * upperRadius * upperRadius; double lowerCircleArea = Math.PI * lowerRadius * lowerRadius; double areaCleared = upperCircleArea - lowerCircleArea; System.out.printf("%.18f", areaCleared); } private static double euclideanDistance(Point p1, Point p2) { double deltaY = p2.y - p1.y; double deltaX = p2.x - p1.x; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); } private static double minDistanceOfLineFromAPoint(Point lineP1, Point lineP2, Point fromP) { double deltaX = lineP2.x - lineP1.x; double deltaY = lineP2.y - lineP1.y; double dotProduct = (deltaX * deltaX) + (deltaY * deltaY); double t = ((fromP.x - lineP1.x) * deltaX + (fromP.y - lineP1.y) * deltaY) / (dotProduct); if (t > 1) { t = 1; } else if (t < 0) { t = 0; } double x = lineP1.x + t * deltaX; double y = lineP1.y + t * deltaY; Point closestPoint = new Point(x, y); return euclideanDistance(closestPoint, fromP); } } class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
8c88b65a603b0764fe0f8e820aae0fac
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.awt.geom.Line2D; import java.util.Scanner; public class CF_614C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), px = scan.nextInt(), py = scan.nextInt(); double minRadius = Double.MAX_VALUE; double maxRadius = -1; Point[] pts = new Point[n]; for(int i=0;i<n;i++) { int x = scan.nextInt(), y = scan.nextInt(); pts[i] = new Point(x-px,y-py); } Point last = pts[pts.length-1]; for(int i=0;i<pts.length;i++) { double r = Line2D.ptSegDist(last.x, last.y, pts[i].x, pts[i].y, 0, 0); // System.err.println("Line between " + last + " and " + pts[i]); // System.err.println("=" + r); minRadius = Math.min(minRadius,r); maxRadius = Math.max(maxRadius,r); long dx = pts[i].x; long dy = pts[i].y; r = Math.sqrt(dx*dx+dy*dy); maxRadius = Math.max(maxRadius,r); minRadius = Math.min(minRadius,r); last = pts[i]; } // System.err.println("min: " + minRadius); // System.err.println("max: " + maxRadius); System.out.println(Math.PI * (maxRadius * maxRadius -minRadius*minRadius)); } static class Point { int x,y; public Point(int x, int y) { this.x = x; this.y = y; } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
5373dec28d9cea27cecd1d9de08ca8ba
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.*; public class Main { int N; P origin; P[] ps; private class P{ double x,y; public P(double x,double y){ this.x = x; this.y = y; } } public double distanceVertex(P p1,P p2){ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } public double dotVector(P v1,P v2){ return v1.x * v2.x +v1.y * v2.y; } public double absVector(P p1){ return Math.sqrt(p1.x * p1.x + p1.y * p1.y); } public double crossVector(P v1,P v2){ return v1.x * v2.y - v1.y * v2.x; } public double distanceDotAndLine(P origin,P p1,P p2){ P p1_p2 = new P(p2.x - p1.x,p2.y - p1.y); P p2_p1 = new P(p1.x - p2.x,p1.y - p2.y); P p1_origin = new P(origin.x - p1.x,origin.y - p1.y); P p2_origin = new P(origin.x - p2.x,origin.y - p2.y); if(dotVector(p1_p2,p1_origin) < 0.0)return absVector(p1_origin); if(dotVector(p2_p1,p2_origin) < 0.0)return absVector(p2_origin); double D = Math.abs(crossVector(p1_p2,p1_origin)); double L = distanceVertex(p1,p2); return D / L; } public void solve(){ N = nextInt(); origin = new P(nextDouble(),nextDouble()); ps = new P[N]; for(int i = 0;i < N;i++){ ps[i] = new P(nextDouble(),nextDouble()); } double maxDistance = 0.0; for(int i = 0;i < N;i++){ double dx = ps[i].x - origin.x; double dy = ps[i].y - origin.y; maxDistance = Math.max(maxDistance,dx * dx + dy * dy); } double minDistance = 1e13; for(int i = 0;i < N;i++){ int j = (i + 1) % N; double distance = distanceDotAndLine(origin,ps[i],ps[j]); minDistance = Math.min(minDistance,distance); } out.println(String.format("%.09f",(maxDistance - minDistance * minDistance) * Math.PI)); } public static void main(String[] args) { out.flush(); new Main().solve(); out.close(); } /* Input */ private static final InputStream in = System.in; private static final PrintWriter out = new PrintWriter(System.out); private final byte[] buffer = new byte[2048]; private int p = 0; private int buflen = 0; private boolean hasNextByte() { if (p < buflen) return true; p = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } public boolean hasNext() { while (hasNextByte() && !isPrint(buffer[p])) { p++; } return hasNextByte(); } private boolean isPrint(int ch) { if (ch >= '!' && ch <= '~') return true; return false; } private int nextByte() { if (!hasNextByte()) return -1; return buffer[p++]; } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = -1; while (isPrint((b = nextByte()))) { sb.appendCodePoint(b); } return sb.toString(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
49d0d6de9d1a88daa5bfd388ee6f69ff
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.*; import java.util.InputMismatchException; public class Main { private static InputReader ir; private static OutputWriter ow; final static int INF = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { initS(); //initF("INPUT.TXT", "OUTPUT.TXT"); task(); exit(); } private static Double getDD(int x1, int y1, int x2, int y2) { if (x1 == x2 && y1 != y2) { if (y1 * y2 <= 0) return (double) x1 * x1; else return null; } if (x1 == x2) return getDD(x1, y1); int x = x2 - x1; int y = y2 - y1; double s1 = (double) x * x1 + (double) y * y1; double s2 = (double) x * x2 + (double) y * y2; if (s1 * s2 <= 0) { double k = (double) y / x; double b = y2 - k * x2; return (y - k * x - b) * (y - k * x - b) / (1 + k * k); } else return null; } private static Double getDD(int x, int y) { return (double) x * x + (double) y * y; } private static void task() throws Exception { int n = ir.nextInt(); int px = ir.nextInt(), py = ir.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = ir.nextInt() - px; y[i] = ir.nextInt() - py; } Double RR = getDD(x[0], y[0]), rr = RR; for (int i = 0; i < n; ++i) { Double dds = getDD(x[i], y[i], x[(i + 1) % n], y[(i + 1) % n]); Double ddp = getDD(x[i], y[i]); RR = Math.max(ddp, RR); rr = Math.min(rr, ddp); if (dds != null) rr = Math.min(rr, dds); } ow.print(String.valueOf(Math.PI * (RR - rr))); } private static void initS() throws IOException { ir = new InputReader(System.in); ow = new OutputWriter(System.out); } private static void initF(String inName, String outName) throws IOException { ir = new InputReader(new FileInputStream(inName)); ow = new OutputWriter(new FileOutputStream(outName)); } private static void exit() throws Exception { ir.close(); ow.close(); } } class InputReader implements AutoCloseable { private final InputStream in; private int capacity; private byte[] buffer; private int len = 0; private int cur = 0; public InputReader(InputStream stream) { this(stream, 100_000); } public InputReader(InputStream stream, int capacity) { this.in = stream; this.capacity = capacity; buffer = new byte[capacity]; } private int read() { if (cur >= len) { try { cur = 0; len = in.read(buffer, 0, capacity); if (len <= 0) return -1; } catch (IOException e) { throw new InputMismatchException(); } } return buffer[cur++]; } private boolean isSpace(int c) { return c == ' ' || isEscape(c); } private boolean isEscape(int c) { return c == '\n' || c == '\t' || c == '\r' || c == -1; } private int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } int nextInt() { int c = readSkipSpace(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } public long nextLong() { int c = readSkipSpace(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } int nextChar() { return readSkipSpace(); } String nextLine() { StringBuilder res = new StringBuilder(); int c = readSkipSpace(); do { res.append((char) (c)); c = read(); } while (!isEscape(c)); return res.toString(); } @Override public void close() throws Exception { in.close(); } } class OutputWriter implements Flushable, AutoCloseable { private byte[] buf; private int capacity; private int count; private OutputStream out; public OutputWriter(OutputStream stream) { out = stream; capacity = 10_000; buf = new byte[capacity]; } public OutputWriter(OutputStream stream, int capacity) { if (capacity <= 0) throw new IllegalArgumentException("capacity <= 0"); out = stream; this.capacity = capacity; buf = new byte[capacity]; } public void write(int b) throws IOException { if (count >= buf.length) flushBuffer(); buf[count++] = (byte)b; } public void write(byte[] bytes, int off, int len) throws IOException { if (len >= buf.length) { flushBuffer(); out.write(bytes, off, len); return; } if (len > buf.length - count) flushBuffer(); System.arraycopy(bytes, off, buf, count, len); count += len; } public void write(byte[] bytes) throws IOException { write(bytes, 0, bytes.length); } public void print(int i) throws IOException { print(String.valueOf(i)); } public void print(long l) throws IOException { print(String.valueOf(l)); } public void print(String str) throws IOException { write(str.getBytes()); } public void println() throws IOException { print("\n"); } public void println(String str) throws IOException { print(str); print("\n"); } public void println(int i) throws IOException { print(i); println(); } public void println(long l) throws IOException { print(l); println(); } public void print(String separator, Object... objects) throws IOException { if (objects == null) return; for (int i = 0; i < objects.length; ++i) { if (i != 0 && separator != null) print(separator); print(objects[i].toString()); } } private void flushBuffer() throws IOException { if (count > 0) { out.write(buf, 0, count); count = 0; } } @Override public void flush() throws IOException { flushBuffer(); out.flush(); } @Override public void close() throws Exception { flush(); out.close(); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
6c62cbaddae55256914f297d48bb969d
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; /** * Problem statement: http://codeforces.com/problemset/problem/614/C */ public class FindTheBug9 { private static class Point { private long x; private long y; Point(long x, long y) { this.x = x; this.y = y; } double norm2() { return (double)x * x + (double)y * y; } double distance2FromOrigin(Point other) { double lineDist = Math.pow((double)other.x*this.y - other.y*this.x, 2) / (Math.pow((double)other.y-this.y, 2) + Math.pow((double)other.x-this.x, 2)); double r_numerator = ((double)this.x)*(this.x-other.x) + ((double)this.y)*(this.y-other.y); double r_denomenator = ((double)other.x-this.x)*(other.x-this.x) + ((double)other.y-this.y)*(other.y-this.y); double r = r_numerator / r_denomenator; if (r >= 0 && r <= 1) return lineDist; else return Math.min(this.norm2(), other.norm2()); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int xOrigin = scanner.nextInt(); int yOrigin = scanner.nextInt(); List<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) { long xCurrent = (long) scanner.nextInt() - xOrigin; long yCurrent = (long) scanner.nextInt() - yOrigin; points.add(new Point(xCurrent, yCurrent)); } System.out.println(getSnowCleared(points)); } private static double getSnowCleared(List<Point> polygon) { // We're going to clear a circle of snow centered at the origin, but // with a smaller circle cut out of the middle. Let R be the radius // of the outer circle and r be the radius of the inner circle. Then // the amount of snow cleared is pi*R^2 - pi*r^2 = pi(R^2 - r^2). I // claim that the outer circle's radius is the same as the distance // from the origin to the point furthest from it on the polygon, and // that the inner circle's radius is the same as the distance from // the origin to the point closest to it on the polygon. double outer = Double.NEGATIVE_INFINITY; double inner = Double.POSITIVE_INFINITY; for (int i = 0; i < polygon.size(); i++) { Point vertex1 = polygon.get(i); Point vertex2 = polygon.get((i+1)%polygon.size()); double norm2 = vertex1.norm2(); outer = Math.max(outer, norm2); double distToLine = vertex1.distance2FromOrigin(vertex2); inner = Math.min(inner, distToLine); } //System.out.println("Inner: "+ inner); return Math.PI * (outer - inner); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
8a795faf02f09144fdd55801f6b4e897
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.awt.geom.Line2D; import java.util.*; /** * Problem statement: http://codeforces.com/problemset/problem/614/C */ public class FindTheBug9 { private static class Point { private double x; private double y; Point(double x, double y) { this.x = x; this.y = y; } double norm2() { return x * x + y * y; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int xOrigin = scanner.nextInt(); int yOrigin = scanner.nextInt(); List<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) { int xCurrent = scanner.nextInt() - xOrigin; int yCurrent = scanner.nextInt() - yOrigin; points.add(new Point(xCurrent, yCurrent)); } System.out.println(getSnowCleared(points)); } private static double getSnowCleared(List<Point> polygon) { // We're going to clear a circle of snow centered at the origin, but // with a smaller circle cut out of the middle. Let R be the radius // of the outer circle and r be the radius of the inner circle. Then // the amount of snow cleared is pi*R^2 - pi*r^2 = pi(R^2 - r^2). I // claim that the outer circle's radius is the same as the distance // from the origin to the point furthest from it on the polygon, and // that the inner circle's radius is the same as the distance from // the origin to the point closest to it on the polygon. double outer = Double.NEGATIVE_INFINITY; double inner = Double.POSITIVE_INFINITY; int counter = 0; Point temp = polygon.get(1); for (Point vertex : polygon) { double norm2 = vertex.norm2(); outer = Math.max(outer, norm2); inner = Math.min(inner, Line2D.ptSegDistSq(vertex.x,vertex.y,temp.x,temp.y,0,0)); counter++; temp = polygon.get((counter+1)%polygon.size()); } return Math.PI * (outer - inner); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
62cef2c508c68d29674fc16bc9d441ca
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PetersSnow { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); StringTokenizer st = new StringTokenizer(line); final int n = Integer.parseInt(st.nextToken()); final int px = Integer.parseInt(st.nextToken()), py = Integer.parseInt(st.nextToken()); double minA = Long.MAX_VALUE, maxA = 0; long[] ax = new long[n], ay = new long[n], r = new long[n]; for (int i = 0; i < n; i++) { line = in.readLine(); st = new StringTokenizer(line); ax[i] = Long.parseLong(st.nextToken()) - px; ay[i] = Long.parseLong(st.nextToken()) - py; r[i] = ax[i]*ax[i] + ay[i]*ay[i]; } // find the minimum distance from the line segment to origin. for (int i = 0; i < n; i++) { int next = (i+1) % n; // long dx = ax[i], dy = ay[i]; // dx -= ax[next]; // dy -= ay[next]; if (r[i] > maxA) { maxA = r[i]; } double sx = ax[i], ex = ax[next], sy = ay[i], ey = ay[next]; double sr = r[i], er = r[next], diff; do { double mx = (sx+ex)/2, my = (sy + ey) /2; double mr = mx*mx + my*my; // System.out.println(String.format("i = %d, er = %f, sr = %f, mr = %f, mx = %f, my = %f", // i, er, sr, mr, mx, my)); if ( sr > er ) { diff = sr - Math.min(mr, er); sr = mr; sx = mx; sy = my; } else { diff = er - Math.min(mr, sr); er = mr; ex = mx; ey = my; } } while (diff > 0.0000001 && diff / sr > 0.000001); if ( er < minA ) { //System.out.println(String.format("i = %d, er = %f, sr = %f",i, er, sr)); minA = er; } } // System.out.println(maxA); // System.out.println(minA); System.out.println(Math.PI * (maxA - minA)); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
64e6e54518931d70b89378c89049935d
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.*; import java.text.DecimalFormat; import java.util.StringTokenizer; public class Main { static final double eps = 1e-6; public static void main(String[] args) throws Exception { Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); Point p = new Point(in.nextDouble(), in.nextDouble()); Point[] points = new Point[n]; double min = Double.MAX_VALUE, max = Double.MIN_VALUE; for (int i = 0; i < n; i++) { double x = in.nextDouble(); double y = in.nextDouble(); points[i] = new Point(x, y); double d = dis(points[i], p); if (d > max) max = d; } for (int i = 0; i < n; i++) { int next = (i + 1) % n; double d = dis(p, new Seg(points[i], points[next])); if (d < min) min = d; } DecimalFormat decimalFormat = new DecimalFormat("0.000000000000000000"); out.println(decimalFormat.format(Math.PI * (max - min))); out.flush(); in.close(); out.close(); } private static double dis(Point p1, Point p2) { return (p1.y - p2.y) * (p1.y - p2.y) + (p1.x - p2.x) * (p1.x - p2.x); } private static double dis(Point p, Seg seg) { double a = dis(seg.a, seg.b); double b = dis(p, seg.a); double c = dis(p, seg.b); if (b < eps || c < eps) { return 0; } if (a < eps) { return b; } if (c >= a + b) { return b; } if (b >= a + c) { return c; } double ra = Math.sqrt(a); double rb = Math.sqrt(b); double rc = Math.sqrt(c); double cc = (ra + rb + rc) / 2; double s = cc * (cc - ra) * (cc - rb) * (cc - rc); return 4 * s / a; } static class Seg { Point a, b; Seg(Point a, Point b) { this.a = a; this.b = b; } @Override public String toString() { return "[ " + a.toString() + " " + b.toString() + " ]"; } } static class Point { double x, y; Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return "(" + x + "," + y + ")"; } } static class Reader { BufferedReader reader; StringTokenizer st; Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } void close() throws IOException { reader.close(); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() throws IOException { return reader.readLine(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
cb9738ccc0dbd16e9b3e114fbed18f27
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.Scanner; public class C { private static final int UNDEF = Integer.MAX_VALUE; private static double max = 0; private static double min = Double.MAX_VALUE; private static long cx; private static long cy; public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); cx = s.nextInt(); cy = s.nextInt(); long x0 = s.nextLong(); long y0 = s.nextLong(); long x1 = x0; long y1 = y0; for (int i = 0; i < n - 1; i++) { long x2 = s.nextLong(); long y2 = s.nextLong(); updateBounds(x1, y1, x2, y2); x1 = x2; y1 = y2; } updateBounds(x1, y1, x0, y0); double area = Math.PI * (max * max - min * min); System.out.println(area); } private static void updateBounds(long x1, long y1, long x2, long y2) { long dx = Math.abs(x2 - cx); long dy = Math.abs(y2 - cy); double r = Math.sqrt(dx * dx + dy * dy); max = r > max ? r : max; if (x1 != UNDEF) { long a = y1 - y2; long b = x2 - x1; long c = x1 * y2 - x2 * y1; double dist = Math.abs(a * cx + b * cy + c) / Math.sqrt(a * a + b * b); if (dot(x1, y1, x2, y2, cx, cy) < 0) { long dx2 = Math.abs(x2 - cx); long dy2 = Math.abs(y2 - cy); dist = Math.sqrt(dx2 * dx2 + dy2 * dy2); } if (dot(x2, y2, x1, y1, cx, cy) < 0) { long dx1 = Math.abs(x1 - cx); long dy1 = Math.abs(y1 - cy); dist = Math.sqrt(dx1 * dx1 + dy1 * dy1); } min = dist < min ? dist : min; } } private static long dot(long ax, long ay, long bx, long by, long cx, long cy) { long abx = ax - bx; long aby = ay - by; long bcx = cx - bx; long bcy = cy - by; return abx * bcx + aby * bcy; } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
f1c93bdd59d48b50d27d97f60fd2f494
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; Reader.init(System.in); //PrintWriter pw = new PrintWriter("output.out", "UTF-8"); double mn = Double.MAX_VALUE,mx = Double.MIN_VALUE; tk = new StringTokenizer(in.readLine()); int n = parseInt(tk.nextToken()); double x = parseDouble(tk.nextToken()), y = parseDouble(tk.nextToken()); double x1,y1; point [] p = new point[n]; int i; double d; point pnt = new point(x,y),p1,p2; for(i=0; i<n; i++) { tk = new StringTokenizer(in.readLine()); x1 = parseDouble(tk.nextToken()); y1 = parseDouble(tk.nextToken()); p[i] = new point(x1,y1); d = hypot(x-x1, y-y1); mn = min(mn, d); mx = max(mx, d); if(i>0) { d = distToSegment(pnt, p[(i-1+n)%n], p[i]); mn = min(mn, d); mx = max(mx, d); } } d = distToSegment(pnt, p[0], p[n-1]); mn = min(mn, d); mx = max(mx, d); System.out.println(PI*mx*mx-PI*mn*mn); } public static double distToSegment(point p,point a,point b) { vector ap = new vector(a,p), ab = new vector(a,b); double u = dot(ap,ab)/norm_sq(ab); if(u < 0.0) return hypot(p.x-a.x, p.y-a.y); if(u > 1.0) return hypot(p.x-b.x, p.y-b.y); return distToLine(p,a,b); } public static double distToLine(point p,point a,point b) { vector ap = new vector(a,p), ab = new vector(a,b); double u = dot(ap,ab)/norm_sq(ab); point c = translate(a, scale(ab,u)); return hypot(p.x-c.x, p.y-c.y); } static class point { double x,y; public point(double x,double y) { this.x = x; this.y = y; } } static class vector { double x,y; public vector(point a,point b) { this.x = b.x-a.x; this.y = b.y-a.y; } } static double dot(vector a,vector b) { return a.x*b.x+a.y*b.y; } static double norm_sq(vector v) { return v.x*v.x+v.y*v.y; } static vector scale(vector v,double s) { v.x *= s; v.y *= s; return v; } static point translate(point p,vector v) { return new point(p.x+v.x, p.y+v.y); } } class Tools { public static boolean next_permutation(int [] p,int len) { int a =len-2; while(a>=0 && p[a]>=p[a+1]) a--; if(a==-1) return false; int b = len-1; while(p[b]<=p[a]) b--; p[a] += p[b]; p[b] = p[a] - p[b]; p[a] -= p[b]; for(int i=a+1, j=len-1; i<j; i++,j--) { p[i] += p[j]; p[j] = p[i]-p[j]; p[i] -= p[j]; } return true; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) throws UnsupportedEncodingException { reader = new BufferedReader( new InputStreamReader(input, "UTF-8") ); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
ccfbf5d88cd027256b08d68359cdda78
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; import java.io.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; public class c { public static void main(String[] arg) { new c(); } public c() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Point2D p = new Point2D.Double(in.nextInt(), in.nextInt()); Point2D[] arr = new Point2D[n]; for(int i = 0; i < n; i++) arr[i] = new Point2D.Double(in.nextInt(), in.nextInt()); double min = Integer.MAX_VALUE; double max = Integer.MIN_VALUE; for(int i = 0; i < n; i++) { int j = (i+1)%n; Line2D l = new Line2D.Double(arr[i], arr[j]); min = Math.min(min, l.ptSegDist(p)); min = Math.min(min, p.distance(arr[i])); min = Math.min(min, p.distance(arr[j])); max = Math.max(max, l.ptSegDist(p)); max = Math.max(max, p.distance(arr[i])); max = Math.max(max, p.distance(arr[j])); } out.println(Math.PI*(max*max-min*min)); in.close(); out.close(); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
715989482ada2f81c7ce6e9f48528f13
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; import java.io.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class c { public static void main(String[] arg) throws IOException { new c(); } public c() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Point2D p = new Point2D.Double(in.nextInt(), in.nextInt()); Point2D[] arr = new Point2D[n]; for(int i = 0; i < n; i++) arr[i] = new Point2D.Double(in.nextInt(), in.nextInt()); double min = Integer.MAX_VALUE; double max = Integer.MIN_VALUE; for(int i = 0; i < n; i++) { int j = (i+1)%n; Line2D l = new Line2D.Double(arr[i], arr[j]); min = Math.min(min, l.ptSegDist(p)); min = Math.min(min, p.distance(arr[i])); min = Math.min(min, p.distance(arr[j])); max = Math.max(max, l.ptSegDist(p)); max = Math.max(max, p.distance(arr[i])); max = Math.max(max, p.distance(arr[j])); } out.println(Math.PI*(max*max-min*min)); in.close(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while(!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 void close() throws IOException { br.close(); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
ab2f30c97cd4604948466466c477b1e3
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SnowBlower { static final int INF = (int) 1e9; void solve() { int n = in.nextInt(); long a = in.nextInt(), b = in.nextInt(); long[] x = new long[n], y = new long[n]; // calc max distance from origin to polygon (the endpoint on the polygon must be a vertex) double max = 0; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); double d = distance(a, b, x[i], y[i]); max = Math.max(max, d); } // calc min distance from origin(a,b) to each segment of the polygon double min = INF; for (int i = 0; i < n; i++) { int j = (i + 1) % n; min = Math.min(min, distanceToSegment(a, b, x[i], y[i], x[j], y[j])); } double area = Math.PI * (max + min) * (max - min); out.println(area); } private double distanceToSegment(long a, long b, long x1, long y1, long x2, long y2) { long[] u, v; u = new long[]{a - x1, b - y1}; v = new long[]{x2 - x1, y2 - y1}; long d1 = dotProduct(u, v); u = new long[]{a - x2, b - y2}; v = new long[]{x1 - x2, y1 - y2}; long d2 = dotProduct(u, v); if (d1 > 0 && d2 > 0) { u = new long[]{x1 - a, y1 - b}; v = new long[]{x2 - a, y2 - b}; return (double) Math.abs(crossProduct(u, v)) / distance(x1, y1, x2, y2); } return Math.min(distance(a, b, x1, y1), distance(a, b, x2, y2)); } private double distance(long x1, long y1, long x2, long y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } private long crossProduct(long[] u, long[] v) { return u[0] * v[1] - u[1] * v[0]; } private long dotProduct(long[] u, long[] v) { return u[0] * v[0] + u[1] * v[1]; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SnowBlower().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
b36f610137bea14851f81599b21bce81
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SnowBlower { static final int INF = (int) 1e9; void solve() { int n = in.nextInt(); long a = in.nextLong(), b = in.nextLong(); long[] x = new long[n], y = new long[n]; for (int i = 0; i < n; i++) { x[i] = in.nextLong(); y[i] = in.nextLong(); } double max = 0; for (int i = 0; i < n; i++) { max = Math.max(max, distanceToPoint(a, b, x[i], y[i])); } double min = INF; for (int i = 0; i < n; i++) { min = Math.min(min, distanceToSegment(a, b, x[i], y[i], x[(i + 1) % n], y[(i + 1) % n])); } out.println(Math.PI * (max + min) * (max - min)); } private double distanceToSegment(long a, long b, long x1, long y1, long x2, long y2) { long[] AP = new long[]{a - x1, b - y1}, AB = new long[]{x2 - x1, y2 - y1}; long d1 = dotProduct(AP, AB); long[] BP = new long[]{a - x2, b - y2}, BA = new long[]{x1 - x2, y1 - y2}; long d2 = dotProduct(BP, BA); if (d1 > 0 && d2 > 0) { long[] PA = new long[]{x1 - a, y1 - b}, PB = new long[]{x2 - a, y2 - b}; return Math.abs(crossProduct(PA, PB)) / distanceToPoint(x1, y1, x2, y2); } return Math.min(distanceToPoint(a, b, x1, y1), distanceToPoint(a, b, x2, y2)); } private long crossProduct(long[] u, long[] v) { return u[0] * v[1] - u[1] * v[0]; } private long dotProduct(long[] u, long[] v) { return u[0] * v[0] + u[1] * v[1]; } private double distanceToPoint(long a, long b, long x, long y) { return Math.sqrt((a - x) * (a - x) + (b - y) * (b - y)); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SnowBlower().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
078901e376cc987e8414ac7427cc69d3
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
/** * * @author meashish */ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Serializable; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class Main { InputReader in; Printer out; long MOD = 1000000007; private void start() throws Exception { int n = in.nextInt(); long px = in.nextInt(); long py = in.nextInt(); Pair<Long, Long> pair[] = new Pair[n]; long maxDist = 0, minDist = Long.MAX_VALUE; for (int i = 0; i < n; i++) { long x = in.nextInt(); long y = in.nextInt(); pair[i] = new Pair<>(x, y); long dist = (px - x) * (px - x) + (py - y) * (py - y); minDist = Math.min(minDist, dist); maxDist = Math.max(maxDist, dist); } double dist = 100000000; for (int i = 1; i < n; i++) { long x1 = pair[i - 1].key; long y1 = pair[i - 1].value; long x2 = pair[i].key; long y2 = pair[i].value; double tmp = (y2 - y1) * px - (x2 - x1) * py + x2 * y1 - y2 * x1; tmp = Math.abs(tmp); tmp /= Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); long v1 = (x2 - x1) * (x2 - px); long v2 = (y2 - y1) * (y2 - py); boolean b1 = (v1 + v2) >= 0; v1 = (x2 - x1) * (px - x1); v2 = (y2 - y1) * (py - y1); boolean b2 = (v1 + v2) >= 0; if (b1 && b2) { dist = Math.min(dist, tmp); } } long x1 = pair[n - 1].key; long y1 = pair[n - 1].value; long x2 = pair[0].key; long y2 = pair[0].value; double tmp = (y2 - y1) * px - (x2 - x1) * py + x2 * y1 - y2 * x1; tmp = Math.abs(tmp); tmp /= Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); long v1 = (x2 - x1) * (x2 - px); long v2 = (y2 - y1) * (y2 - py); boolean b1 = (v1 + v2) >= 0; v1 = (x2 - x1) * (px - x1); v2 = (y2 - y1) * (py - y1); boolean b2 = (v1 + v2) >= 0; if (b1 && b2) { dist = Math.min(dist, tmp); } /*Arrays.sort(pair, (Pair<Long, Long> t, Pair<Long, Long> t1) -> { if (t.dist > t1.dist) { return 1; } if (t.dist < t1.dist) { return -1; } return 0; });*/ double ans = Math.PI * (maxDist - Math.min(minDist, dist * dist)); System.out.printf("%.11f\n", ans); } long power(long x, long n) { if (n <= 0) { return 1; } long y = power(x, n / 2); if ((n & 1) == 1) { return (((y * y) % MOD) * x) % MOD; } return (y * y) % MOD; } public int gcd(int a, int b) { a = Math.abs(a); b = Math.abs(b); return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue(); } public static void main(String[] args) throws Exception { InputReader in; PrintStream out; //in = new InputReader(new FileInputStream(new File("the_price_is_correct.txt"))); //out = new PrintStream("out.txt"); in = new InputReader(System.in); out = System.out; Main main = new Main(); main.in = in; main.out = new Printer(out); main.start(); } private 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 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 String nextString() { 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 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 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 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 nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class Printer { PrintStream out; StringBuilder buffer = new StringBuilder(); boolean autoFlush; public Printer(PrintStream out) { this.out = out; } public Printer(PrintStream out, boolean autoFlush) { this.out = out; this.autoFlush = autoFlush; } public void println() { buffer.append("\n"); if (autoFlush) { flush(); } } public void println(int n) { println(Integer.toString(n)); } public void println(long n) { println(Long.toString(n)); } public void println(double n) { println(Double.toString(n)); } public void println(float n) { println(Float.toString(n)); } public void println(boolean n) { println(Boolean.toString(n)); } public void println(char n) { println(Character.toString(n)); } public void println(byte n) { println(Byte.toString(n)); } public void println(short n) { println(Short.toString(n)); } public void println(Object o) { println(o.toString()); } public void println(String s) { buffer.append(s).append("\n"); if (autoFlush) { flush(); } } public void print(char s) { buffer.append(s); if (autoFlush) { flush(); } } public void print(String s) { buffer.append(s); if (autoFlush) { flush(); } } public void flush() { try { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(out)); log.write(buffer.toString()); log.flush(); buffer = new StringBuilder(); } catch (Exception e) { e.printStackTrace(); } } } private class Pair<T, U> implements Serializable { public long dist; private T key; public T getKey() { return key; } private U value; public U getValue() { return value; } public Pair(T key, U value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (!this.key.equals(other.key)) { return false; } return this.value.equals(other.value); } @Override public int hashCode() { return key.hashCode() + 13 * value.hashCode(); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
266e5b28b66b94433cc4bf855a0c38db
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.util.regex.Pattern; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author amalev */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long dist2(long x1, long y1, long x2, long y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } long sq(long x1, long y1, long x2, long y2) { return x1 * x2 + y1 * y2; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); long xp = in.nextLong(); long yp = in.nextLong(); double max = 0; double min = Long.MAX_VALUE; long[] ax = new long[n]; long[] ay = new long[n]; for (int i = 0; i < n; i++) { ax[i] = in.nextLong(); ay[i] = in.nextLong(); } for (int i = 0; i < n; i++) { long x0 = ax[i]; long y0 = ay[i]; double d = dist2(xp, yp, x0, y0); if (d > max) { max = d; } if (d < min) { min = d; } long x1 = ax[(i + 1) % n]; long y1 = ay[(i + 1) % n]; if (sq(xp - x0, yp - y0, x1 - x0, y1 - y0) > 0 && sq(x0 - x1, y0 - y1, xp - x1, yp - y1) > 0) { d = Math.abs((xp - x0) * (y1 - y0) - (x1 - x0) * (yp - y0)) / Math.sqrt(dist2(x0, y0, x1, y1)); d = d * d; if (d < min) { min = d; } } } out.println(Math.PI * (max - min)); } } static class FastScanner { final BufferedReader input; String[] buffer; int pos; final static Pattern SEPARATOR = Pattern.compile("\\s+"); public FastScanner(InputStream inputStream) { input = new BufferedReader(new InputStreamReader(inputStream)); } private String read() { try { if (buffer == null || pos >= buffer.length) { buffer = SEPARATOR.split(input.readLine()); pos = 0; } return buffer[pos++]; } catch (Exception ex) { throw new RuntimeException(ex); } } public long nextLong() { return Long.parseLong(read()); } public int nextInt() { return Integer.parseInt(read()); } } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
0cbd312d2d35b019cd0bc31c5e54cf85
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.awt.Point; import java.util.*; import java.math.*; import java.awt.geom.*; /** * * @author sarthak */ public class rnd339_C { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int px=s.nextInt(); int py=s.nextInt(); double mx=Double.MIN_VALUE; double mn=Double.MAX_VALUE; // System.out.println(mx + " " + mn); int[] X=new int[n]; int[] Y=new int[n]; for(int i=0;i<n;i++) { int x=s.nextInt(); int y=s.nextInt(); mx=Math.max(mx, (double)((double)(px-x)*(double)(px-x))+(double)((double)(py-y)*(double)(py-y))); X[i]=x;Y[i]=y; //mn=Math.min(mn,(px-x)*(px-x)+(py-y)*(py-y)); } for(int i=0;i<n;i++){ Point2D p1=new Point2D.Double(X[i], Y[i]); Point2D p2=new Point2D.Double(X[(i+1)%n], Y[(i+1)%n]); Line2D l=new Line2D.Double(p1, p2); mn=Math.min(mn,l.ptSegDistSq(px, py)); } // System.out.println(mx + " " + mn); System.out.printf("%.12f", Math.PI*(mx-mn)); System.out.println(); } }
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
948f3e6d06072e7e586d8abd1af719fb
train_000.jsonl
1452789300
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ BufferedReader buf; PrintWriter out; class Pt{ double x,y; Pt(double x, double y) { super(); this.x = x; this.y = y; } double dist(Pt to){ return Math.sqrt( (to.x-this.x)*(to.x-this.x) + (to.y-this.y)*(to.y-this.y) ); } Pt sub(Pt a){return new Pt(x - a.x,y - a.y);} Pt add(Pt a){return new Pt(a.x + x,a.y + y);} Pt mult(double val){return new Pt(x * val,y * val);} double dot(Pt a){return a.x * x + a.y * y;} double distToLine(Pt a0, Pt a1){ return (a0.y - a1.y)*x + (a1.x - a0.x)*y + (a0.x*a1.y - a1.x*a0.y) / Math.sqrt( (a1.x - a0.x)*(a1.x - a0.x) + (a1.y - a0.y)*(a1.y - a0.y)); } double distToSegment(Pt a0, Pt a1) { Pt v = a1.sub(a0); Pt w = this.sub(a0); double c1 = w.dot(v); if ( c1 <= 0 ) return this.dist(a0); double c2 = v.dot(v); if ( c2 <= c1 ) return this.dist(a1); double b = c1 / c2; Pt pb = a0.add(v.mult(b)); return this.dist(pb); } } public static void main(String[] args) throws Exception { new Main(); } Main() throws IOException{ //buf = new BufferedReader(new FileReader("b.in"));out = new PrintWriter(new FileWriter("b.out")); buf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); out.close(); } private void solve() throws IOException { String[] in = buf.readLine().split(" "); int n = Integer.parseInt(in[0]); Pt p = new Pt(Double.parseDouble(in[1]),Double.parseDouble(in[2])); Double l = null,r = null; Pt a[] = new Pt[n+1]; for (int i = 0; i < n; i++) { in = buf.readLine().split(" "); a[i] = new Pt(Double.parseDouble(in[0]),Double.parseDouble(in[1])); if(l == null && r== null){ l = r = p.dist(a[i]); }else{ double dist = p.dist(a[i]); if(l>dist) l = dist; if(r<dist) r = dist; } } a[n] = a[0]; for (int i = 0; i < n; i++) { l = Math.min(l, p.distToSegment(a[i], a[i+1])); } System.out.format(Locale.ENGLISH,"%.8f", r*r*Math.PI - l*l*Math.PI); //System.out.print(r*r*Math.PI - l*l*Math.PI); } } /* 3 0 0 1 -1 -1 -1 0 -2 */
Java
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
NoteIn the first sample snow will be removed from that area:
Java 8
standard input
[ "geometry" ]
1d547a38250c7780ddcf10674417d5ff
The first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
1,900
Print a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
standard output
PASSED
245d3387f5edc1f4eb249a133a9f7079
train_000.jsonl
1358091000
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
256 megabytes
import java.util.*; public class D { static final int MAX = 50; static int [] a; static int n; static int p; static double [][] c; static { c = new double[MAX + 1][MAX + 1]; c[0][0] = 1; for (int i = 1; i <= MAX; ++i){ c[i][0] = 1; for (int j = 1; j <= i; ++j){ c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } } } static double solve(int exclude){ swap(a, exclude, n - 1); double [][][] dp = new double[n][n][p + 1]; dp[0][0][0] = 1; for (int i = 1; i <= n - 1; ++i){ for (int j = 0; j <= i; ++j){ for (int s = 0; s <= p; ++s){ dp[i][j][s] = dp[i - 1][j][s]; if (s >= a[i - 1] && j > 0){ dp[i][j][s] += dp[i - 1][j - 1][s - a[i - 1]]; } } } } swap(a, exclude, n - 1); double res = 0.0; for (int j = 1; j <= n - 1; ++j){ for (int s = 0; s <= p; ++s){ if (s + a[exclude] > p){ res += j*(dp[n - 1][j][s]/(c[n][j]*(n - j))); } } } return res; } static void swap(int [] a, int i, int j){ final int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void main(String [] args){ try (Scanner s = new Scanner(System.in)){ n = s.nextInt(); a = new int[n]; int sum = 0; for (int i = 0; i < n; ++i){ sum += (a[i] = s.nextInt()); } p = s.nextInt(); if (sum <= p){ System.out.println(n); }else{ double res = 0.0; for (int i = 0; i < n; ++i){ res += solve(i); } System.out.println(res); } } } }
Java
["3\n1 2 3\n3"]
2 seconds
["1.3333333333"]
NoteIn the first sample the people will come in the following orders: (1, 2, 3) β€” there will be two people in the restaurant; (1, 3, 2) β€” there will be one person in the restaurant; (2, 1, 3) β€” there will be two people in the restaurant; (2, 3, 1) β€” there will be one person in the restaurant; (3, 1, 2) β€” there will be one person in the restaurant; (3, 2, 1) β€” there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).
Java 7
standard input
[ "dp", "combinatorics" ]
b64f1667a8fd29d1de81414259a626c9
The first line contains integer n (1 ≀ n ≀ 50) β€” the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 50) β€” the guests' sizes in meters. The third line contains integer p (1 ≀ p ≀ 50) β€” the table's length in meters. The numbers in the lines are separated by single spaces.
1,900
In a single line print a real number β€” the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
standard output
PASSED
d03a1d9d9c8ab3b4d14df72292eecfa6
train_000.jsonl
1358091000
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.math.BigDecimal; import java.util.Scanner; /** * * @author psergiol */ public class Main { /** * @param args the command line arguments */ public static BigDecimal neg = new BigDecimal("-1"); public static BigDecimal[][][] dp; public static int[] v =new int[100]; public static BigDecimal rec(int n, int m, int p){ if(dp[n][m][p].compareTo(neg) == 0){ if(m == 0){ // cout <<"p = " <<p << endl; return dp[n][m][p] = BigDecimal.ONE; } if(n == 0) return BigDecimal.ZERO; BigDecimal cont = BigDecimal.ZERO; if(n > m) cont = rec(n-1, m, p); if(p>=v[n] && n >= m){ cont = cont.add(rec(n-1, m-1, p-v[n])); } return dp[n][m][p] = cont; } return dp[n][m][p]; } public static void main(String[] args) throws IOException { // TODO code application logic here int n, p, j, k; Scanner cin = new Scanner(System.in); BigDecimal[] fact = new BigDecimal[100]; BigDecimal suma, cuenta, valor; Integer i; n = cin.nextInt(); fact[0] = BigDecimal.ONE; for(i = 1; i <= n; i++){ v[i] =cin.nextInt(); fact[i] = fact[i-1].multiply(new BigDecimal(i.toString())); } p = cin.nextInt(); suma = BigDecimal.ZERO; cuenta = BigDecimal.ZERO; dp = new BigDecimal[n+1][n+1][p+1]; for(i = 0; i <= n; i++){ for(j = 0; j <= n; j++){ for(k = 0; k <= p; k++) dp[i][j][k] = neg; } } for(i = n, j = 1; i >= 1; i--, j++){ valor = (rec(n, i, p).multiply(fact[n-i])).multiply(fact[i]); // cout << "i = "<<i << " "<<valor<<" "<<rec(n, i, p) << " "<< fact[n-i] << " " << fact[i]<< endl; if(valor.compareTo(suma)>=0) cuenta = cuenta.add((valor.subtract(suma)).multiply(new BigDecimal(i.toString()))); suma = valor; } System.out.println(cuenta.divide(fact[n], 10, 1).toString()); } }
Java
["3\n1 2 3\n3"]
2 seconds
["1.3333333333"]
NoteIn the first sample the people will come in the following orders: (1, 2, 3) β€” there will be two people in the restaurant; (1, 3, 2) β€” there will be one person in the restaurant; (2, 1, 3) β€” there will be two people in the restaurant; (2, 3, 1) β€” there will be one person in the restaurant; (3, 1, 2) β€” there will be one person in the restaurant; (3, 2, 1) β€” there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).
Java 7
standard input
[ "dp", "combinatorics" ]
b64f1667a8fd29d1de81414259a626c9
The first line contains integer n (1 ≀ n ≀ 50) β€” the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 50) β€” the guests' sizes in meters. The third line contains integer p (1 ≀ p ≀ 50) β€” the table's length in meters. The numbers in the lines are separated by single spaces.
1,900
In a single line print a real number β€” the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
standard output
PASSED
491a2e1f3c4a1dfaaeba2922fe9b773c
train_000.jsonl
1358091000
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
256 megabytes
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; public class Main { public static int arr[] = new int[51]; public static int n, p, x, cnt; public static BigDecimal fact[] = new BigDecimal[51]; public static double mem[][][][] = new double[2][51][51][51]; public static double pre[][] = new double[51][51]; public static void main(String[] args) { fact[0] = fact[1] = BigDecimal.ONE; for (int i=2;i<=50;i++) fact[i] = fact[i - 1].multiply(BigDecimal.valueOf(i)); Scanner sc = new Scanner(System.in); n = sc.nextInt(); for (int i=0;i<n;i++) arr[i] = sc.nextInt(); for (int sel=0;sel<n;sel++) for (int lesseq=0;lesseq<=n-sel;lesseq++) pre[sel][lesseq] = BigDecimal.valueOf((n - sel - lesseq) * sel).multiply(fact[n-sel-1]).multiply(fact[sel]).divide(fact[n],100,1).doubleValue(); for (int lesseq=0;lesseq<=n;lesseq++) pre[n][lesseq] = n; p = sc.nextInt(); double ans = 0; int r,sel,lesseq,cap; double z = 0; for (x=p;x>0;x--) { for (r=n;r>=0;r--) for (sel=0;sel<=r;sel++) for (lesseq=0;lesseq<=r-sel;lesseq++) for (cap=0;cap<=x;cap++) { if (r == n) { if (cap > 0) mem[r&1][cap][sel][lesseq] = z; else mem[r&1][cap][sel][lesseq] = pre[sel][lesseq]; } else { if (cap >= arr[r]) mem[r&1][cap][sel][lesseq] = mem[(r+1)&1][cap][sel][lesseq + (arr[r] <= p-x ? 1 : 0)] + mem[(r+1)&1][cap - arr[r]][sel + 1][lesseq]; else mem[r&1][cap][sel][lesseq] = mem[(r+1)&1][cap][sel][lesseq + (arr[r] <= p-x ? 1 : 0)]; } } ans = ans + mem[0][x][0][0]; } System.out.println(ans); } }
Java
["3\n1 2 3\n3"]
2 seconds
["1.3333333333"]
NoteIn the first sample the people will come in the following orders: (1, 2, 3) β€” there will be two people in the restaurant; (1, 3, 2) β€” there will be one person in the restaurant; (2, 1, 3) β€” there will be two people in the restaurant; (2, 3, 1) β€” there will be one person in the restaurant; (3, 1, 2) β€” there will be one person in the restaurant; (3, 2, 1) β€” there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).
Java 7
standard input
[ "dp", "combinatorics" ]
b64f1667a8fd29d1de81414259a626c9
The first line contains integer n (1 ≀ n ≀ 50) β€” the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 50) β€” the guests' sizes in meters. The third line contains integer p (1 ≀ p ≀ 50) β€” the table's length in meters. The numbers in the lines are separated by single spaces.
1,900
In a single line print a real number β€” the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
standard output
PASSED
40aea1beaca839f58fab7a299ab92ea1
train_000.jsonl
1358091000
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.acos(-1.0); private final int SIZEN = (int)(1e5); private final int MOD = (int)(1e9 + 7); public void foo() { int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0;i < n;++i) { a[i] = scan.nextInt(); } int p = scan.nextInt(); double[][] dp = new double[n + 1][p + 1]; dp[0][0] = 1; for(int i = 0;i < n;++i) { for(int j = n;j >= 1;--j) { for(int k = p;k >= a[i];--k) { dp[j][k] += dp[j - 1][k - a[i]]; } } } double[] f = new double[n + 1]; f[0] = 1; for(int i = 1;i <= n;++i) { f[i] = i * f[i - 1]; } double ans = 0; for(int i = 0;i <= n;++i) { for(int j = 1;j <= p;++j) { ans += dp[i][j] * f[i] * f[n - i]; } } out.println(ans / f[n]); } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } /** * get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.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 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 & 15; 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 & 15) * m; c = read(); } } return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["3\n1 2 3\n3"]
2 seconds
["1.3333333333"]
NoteIn the first sample the people will come in the following orders: (1, 2, 3) β€” there will be two people in the restaurant; (1, 3, 2) β€” there will be one person in the restaurant; (2, 1, 3) β€” there will be two people in the restaurant; (2, 3, 1) β€” there will be one person in the restaurant; (3, 1, 2) β€” there will be one person in the restaurant; (3, 2, 1) β€” there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).
Java 7
standard input
[ "dp", "combinatorics" ]
b64f1667a8fd29d1de81414259a626c9
The first line contains integer n (1 ≀ n ≀ 50) β€” the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 50) β€” the guests' sizes in meters. The third line contains integer p (1 ≀ p ≀ 50) β€” the table's length in meters. The numbers in the lines are separated by single spaces.
1,900
In a single line print a real number β€” the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
standard output
PASSED
b4eacd3d555ac0105257a01d4be86b7c
train_000.jsonl
1358091000
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); private static int OO = (int) 1e9 + 9, r; private static int[] dx = {0, 0, 1, -1}; private static int[] dy = {1, -1, 0, 0}; private static int[] arr = new int[32]; public static void main(String[] args) { int n = scanner.nextInt(), k = scanner.nextInt(), i; int[] arr = new int[n]; for (i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } i = 0; while (k > 0 && i < n && arr[i] < 0) { k--; arr[i] *= -1; i++; } if (k == 0) { System.out.println(sum(arr)); } else { Arrays.sort(arr); if (k % 2 == 0) { System.out.println(sum(arr)); } else { arr[0] *= -1; System.out.println(sum(arr)); } } } private static int sum(int[] arr) { int r = 0; for (int value : arr) { r += value; } return r; } }
Java
["3 2\n-1 -1 1", "3 1\n-1 -1 1"]
2 seconds
["3", "1"]
NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
Java 11
standard input
[ "greedy" ]
befd3b1b4afe19ff619c0b34ed1a4966
The first line contains two integers n and k (1 ≀ n, k ≀ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≀ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
1,200
In the single line print the answer to the problem β€” the maximum total income that we can obtain after exactly k changes.
standard output
PASSED
8ce56cdf8fe21f5b3315ae26d5fed12c
train_000.jsonl
1358091000
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
256 megabytes
import java.util.*; public class Prob87{ public static long compute(Vector<Integer> v , int count,int k){ if(count == 0){ int min = v.elementAt(0); int temp = min; min =min * (int)Math.pow((double)-1,k); if(min != temp){ v.add(min); v.add(min); } } else{ if(k<=count){ for(int i=0;i<k;i++){ v.set(i,v.elementAt(i)*(-1)); } // System.out.println(v); } else{ for(int i=0;i<count;i++){ v.set(i,v.elementAt(i) * (-1)); } int rem = k - count; // System.out.println(v); int min = Collections.min(v); int temp = min; // System.out.println("remaining count = "+count+" min = "+min); min = min *(int)Math.pow(-1,rem); if(min != temp){ v.add(min); v.add(min); } } } long sum = 0; for(int i=0;i<v.size();i++){ sum += v.elementAt(i); } return sum; } public static void main(String args[]){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); // int count = 0; Vector<Integer> v = new Vector<>(); // Vector<Integer> neg = new Vector<>(); int count = 0; for(int i=0;i<n;i++){ int no = s.nextInt(); if(no<0){ count++; } v.add(no); } System.out.println(compute(v,count,k)); } }
Java
["3 2\n-1 -1 1", "3 1\n-1 -1 1"]
2 seconds
["3", "1"]
NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
Java 11
standard input
[ "greedy" ]
befd3b1b4afe19ff619c0b34ed1a4966
The first line contains two integers n and k (1 ≀ n, k ≀ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≀ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
1,200
In the single line print the answer to the problem β€” the maximum total income that we can obtain after exactly k changes.
standard output
PASSED
d8970969ad11caa70beaf2962b7bb437
train_000.jsonl
1358091000
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class practice{ static Scanner sc = new Scanner(System.in); public static int[] read(int n) { int[] arr= new int[n]; for(int i=0;i<n;++i) { arr[i]=sc.nextInt(); } return arr; } public static int function(int n,int k,int[] arr) { int ans=0; Arrays.sort(arr); int i=0; while(i<arr.length && arr[i]<0 && k>0) { arr[i]*=-1; k--; i++; } if(k>0 && k%2==1) { Arrays.sort(arr); arr[0]*=-1; } for(int j=0;j<arr.length;++j) { ans+=arr[j]; } return ans; } public static void main(String[] args) { // TODO Auto-generated method stub int n= sc.nextInt(); int k= sc.nextInt(); int[] arr =read(n); System.out.println(function(n,k,arr)); } }
Java
["3 2\n-1 -1 1", "3 1\n-1 -1 1"]
2 seconds
["3", "1"]
NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
Java 11
standard input
[ "greedy" ]
befd3b1b4afe19ff619c0b34ed1a4966
The first line contains two integers n and k (1 ≀ n, k ≀ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≀ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
1,200
In the single line print the answer to the problem β€” the maximum total income that we can obtain after exactly k changes.
standard output
PASSED
9b9a19cad54174f5ddee354311aa1332
train_000.jsonl
1358091000
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
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 sc=new Scanner(System.in); boolean b=true; int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){a[i]=sc.nextInt();if(a[i]==0)b=false;} int low=0;int high=n-1;int j=-1; while(low<=high){ int mid=low+(high-low)/2; if(a[mid]<0){low=mid+1;j=mid;} else high=mid-1; } j++;int sum=0; //System.out.println(j); if(j>=k){for(int i=0;i<k;i++){a[i]=Math.abs(a[i]);}} else {for(int i=0;i<j;i++){a[i]=Math.abs(a[i]);}if(b){ if((k-j)%2==1) { if(j==n){a[j-1]=-1*a[j-1];} else if(j==0){a[j]=-1*a[j];} else {if(a[j]>a[j-1]){a[j-1]=-1*a[j-1];} else {a[j]=-1*a[j];} } } }} for(int i=0;i<n;i++){sum+=a[i];} System.out.println(sum); } } /*3 2 -1 -1 1 */
Java
["3 2\n-1 -1 1", "3 1\n-1 -1 1"]
2 seconds
["3", "1"]
NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
Java 11
standard input
[ "greedy" ]
befd3b1b4afe19ff619c0b34ed1a4966
The first line contains two integers n and k (1 ≀ n, k ≀ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≀ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
1,200
In the single line print the answer to the problem β€” the maximum total income that we can obtain after exactly k changes.
standard output
PASSED
a68e2c857c47dc15e2bd367913a60676
train_000.jsonl
1358091000
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
256 megabytes
import java.util.*; public class romaAndChangingSigns1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n]; long sum=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } Arrays.sort(a); for(int i=0;i<n;i++) { if(a[i]<0 && k>0) { a[i]=a[i]*-1; k--; if(k==0) { break; } } } for(int i=0;i<n;i++) { sum=sum+a[i]; } if(k>0) { Arrays.sort(a); if(k%2==0) { System.out.println(sum); } else { System.out.println(sum-2*a[0]); } } else { System.out.println(sum); } } }
Java
["3 2\n-1 -1 1", "3 1\n-1 -1 1"]
2 seconds
["3", "1"]
NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
Java 11
standard input
[ "greedy" ]
befd3b1b4afe19ff619c0b34ed1a4966
The first line contains two integers n and k (1 ≀ n, k ≀ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≀ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
1,200
In the single line print the answer to the problem β€” the maximum total income that we can obtain after exactly k changes.
standard output
PASSED
87cc8bcc4ee6ad33a3c4c5211ece3cf1
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class ACMIND { static FastReader scan; static PrintWriter pw; static long MOD = 998244353; static long INF = 1_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<27) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n,l[],r[]; static boolean can[][]; static ArrayList<Pair> segments; static long res,dp[][][]; static void solve() throws IOException { scan = new FastReader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); n = ni(); l = new int[n]; r = new int[n]; TreeSet<Integer> set = new TreeSet<>(); for(int i=0;i<n;++i) { l[i] = ni(); r[i] = ni(); set.add(l[i]); set.add(r[i]); } segments = new ArrayList<>(); while(!set.isEmpty()) { int x = set.pollFirst(); segments.add(new Pair(x,x)); if(!set.isEmpty() && x+1<set.first()) { segments.add(new Pair(x+1, set.first()-1)); } } //pa("segments", segments); can = new boolean[n][segments.size()]; for(int i=0;i<n;++i) { for(int j=0;j<segments.size();++j) { if(segments.get(j).x >= l[i] && segments.get(j).y<=r[i]) { can[i][j] = true; } } } // for(int i=0;i<n;++i) { // for(int j=0;j<segments.size();++j) { // p(can[i][j]); // } // pl(); // } dp = new long[n][segments.size()][n+1]; for(int i=0;i<n;++i) { for(int j=0;j<segments.size();++j) { for(int k=0;k<=n;++k) { dp[i][j][k] = -1; } } } long den = 1; for(int i=0;i<n;++i) { den*=1L * (r[i] - l[i] + 1); den%=MOD; } //pl("Den : "+den); long ans = f(0,segments.size() - 1,0); //pl("ans : "+ans); ans*=modpow(den, MOD-2, MOD); ans%=MOD; pl(ans); pw.flush(); pw.close(); } static long f(int idx, int which, int prev) { if(idx==n) { if(which>=0) { return calc(segments.get(which).y - segments.get(which).x + prev ,prev); } return 0; } if(which<0) { return 0; } if(dp[idx][which][prev] != -1) { return dp[idx][which][prev]; } long ans = 0; if(can[idx][which]) { ans+=f(idx+1, which, prev+1); } ans+=calc(segments.get(which).y - segments.get(which).x + prev ,prev) * f(idx, which-1, 0); ans%=MOD; return dp[idx][which][prev] = ans; } static long calc(long n, long r) { if(r<0 || r>n) { return 0; } long num = 1, den = 1; for(int i=1;i<=r;++i) { num*=(n-r+i); num%=MOD; den*=i; den%=MOD; } return (num*modpow(den, MOD-2, MOD))%MOD; } static long modpow(long x,long y,long mod) { res = 1; while(y>0) { if((y&1)==1) res = (res*x)%mod; y>>=1; x = (x*x)%mod; } return res; } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "("+x+","+y+")"; } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; 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
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
b6c5d793c2e2b77012c6b60282e6acd4
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class f { class DSU { int[] p; public DSU(int n) { p = new int[n]; for(int i = 0 ; i < n ; i++) p[i] = i; } int find(int x) { return x == p[x] ? x : (p[x] = find(p[x])); } boolean union(int u, int v) { int p1 = find(u), p2 = find(v); if(p1 != p2) { p[p1] = p2; return true; } return false; } } long modinv(long x) { return modpow(x, mod - 2); } long modpow(long b, long e) { if(e == 0) return 1; long r = modpow(b, e >> 1); if((e & 1) == 0) return mult(r, r); return mult(b, mult(r, r)); } long mult(long a, long b) { if(a * b >= mod) return a * b % mod; return a * b; } long add(long a, long b) { if(a + b >= mod) return a + b - mod; return a + b; } boolean inrange(long[] r1, long[] r2) { // r1 in r2 return (r2[0] <= r1[0] && r1[0] <= r2[1]) || (r2[0] <= r1[1] && r1[1] <= r2[1]); } long go(int at1, int at2) { if(at2 == m) return at1 == n ? 1 : 0; if(at1 == n) return 1; if(dp[at1][at2] != -1) return dp[at1][at2]; long res = go(at1, at2 + 1); for(int i = 1 ; at1 + i <= n ; i++) { if(!inrange(nranges[at2], ranges[at1 + i - 1])) break; long t = go(at1 + i, at2 + 1); res = add(res, mult(t, precmp[at2][i])); } return dp[at1][at2] = res; } // precmp[i][j] is the number of ways // for j random numbers to be generated from // range i, such that the numbers are non decreasing long[][] precmp; int n, m; long[][] ranges, nranges; long[] lens; // length of the ith nrange long[][] dp; final int mod = 998244353; public f() { FS scan = new FS(); n = scan.nextInt(); ranges = new long[n][3]; TreeSet<long[]> set = new TreeSet<>(new Comparator<long[]>() { public int compare(long[] a, long[] b) { if(a[0] == b[0]) return Long.compare(a[1], b[1]); return Long.compare(a[0], b[0]); } }); for(int i = 0 ; i < n ; i++) { ranges[i][0] = scan.nextLong(); ranges[i][1] = scan.nextLong(); set.add(new long[] {ranges[i][0], 0}); set.add(new long[] {ranges[i][1], 1}); } List<long[]> newranges = new ArrayList<>(); for(long[] val : set) { if(set.higher(val) == null) break; long[] next = set.higher(val); long left = val[0]; long right = next[0]; if(val[1] == 1) left++; if(next[1] == 0) right--; if(left <= right) newranges.add(new long[] {left, right}); } Collections.sort(newranges, (a, b) -> Long.compare(b[1], a[1])); m = newranges.size(); nranges = new long[m][2]; lens = new long[m]; for(int i = 0 ; i < m ; i++) { nranges[i] = newranges.get(i); lens[i] = nranges[i][1] - nranges[i][0] + 1; } long[] inv = new long[100]; inv[1] = 1; for (int i = 2; i < inv.length; ++i) inv[i] = (mod - (mod / i) * inv[mod % i] % mod) % mod; precmp = new long[m][n + 1]; for(int i = 0 ; i < m ; i++) { precmp[i][0] = 1; for(int j = 1 ; j <= n ; j++) { precmp[i][j] = mult(precmp[i][j - 1], lens[i] + j - 1); precmp[i][j] = mult(precmp[i][j], inv[j]); } } dp = new long[n][m]; for(int i = 0 ; i < n ; i++) Arrays.fill(dp[i], -1); long valid = go(0, 0); long all = 1; for(int i = 0 ; i < n ; i++) all = mult(all, ranges[i][1] - ranges[i][0] + 1); System.out.println(mult(valid, modinv(all))); } class FS { 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) throws Exception { new f(); } } /* 3 1 10 3 10 8 15 */
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
358406266e9b84ecb9d199f4dab0f5d5
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class f { class DSU { int[] p; public DSU(int n) { p = new int[n]; for(int i = 0 ; i < n ; i++) p[i] = i; } int find(int x) { return x == p[x] ? x : (p[x] = find(p[x])); } boolean union(int u, int v) { int p1 = find(u), p2 = find(v); if(p1 != p2) { p[p1] = p2; return true; } return false; } } long modinv(long x) { return modpow(x, mod - 2); } long modpow(long b, long e) { if(e == 0) return 1; long r = modpow(b, e >> 1); if((e & 1) == 0) return mult(r, r); return mult(b, mult(r, r)); } long mult(long a, long b) { if(a * b >= mod) return a * b % mod; return a * b; } long add(long a, long b) { if(a + b >= mod) return a + b - mod; return a + b; } // checks if r1 is in r2 boolean inrange(long[] r1, long[] r2) { return (r2[0] <= r1[0] && r1[0] <= r2[1]) || (r2[0] <= r1[1] && r1[1] <= r2[1]); } // at1 is the position in the original ranges // at2 is the position in the new ranges long go(int at1, int at2) { if(at2 == m) return at1 == n ? 1 : 0; if(at1 == n) return 1; if(dp[at1][at2] != -1) return dp[at1][at2]; long res = 0; for(int i = 0 ; i <= n ; i++) { if(at1 + i > n) break; if(i > 0 && !inrange(nranges[at2], ranges[at1 + i - 1])) break; long t = go(at1 + i, at2 + 1); res = add(res, mult(t, precmp[at2][i])); } return dp[at1][at2] = res; } // precmp[i][j] is the number of ways // for j random numbers to be generated from // range i, such that the numbers are non decreasing long[][] precmp; int n, m; long[][] ranges, nranges; long[] lens; // length of the ith nrange long[][] dp; final int mod = 998244353; public f() { FS scan = new FS(); n = scan.nextInt(); ranges = new long[n][3]; for(int i = 0 ; i < n ; i++) { ranges[i][0] = scan.nextLong(); ranges[i][1] = scan.nextLong(); ranges[i][2] = i; } Arrays.sort(ranges, (a, b) -> Long.compare(a[0], b[0])); DSU dsu = new DSU(n); int index = 0; long curmax = 0; for(int i = 0 ; i < n ; i++) { if(ranges[i][0] <= curmax) { dsu.union(index, i); curmax = Math.max(curmax, ranges[i][1]); } else { curmax = ranges[i][1]; index = i; } } Arrays.sort(ranges, (a, b) -> Long.compare(a[2], b[2])); List<long[]>[] cmps = new ArrayList[n]; for(int i = 0 ; i < n ; i++) cmps[i] = new ArrayList<>(); for(int i = 0 ; i < n ; i++) cmps[dsu.find(i)].add(ranges[i]); List<long[]> newranges = new ArrayList<>(); boolean[] done = new boolean[n]; for(int i = 0 ; i < n ; i++) { if(!done[dsu.find(i)]) { done[dsu.find(i)] = true; TreeSet<long[]> set = new TreeSet<>(new Comparator<long[]>() { public int compare(long[] a, long[] b) { if(a[0] == b[0]) return Long.compare(a[1], b[1]); return Long.compare(a[0], b[0]); } }); for(long[] range : cmps[dsu.find(i)]) { set.add(new long[] {range[0], 0}); set.add(new long[] {range[1], 1}); } for(long[] val : set) { if(set.higher(val) == null) break; long[] next = set.higher(val); long left = val[0]; long right = next[0]; if(val[1] == 1) left++; if(next[1] == 0) right--; if(left <= right) newranges.add(new long[] {left, right}); } } } Collections.sort(newranges, (a, b) -> Long.compare(b[0], a[0])); m = newranges.size(); nranges = new long[m][2]; lens = new long[m]; for(int i = 0 ; i < m ; i++) { nranges[i] = newranges.get(i); lens[i] = nranges[i][1] - nranges[i][0] + 1; } long[] inv = new long[100]; inv[1] = 1; for (int i = 2; i < inv.length; ++i) inv[i] = (mod - (mod / i) * inv[mod % i] % mod) % mod; precmp = new long[m][n + 1]; for(int i = 0 ; i < m ; i++) { precmp[i][0] = 1; for(int j = 1 ; j <= n ; j++) { precmp[i][j] = mult(precmp[i][j - 1], lens[i] + j - 1); precmp[i][j] = mult(precmp[i][j], inv[j]); } } dp = new long[n][m]; for(int i = 0 ; i < n ; i++) Arrays.fill(dp[i], -1); long valid = go(0, 0); long all = 1; for(int i = 0 ; i < n ; i++) all = mult(all, ranges[i][1] - ranges[i][0] + 1); System.out.println(mult(valid, modinv(all))); } class FS { 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) throws Exception { new f(); } } /* 3 1 10 3 10 8 15 */
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
f9ef73dab0034a620a972344721da821
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class f { long modinv(long x) { return modpow(x, mod - 2); } long modpow(long b, long e) { if(e == 0) return 1; long r = modpow(b, e >> 1); if((e & 1) == 0) return mult(r, r); return mult(b, mult(r, r)); } long add(long a, long b) { return a + b >= mod ? a + b - mod : a + b; } long mult(long a, long b) { return a * b >= mod ? a * b % mod : a * b; } boolean inrange(long[] r1, long[] r2) { // r1 in r2 return (r2[0] <= r1[0] && r1[0] <= r2[1]) || (r2[0] <= r1[1] && r1[1] <= r2[1]); } long go(int at1, int at2) { if(at2 == m) return at1 == n ? 1 : 0; if(at1 == n) return 1; if(dp[at1][at2] != -1) return dp[at1][at2]; long res = go(at1, at2 + 1); for(int i = 1 ; at1 + i <= n ; i++) { if(!inrange(nranges[at2], ranges[at1 + i - 1])) break; long t = go(at1 + i, at2 + 1); res = add(res, mult(t, precmp[at2][i])); } return dp[at1][at2] = res; } final int mod = 998_244_353; long[][] ranges, nranges, precmp, dp; int n, m; public f() { long[] inv = new long[100]; inv[1] = 1; for (int i = 2; i < inv.length; ++i) inv[i] = (mod - (mod / i) * inv[mod % i] % mod) % mod; FS scan = new FS(); n = scan.nextInt(); long[] bounds = new long[n * 2]; ranges = new long[n][2]; long all = 1; for(int i = 0 ; i < n ; i++) { ranges[i][0] = scan.nextLong(); ranges[i][1] = scan.nextLong(); bounds[i] = ranges[i][0]; bounds[i + n] = ranges[i][1] + 1; all = mult(all, ranges[i][1] - ranges[i][0] + 1); } Arrays.sort(bounds); List<long[]> newranges = new ArrayList<>(); for(int i = bounds.length - 1 ; i > 0 ; i--) if(bounds[i] != bounds[i - 1]) newranges.add(new long[] {bounds[i - 1], bounds[i] - 1}); m = newranges.size(); nranges = new long[m][2]; precmp = new long[m][n + 1]; for(int i = 0 ; i < m ; i++) { nranges[i] = newranges.get(i); precmp[i][0] = 1; for(int j = 1 ; j <= n ; j++) precmp[i][j] = mult(mult(precmp[i][j - 1], nranges[i][1] - nranges[i][0] + 1 + j - 1), inv[j]); } dp = new long[n][m]; for(int i = 0 ; i < n ; i++) Arrays.fill(dp[i], -1); long valid = go(0, 0); System.out.println(mult(valid, modinv(all))); } class FS { 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) throws Exception { new f(); } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
566f60fe721bc405103e4abd9373ce39
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.util.Collection; import java.io.IOException; import java.util.stream.Collectors; import java.io.UncheckedIOException; import java.util.List; import java.util.stream.Stream; import java.util.TreeMap; import java.io.Closeable; import java.io.Writer; import java.util.Map.Entry; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FGoodContest solver = new FGoodContest(); solver.solve(1, in, out); out.close(); } } static class FGoodContest { Modular mod = new Modular(998244353); Power power = new Power(mod); GravityModLagrangeInterpolation zero = new GravityModLagrangeInterpolation(mod, 1); GravityModLagrangeInterpolation one = new GravityModLagrangeInterpolation(mod, 1); { zero.addPoint(0, 0); one.addPoint(0, 1); } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[][] lr = new int[n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { lr[i][j] = in.readInt(); } } SequenceUtils.reverse(lr, 0, n - 1); SegmentFunctions functions = new SegmentFunctions(); functions.add(new SegmentFunction(-1, lr[0][0] - 1, zero)); functions.add(new SegmentFunction(lr[0][0], lr[0][1], one)); functions.add(new SegmentFunction(lr[0][1] + 1, (int) 1e9, zero)); for (int i = 1; i < n; i++) { functions = build(functions, lr[i][0], lr[i][1], true, i + 1); } functions = build(functions, 0, (int) 1e9 - 1, false, n + 1); int valid = functions.apply((int) 1e9).p.getYByInterpolation((int) 1e9); int total = 1; for (int[] x : lr) { total = mod.mul(total, x[1] - x[0] + 1); } int ans = mod.mul(valid, power.inverseByFermat(total)); out.println(ans); } public SegmentFunctions build(SegmentFunctions functions, int l, int r, boolean addTail, int trainLimit) { List<Interval> intervals = new ArrayList<>(); for (SegmentFunction x : functions.functionTreeSet.values()) { intervals.add(x.interval); } for (Interval interval : intervals) { if (interval.contain(l)) { intervals.remove(interval); intervals.addAll(Arrays.asList(interval.split(l - 1))); break; } } for (Interval interval : intervals) { if (interval.contain(r)) { intervals.remove(interval); intervals.addAll(Arrays.asList(interval.split(r))); break; } } intervals = intervals.stream().filter(x -> !x.empty()).collect(Collectors.toList()); intervals.sort((a, b) -> a.l - b.l); SegmentFunctions ans = new SegmentFunctions(); ans.add(new SegmentFunction(intervals.get(0).l - 1, intervals.get(0).l - 1, zero)); for (Interval interval : intervals) { if (interval.l > r) { break; } GravityModLagrangeInterpolation interpolation = new GravityModLagrangeInterpolation(mod, trainLimit); SegmentFunction tail = ans.functionTreeSet.lastEntry().getValue(); SegmentFunction bot = functions.apply(interval.l); int ps = tail.p.getYByInterpolation(interval.l - 1); for (int i = 0; i < trainLimit; i++) { int x = mod.valueOf(interval.l + i); ps = mod.plus(ps, bot.p.getYByInterpolation(x)); interpolation.addPoint(x, ps); } ans.add(new SegmentFunction(interval.l, interval.r, interpolation)); } while (ans.functionTreeSet.firstKey() < l) { ans.functionTreeSet.pollFirstEntry(); } ans.add(new SegmentFunction(intervals.get(0).l, l - 1, zero)); if (addTail) { ans.add(new SegmentFunction(r + 1, intervals.get(intervals.size() - 1).r, zero)); } return ans; } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static class SequenceUtils { public static <T> void swap(T[] data, int i, int j) { T tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static <T> void reverse(T[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } } static class SegmentFunction { Interval interval; GravityModLagrangeInterpolation p; public SegmentFunction(int l, int r, GravityModLagrangeInterpolation p) { this.interval = new Interval(l, r); this.p = p; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class GravityModLagrangeInterpolation { private Power power; private Modular modular; Map<Integer, Integer> points = new HashMap<>(); Polynomial xs; Polynomial ys; Polynomial lx; Polynomial lxBuf; Polynomial invW; int n; public GravityModLagrangeInterpolation(Modular modular, int expect) { this(new Power(modular), expect); } public GravityModLagrangeInterpolation(Power power, int expect) { this.modular = power.getModular(); this.power = power; xs = new Polynomial(expect); ys = new Polynomial(expect); lx = new Polynomial(expect); lxBuf = new Polynomial(expect); invW = new Polynomial(expect); lx.setN(1); lx.coes[0] = 1; } public void addPoint(int x, int y) { x = modular.valueOf(x); y = modular.valueOf(y); Integer exist = points.get(x); if (exist != null) { if (exist != y) { throw new RuntimeException(); } return; } points.put(x, y); xs.setN(n + 1); xs.coes[n] = x; ys.setN(n + 1); ys.coes[n] = y; lx.multiply(modular.valueOf(-x), lxBuf); switchBuf(); invW.setN(n + 1); invW.coes[n] = 1; for (int i = 0; i < n; i++) { invW.coes[i] = modular.mul(invW.coes[i], modular.subtract(xs.coes[i], x)); invW.coes[n] = modular.mul(invW.coes[n], modular.subtract(x, xs.coes[i])); } n++; } public int getYByInterpolation(int x) { x = modular.valueOf(x); if (points.containsKey(x)) { return points.get(x); } int y = lx.function(x); int sum = 0; for (int i = 0; i < n; i++) { int val = modular.mul(invW.coes[i], modular.subtract(x, xs.coes[i])); val = modular.mul(power.inverseByFermat(val), ys.coes[i]); sum = modular.plus(sum, val); } return modular.mul(y, sum); } public Polynomial preparePolynomial() { Polynomial ans = new Polynomial(n); Polynomial ansBuf = new Polynomial(n); for (int i = 0; i < n; i++) { int c = modular.mul(ys.coes[i], power.inverseByFermat(invW.coes[i])); lx.div(modular.valueOf(-xs.coes[i]), ansBuf); ansBuf.mulConstant(c, ansBuf); ans.plus(ansBuf, ans); } return ans; } private void switchBuf() { Polynomial tmp = lx; lx = lxBuf; lxBuf = tmp; } public String toString() { return preparePolynomial().toString(); } public class Polynomial { private int[] coes; private int n; public int function(int x) { int ans = 0; int xi = 1; for (int i = 0; i < n; i++) { ans = modular.plus(ans, modular.mul(xi, coes[i])); xi = modular.mul(xi, x); } return ans; } public Polynomial(int n) { this.n = 0; coes = new int[n]; } public void ensureLength() { if (coes.length >= n) { return; } int proper = coes.length; while (proper < n) { proper = Math.max(proper + proper, proper + 10); } coes = Arrays.copyOf(coes, proper); } public void setN(int n) { this.n = n; ensureLength(); } public void multiply(int b, Polynomial ans) { ans.setN(n + 1); for (int i = 0; i < n; i++) { ans.coes[i] = modular.mul(coes[i], b); } ans.coes[n] = 0; for (int i = 0; i < n; i++) { ans.coes[i + 1] = modular.plus(ans.coes[i + 1], coes[i]); } } public void mulConstant(int b, Polynomial ans) { ans.setN(n); for (int i = 0; i < n; i++) { ans.coes[i] = modular.mul(coes[i], b); } } public void plus(Polynomial a, Polynomial ans) { ans.setN(Math.max(n, a.n)); for (int i = 0; i < n; i++) { ans.coes[i] = coes[i]; } for (int i = 0; i < a.n; i++) { ans.coes[i] = modular.plus(ans.coes[i], a.coes[i]); } } public void div(int b, Polynomial ans) { ans.setN(n - 1); int affect = 0; for (int i = n - 1; i >= 1; i--) { affect = modular.plus(affect, coes[i]); ans.coes[i - 1] = affect; affect = modular.mul(-affect, b); } } public String toString() { return Arrays.toString(Arrays.copyOfRange(coes, 0, n)); } } } static class Interval { int l; int r; public boolean contain(int x) { return l <= x && x <= r; } public boolean empty() { return l > r; } public Interval(int l, int r) { this.l = l; this.r = r; } public Interval[] split(int m) { return new Interval[]{new Interval(l, m), new Interval(m + 1, r)}; } public String toString() { return "(" + l + "," + r + ")"; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Power { final Modular modular; public Modular getModular() { return modular; } public Power(Modular modular) { this.modular = modular; } public int pow(int x, int n) { if (n == 0) { return modular.valueOf(1); } long r = pow(x, n >> 1); r = modular.valueOf(r * r); if ((n & 1) == 1) { r = modular.valueOf(r * x); } return (int) r; } public int inverseByFermat(int x) { return pow(x, modular.m - 2); } } static class SegmentFunctions { TreeMap<Integer, SegmentFunction> functionTreeSet = new TreeMap<>(); public void add(SegmentFunction function) { functionTreeSet.put(function.interval.l, function); } public SegmentFunction apply(int x) { SegmentFunction function = functionTreeSet.floorEntry(x).getValue(); return function; } } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
706624e0d3240497ecc0dd720f6e0c7e
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.util.Collection; import java.io.IOException; import java.util.stream.Collectors; import java.io.UncheckedIOException; import java.util.List; import java.util.stream.Stream; import java.util.TreeMap; import java.io.Closeable; import java.io.Writer; import java.util.Map.Entry; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FGoodContest solver = new FGoodContest(); solver.solve(1, in, out); out.close(); } } static class FGoodContest { Modular mod = new Modular(998244353); Power power = new Power(mod); GravityModLagrangeInterpolation zero = new GravityModLagrangeInterpolation(mod, 1); GravityModLagrangeInterpolation one = new GravityModLagrangeInterpolation(mod, 1); int trainLimit = 100; { zero.addPoint(0, 0); one.addPoint(0, 1); } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[][] lr = new int[n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { lr[i][j] = in.readInt(); } } SequenceUtils.reverse(lr, 0, n - 1); SegmentFunctions functions = new SegmentFunctions(); functions.add(new SegmentFunction(-1, lr[0][0] - 1, zero)); functions.add(new SegmentFunction(lr[0][0], lr[0][1], one)); functions.add(new SegmentFunction(lr[0][1] + 1, (int) 1e9, zero)); for (int i = 1; i < n; i++) { functions = build(functions, lr[i][0], lr[i][1], true); } functions = build(functions, 0, (int) 1e9 - 1, false); int valid = functions.apply((int) 1e9).p.getYByInterpolation((int) 1e9); int total = 1; for (int[] x : lr) { total = mod.mul(total, x[1] - x[0] + 1); } int ans = mod.mul(valid, power.inverseByFermat(total)); out.println(ans); } public SegmentFunctions build(SegmentFunctions functions, int l, int r, boolean addTail) { List<Interval> intervals = new ArrayList<>(); for (SegmentFunction x : functions.functionTreeSet.values()) { intervals.add(x.interval); } for (Interval interval : intervals) { if (interval.contain(l)) { intervals.remove(interval); intervals.addAll(Arrays.asList(interval.split(l - 1))); break; } } for (Interval interval : intervals) { if (interval.contain(r)) { intervals.remove(interval); intervals.addAll(Arrays.asList(interval.split(r))); break; } } intervals = intervals.stream().filter(x -> !x.empty()).collect(Collectors.toList()); intervals.sort((a, b) -> a.l - b.l); SegmentFunctions ans = new SegmentFunctions(); ans.add(new SegmentFunction(intervals.get(0).l - 1, intervals.get(0).l - 1, zero)); for (Interval interval : intervals) { if (interval.l > r) { break; } GravityModLagrangeInterpolation interpolation = new GravityModLagrangeInterpolation(mod, trainLimit); SegmentFunction tail = ans.functionTreeSet.lastEntry().getValue(); SegmentFunction bot = functions.apply(interval.l); int ps = tail.p.getYByInterpolation(interval.l - 1); for (int i = 0; i < trainLimit; i++) { int x = mod.valueOf(interval.l + i); ps = mod.plus(ps, bot.p.getYByInterpolation(x)); interpolation.addPoint(x, ps); } ans.add(new SegmentFunction(interval.l, interval.r, interpolation)); } while (ans.functionTreeSet.firstKey() < l) { ans.functionTreeSet.pollFirstEntry(); } ans.add(new SegmentFunction(intervals.get(0).l, l - 1, zero)); if (addTail) { ans.add(new SegmentFunction(r + 1, intervals.get(intervals.size() - 1).r, zero)); } return ans; } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static class SequenceUtils { public static <T> void swap(T[] data, int i, int j) { T tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static <T> void reverse(T[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } } static class SegmentFunction { Interval interval; GravityModLagrangeInterpolation p; public SegmentFunction(int l, int r, GravityModLagrangeInterpolation p) { this.interval = new Interval(l, r); this.p = p; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class GravityModLagrangeInterpolation { private Power power; private Modular modular; Map<Integer, Integer> points = new HashMap<>(); Polynomial xs; Polynomial ys; Polynomial lx; Polynomial lxBuf; Polynomial invW; int n; public GravityModLagrangeInterpolation(Modular modular, int expect) { this(new Power(modular), expect); } public GravityModLagrangeInterpolation(Power power, int expect) { this.modular = power.getModular(); this.power = power; xs = new Polynomial(expect); ys = new Polynomial(expect); lx = new Polynomial(expect); lxBuf = new Polynomial(expect); invW = new Polynomial(expect); lx.setN(1); lx.coes[0] = 1; } public void addPoint(int x, int y) { x = modular.valueOf(x); y = modular.valueOf(y); Integer exist = points.get(x); if (exist != null) { if (exist != y) { throw new RuntimeException(); } return; } points.put(x, y); xs.setN(n + 1); xs.coes[n] = x; ys.setN(n + 1); ys.coes[n] = y; lx.multiply(modular.valueOf(-x), lxBuf); switchBuf(); invW.setN(n + 1); invW.coes[n] = 1; for (int i = 0; i < n; i++) { invW.coes[i] = modular.mul(invW.coes[i], modular.subtract(xs.coes[i], x)); invW.coes[n] = modular.mul(invW.coes[n], modular.subtract(x, xs.coes[i])); } n++; } public int getYByInterpolation(int x) { x = modular.valueOf(x); if (points.containsKey(x)) { return points.get(x); } int y = lx.function(x); int sum = 0; for (int i = 0; i < n; i++) { int val = modular.mul(invW.coes[i], modular.subtract(x, xs.coes[i])); val = modular.mul(power.inverseByFermat(val), ys.coes[i]); sum = modular.plus(sum, val); } return modular.mul(y, sum); } public Polynomial preparePolynomial() { Polynomial ans = new Polynomial(n); Polynomial ansBuf = new Polynomial(n); for (int i = 0; i < n; i++) { int c = modular.mul(ys.coes[i], power.inverseByFermat(invW.coes[i])); lx.div(modular.valueOf(-xs.coes[i]), ansBuf); ansBuf.mulConstant(c, ansBuf); ans.plus(ansBuf, ans); } return ans; } private void switchBuf() { Polynomial tmp = lx; lx = lxBuf; lxBuf = tmp; } public String toString() { return preparePolynomial().toString(); } public class Polynomial { private int[] coes; private int n; public int function(int x) { int ans = 0; int xi = 1; for (int i = 0; i < n; i++) { ans = modular.plus(ans, modular.mul(xi, coes[i])); xi = modular.mul(xi, x); } return ans; } public Polynomial(int n) { this.n = 0; coes = new int[n]; } public void ensureLength() { if (coes.length >= n) { return; } int proper = coes.length; while (proper < n) { proper = Math.max(proper + proper, proper + 10); } coes = Arrays.copyOf(coes, proper); } public void setN(int n) { this.n = n; ensureLength(); } public void multiply(int b, Polynomial ans) { ans.setN(n + 1); for (int i = 0; i < n; i++) { ans.coes[i] = modular.mul(coes[i], b); } ans.coes[n] = 0; for (int i = 0; i < n; i++) { ans.coes[i + 1] = modular.plus(ans.coes[i + 1], coes[i]); } } public void mulConstant(int b, Polynomial ans) { ans.setN(n); for (int i = 0; i < n; i++) { ans.coes[i] = modular.mul(coes[i], b); } } public void plus(Polynomial a, Polynomial ans) { ans.setN(Math.max(n, a.n)); for (int i = 0; i < n; i++) { ans.coes[i] = coes[i]; } for (int i = 0; i < a.n; i++) { ans.coes[i] = modular.plus(ans.coes[i], a.coes[i]); } } public void div(int b, Polynomial ans) { ans.setN(n - 1); int affect = 0; for (int i = n - 1; i >= 1; i--) { affect = modular.plus(affect, coes[i]); ans.coes[i - 1] = affect; affect = modular.mul(-affect, b); } } public String toString() { return Arrays.toString(Arrays.copyOfRange(coes, 0, n)); } } } static class Interval { int l; int r; public boolean contain(int x) { return l <= x && x <= r; } public boolean empty() { return l > r; } public Interval(int l, int r) { this.l = l; this.r = r; } public Interval[] split(int m) { return new Interval[]{new Interval(l, m), new Interval(m + 1, r)}; } public String toString() { return "(" + l + "," + r + ")"; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Power { final Modular modular; public Modular getModular() { return modular; } public Power(Modular modular) { this.modular = modular; } public int pow(int x, int n) { if (n == 0) { return modular.valueOf(1); } long r = pow(x, n >> 1); r = modular.valueOf(r * r); if ((n & 1) == 1) { r = modular.valueOf(r * x); } return (int) r; } public int inverseByFermat(int x) { return pow(x, modular.m - 2); } } static class SegmentFunctions { TreeMap<Integer, SegmentFunction> functionTreeSet = new TreeMap<>(); public void add(SegmentFunction function) { functionTreeSet.put(function.interval.l, function); } public SegmentFunction apply(int x) { SegmentFunction function = functionTreeSet.floorEntry(x).getValue(); return function; } } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
b184e1edc499e50ab94acdd4a0497e87
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.Random; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FGoodContest solver = new FGoodContest(); solver.solve(1, in, out); out.close(); } } static class FGoodContest { Modular mod = new Modular(998244353); InverseNumber inverseNumber = new InverseNumber(100, mod); Power power = new Power(mod); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); Interval[] intervals = new Interval[n]; IntegerList list = new IntegerList(n * 2); for (int i = 0; i < n; i++) { intervals[i] = new Interval(in.readInt(), in.readInt()); list.add(intervals[i].l); list.add(intervals[i].r); } SequenceUtils.reverse(intervals, 0, intervals.length - 1); list.unique(); List<Interval> allPossibleIntervals = new ArrayList<>(list.size() * 2); allPossibleIntervals.add(new Interval(list.first(), list.first())); for (int i = 1; i < list.size(); i++) { int last = list.get(i - 1); int cur = list.get(i); if (cur - last > 1) { allPossibleIntervals.add(new Interval(last + 1, cur - 1)); } allPossibleIntervals.add(new Interval(cur, cur)); } Interval[] ranges = allPossibleIntervals.toArray(new Interval[0]); int m = ranges.length; int[][] dp = new int[m + 1][n + 1]; dp[0][0] = 1; for (int i = 1; i <= m; i++) { for (int j = 0; j <= n; j++) { dp[i][j] = mod.plus(dp[i][j], dp[i - 1][j]); for (int k = j - 1; k >= 0; k--) { if (!intervals[k].contain(ranges[i - 1])) { break; } int contrib = dp[i - 1][k]; contrib = mod.mul(nonStrictlyIncrementSequence(ranges[i - 1].length(), j - k), contrib); dp[i][j] = mod.plus(dp[i][j], contrib); } } } // System.err.println(Arrays.deepToString(dp)); int valid = dp[m][n]; int total = 1; for (int i = 0; i < n; i++) { total = mod.mul(total, intervals[i].length()); } int ans = valid; ans = mod.mul(ans, power.inverseByFermat(total)); out.println(ans); } public int nonStrictlyIncrementSequence(int n, int k) { return composite(n - 1 + k, k); } public int composite(int n, int m) { if (n < m) { return 0; } return m == 0 ? 1 : mod.mul(mod.mul(n, inverseNumber.inverse(m)), composite(n - 1, m - 1)); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("index " + i + " out of range"); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public void sort() { if (size <= 1) { return; } Randomized.shuffle(data, 0, size); Arrays.sort(data, 0, size); } public int first() { checkRange(0); return data[0]; } public void unique() { if (size <= 1) { return; } sort(); int wpos = 1; for (int i = 1; i < size; i++) { if (data[i] != data[wpos - 1]) { data[wpos++] = data[i]; } } size = wpos; } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class Power { final Modular modular; public Power(Modular modular) { this.modular = modular; } public int pow(int x, int n) { if (n == 0) { return modular.valueOf(1); } long r = pow(x, n >> 1); r = modular.valueOf(r * r); if ((n & 1) == 1) { r = modular.valueOf(r * x); } return (int) r; } public int inverseByFermat(int x) { return pow(x, modular.m - 2); } } static class Interval { int l; int r; boolean contain(Interval other) { return l <= other.l && other.r <= r; } int length() { return r - l + 1; } public Interval(int l, int r) { this.l = l; this.r = r; } public String toString() { return String.format("[%d,%d]", l, r); } } static class SequenceUtils { public static <T> void swap(T[] data, int i, int j) { T tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static <T> void reverse(T[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Randomized { private static Random random = new Random(); public static void shuffle(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } static class InverseNumber { int[] inv; public InverseNumber(int[] inv, int limit, Modular modular) { this.inv = inv; inv[1] = 1; int p = modular.getMod(); for (int i = 2; i <= limit; i++) { int k = p / i; int r = p % i; inv[i] = modular.mul(-k, inv[r]); } } public InverseNumber(int limit, Modular modular) { this(new int[limit + 1], limit, modular); } public int inverse(int x) { return inv[x]; } } static class Modular { int m; public int getMod() { return m; } public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
8c67b4fa037a4d41b365c6c37533d0f7
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.Random; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FGoodContest solver = new FGoodContest(); solver.solve(1, in, out); out.close(); } } static class FGoodContest { Modular mod = new Modular(998244353); InverseNumber inverseNumber = new InverseNumber(100, mod); Power power = new Power(mod); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); Interval[] intervals = new Interval[n]; IntegerList list = new IntegerList(n * 2); for (int i = 0; i < n; i++) { intervals[i] = new Interval(in.readInt(), in.readInt()); list.add(intervals[i].l); list.add(intervals[i].r); } SequenceUtils.reverse(intervals, 0, intervals.length - 1); list.unique(); List<Interval> allPossibleIntervals = new ArrayList<>(list.size() * 2); allPossibleIntervals.add(new Interval(list.first(), list.first())); for (int i = 1; i < list.size(); i++) { int last = list.get(i - 1); int cur = list.get(i); if (cur - last > 1) { allPossibleIntervals.add(new Interval(last + 1, cur - 1)); } allPossibleIntervals.add(new Interval(cur, cur)); } Interval[] ranges = allPossibleIntervals.toArray(new Interval[0]); int m = ranges.length; int[][] dp = new int[m + 1][n + 1]; dp[0][0] = 1; int[] comp = new int[n + 1]; for (int i = 1; i <= m; i++) { for (int j = 0; j <= n; j++) { comp[j] = nonStrictlyIncrementSequence(ranges[i - 1].length(), j); } for (int j = 0; j <= n; j++) { dp[i][j] = mod.plus(dp[i][j], dp[i - 1][j]); for (int k = j - 1; k >= 0; k--) { if (!intervals[k].contain(ranges[i - 1])) { break; } int contrib = dp[i - 1][k]; contrib = mod.mul(comp[j - k], contrib); dp[i][j] = mod.plus(dp[i][j], contrib); } } } // System.err.println(Arrays.deepToString(dp)); int valid = dp[m][n]; int total = 1; for (int i = 0; i < n; i++) { total = mod.mul(total, intervals[i].length()); } int ans = valid; ans = mod.mul(ans, power.inverseByFermat(total)); out.println(ans); } public int nonStrictlyIncrementSequence(int n, int k) { return composite(n - 1 + k, k); } public int composite(int n, int m) { if (n < m) { return 0; } return m == 0 ? 1 : mod.mul(mod.mul(n, inverseNumber.inverse(m)), composite(n - 1, m - 1)); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("index " + i + " out of range"); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public void sort() { if (size <= 1) { return; } Randomized.shuffle(data, 0, size); Arrays.sort(data, 0, size); } public int first() { checkRange(0); return data[0]; } public void unique() { if (size <= 1) { return; } sort(); int wpos = 1; for (int i = 1; i < size; i++) { if (data[i] != data[wpos - 1]) { data[wpos++] = data[i]; } } size = wpos; } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class Power { final Modular modular; public Power(Modular modular) { this.modular = modular; } public int pow(int x, int n) { if (n == 0) { return modular.valueOf(1); } long r = pow(x, n >> 1); r = modular.valueOf(r * r); if ((n & 1) == 1) { r = modular.valueOf(r * x); } return (int) r; } public int inverseByFermat(int x) { return pow(x, modular.m - 2); } } static class Randomized { private static Random random = new Random(); public static void shuffle(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } static class SequenceUtils { public static <T> void swap(T[] data, int i, int j) { T tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static <T> void reverse(T[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Interval { int l; int r; boolean contain(Interval other) { return l <= other.l && other.r <= r; } int length() { return r - l + 1; } public Interval(int l, int r) { this.l = l; this.r = r; } public String toString() { return String.format("[%d,%d]", l, r); } } static class InverseNumber { int[] inv; public InverseNumber(int[] inv, int limit, Modular modular) { this.inv = inv; inv[1] = 1; int p = modular.getMod(); for (int i = 2; i <= limit; i++) { int k = p / i; int r = p % i; inv[i] = modular.mul(-k, inv[r]); } } public InverseNumber(int limit, Modular modular) { this(new int[limit + 1], limit, modular); } public int inverse(int x) { return inv[x]; } } static class Modular { int m; public int getMod() { return m; } public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
596c247c2436547f5c4fb2e1370fd3db
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{ } void solve(int TC)throws Exception { int n = ni(); long[][] rng = new long[1+n][]; TreeSet<Long> set = new TreeSet<>(); for(int i = 1; i<= n; i++){ rng[n-i+1] = new long[]{nl(), nl()+1}; set.add(rng[n-i+1][0]);set.add(rng[n-i+1][1]); } TreeMap<Long, Integer> mp = new TreeMap<>();int c = 0; long[] w = new long[1+set.size()]; for(long l:set){ w[++c] = l; mp.put(l, c); } long[] sz = new long[1+c]; for(int i = 1; i< c; i++)sz[i] = w[i+1]-w[i]; long[][] dp = new long[1+n][1+c]; dp[0][0] = 1; long[][] sum = new long[1+n][1+c]; for(int i = 0; i<= c; i++)sum[0][i] = 1; int[][] range = new int[1+n][]; for(int i = 1; i<= n; i++)range[i] = new int[]{mp.get(rng[i][0]), mp.get(rng[i][1])}; for(int i = 1; i<= n; i++){ for(int j = 1; j<= c; j++){ sum[i][j] = sum[i][j-1]; for(int prev = i-1; prev >= 0; prev--){ if(j< range[prev+1][0] || j >= range[prev+1][1])break; dp[i][j] += (sum[prev][j-1]*C(sz[j]+i-prev-1, i-prev))%MOD; if(dp[i][j] >= MOD)dp[i][j] -= MOD; } sum[i][j] = (sum[i][j]+dp[i][j])%MOD; } } long prod = 1; for(int i = 1; i<= n; i++)prod = (prod*(rng[i][1]-rng[i][0]))%MOD; pn((sum[n][c]*inv(prod))%MOD); } long MOD = 998244353; long inv(long a){ long inv = 1; for(long p = MOD-2; p >0; p>>=1){ if((p&1)==1)inv = (inv*a)%MOD; a = (a*a)%MOD; } return inv; } long C(long n, int k){ if(k == 0)return 1; return (C(n, k-1)*(n-k+1)%MOD*inv(k))%MOD; } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} long IINF = (long)1e15; final int INF = (int)1e9+2, MX = (int)2e6+5; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-7; static boolean multipleTC = false, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ if(fileIO){ in = new FastReader(""); out = new PrintWriter(""); }else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre(); for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
2da45a82d999bd8459f03bc358f4403c
train_000.jsonl
1580308500
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x &lt; y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent.
256 megabytes
//package educational.round81; 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 F { InputStream is; PrintWriter out; String INPUT = ""; // 1/2 1/2 // 1/2 1/2 // 1 void solve() { int n = ni(); int[] A = new int[n]; int[] B = new int[n]; int mod = 998244353; for(int i = 0;i < n;i++){ A[n-1-i] = ni(); B[n-1-i] = ni(); } int[] xs = new int[2*n+1]; int min = Integer.MAX_VALUE; for(int i = 0;i < n;i++){ xs[i] = A[i]; min = Math.min(min, A[i]); xs[i+n] = B[i]+1; } xs[2*n] = min-1; Arrays.sort(xs); xs = uniq(xs); int m = xs.length; long[][] dp = new long[m-1][n+1]; dp[0][0] = 1; long[][] ss = powerSumPolynomial(n+1, mod); long den = 1; for(int i = 0;i < n;i++){ int a = A[i]; int b = B[i]; den = den * (b-a+1) % mod; long[][] ndp = new long[m-1][n+1]; long P = 0; for(int j = 0;j < m-1;j++){ long[] po = new long[n+1]; for(int k = 0;k <= n;k++){ if(dp[j][k] == 0)continue; for(int l = 0;l <= k+1;l++){ po[l] += dp[j][k] * ss[k][l]; po[l] %= mod; } } po[0] += P; po[0] %= mod; if(a <= xs[j] && xs[j] <= b){ System.arraycopy(po, 0, ndp[j], 0, n+1); } P = f(po, xs[j+1] - xs[j], mod); } dp = ndp; } long P = 0; for(int j = 0;j < m-1;j++){ long[] po = new long[n+1]; for(int k = 0;k <= n;k++){ if(dp[j][k] == 0)continue; for(int l = 0;l <= k+1;l++){ po[l] += dp[j][k] * ss[k][l]; po[l] %= mod; } } po[0] += P; po[0] %= mod; P = f(po, xs[j+1] - xs[j], mod); } out.println(P%mod*invl(den, mod)%mod); } long f(long[] po, int x, int mod) { long v = 0; for(int i = po.length-1;i >= 0;i--){ v = v * x + po[i]; v %= mod; } return v; } public static long[][] powerSumPolynomial(int K, long mod) { final long BIG = 8L*mod*mod; int[][] C = new int[K+3][K+3]; for(int i = 0;i <= K+2;i++){ C[i][0] = mod == 1 ? 0 : 1; for(int j = 1;j <= i;j++){ C[i][j] = C[i-1][j]+C[i-1][j-1]; if(C[i][j] >= mod)C[i][j] -= mod; } } long[][] dp = new long[K+1][K+2]; dp[0][1] = 1; for(int i = 1;i <= K;i++){ for(int j = i+1;j >= 1;j--){ dp[i][j] = C[i+1][j]; } for(int j = 0;j <= i-1;j++){ for(int l = 0;l <= j+1;l++){ dp[i][l] -= dp[j][l]*C[i+1][j]; if(dp[i][l] < -BIG)dp[i][i] += BIG; } } long iv = invl(i+1, mod); for(int j = 0;j <= i+1;j++){ dp[i][j] = dp[i][j] % mod * iv % mod; if(dp[i][j] < 0)dp[i][j] += mod; } } return dp; } public static int[] uniq(int[] a) { int n = a.length; int p = 0; for(int i = 0;i < n;i++) { if(i == 0 || a[i] != a[i-1])a[p++] = a[i]; } return Arrays.copyOf(a, p); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } public static long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"]
3 seconds
["499122177", "578894053", "1", "1"]
NoteThe real answer in the first test is $$$\frac{1}{2}$$$.
Java 8
standard input
[ "dp", "combinatorics", "probabilities" ]
075249e446f34d1e88245ea3a1ab0768
The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) β€” the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) β€” the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively.
2,700
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer β€” the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$.
standard output
PASSED
a927e3af5f7f5fe128260f24d34910d0
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public static int[] z(int[] a) { int n = a.length; int[] z = new int[n]; int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && a[R - L] == a[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && a[R - L] == a[R]) R++; z[i] = R - L; R--; } } } return z; } public void solve(int testNumber, FastScanner in, PrintWriter out) { String s = in.ns(); int ns = s.length(); String l = in.ns(); int nl = l.length(); String r = in.ns(); int nr = r.length(); int[] ar = new int[ns + nr + 1]; int[] al = new int[ns + nl + 1]; for (int i = 0; i < nr; i++) { ar[i] = r.charAt(i) - '0'; } for (int i = 0; i < nl; i++) { al[i] = l.charAt(i) - '0'; } ar[nr] = -1; al[nl] = -1; for (int i = 0; i < ns; i++) { ar[nr + 1 + i] = s.charAt(i) - '0'; al[nl + 1 + i] = s.charAt(i) - '0'; } int[] z = z(ar); boolean[] lr = new boolean[ns]; Arrays.fill(lr, true); int zi = nr + 1; /*for (int i = 0; i < ar.length; i++) { System.out.print(ar[i] + " "); } System.out.println(); for (int i = 0; i < ar.length; i++) { System.out.print(z[i] + " "); } System.out.println();*/ for (int i = 0; i < ns - nr + 1; i++, zi++) { if (z[zi] < nr) { lr[i] = ar[z[zi]] > ar[zi + z[zi]]; } //System.out.printf("%d %s%n", i, lr[i]); } z = z(al); boolean[] gl = new boolean[ns]; zi = nl + 1; for (int i = 0; i < ns - nl + 1; i++, zi++) { if (z[zi] < nl) { gl[i] = al[z[zi]] < al[zi + z[zi]]; } else { gl[i] = true; // equals } } /* BigInteger L = new BigInteger(l); BigInteger R = new BigInteger(r); for (int i = 0; i < ns - nr + 1; i++) { BigInteger NUM = new BigInteger(s.substring(i, i + nr)); boolean check = NUM.compareTo(R)<=0; if(lr[i] != check) throw new RuntimeException("lr wrong " + i + " " + NUM.toString()); } for (int i = 0; i < ns - nl + 1; i++) { BigInteger NUM = new BigInteger(s.substring(i, i + nl)); boolean check = NUM.compareTo(L)>=0; if(gl[i] != check) throw new RuntimeException("gl wrong"); }*/ long mod = 998244353; long[] dp = new long[ns + 1]; long[] suffix = new long[ns + 1]; suffix[ns] = dp[ns] = 1; for (int i = ns - 1; i >= 0; i--) { suffix[i] = suffix[i + 1]; //dp[i] = sum dp[from]...dp[to] int from = i + nl; if (!gl[i]) from++; if (from > ns) continue; int to = i + nr; if (!lr[i]) to--; if (to < from) continue; if (to > ns) to = ns; if (s.charAt(i) == '0') { if ("0".equals(l)) { from = to = i + 1; } else continue; } dp[i] = suffix[from]; if (to < ns) dp[i] -= suffix[to + 1]; dp[i] = (dp[i] + mod) % mod; suffix[i] = (suffix[i] + dp[i]) % mod; } out.println(dp[0]); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
26114dc70624b09dbece8c25b13c3157
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class dk { static int mod = 998244353; public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String a = sc.next(); String l = sc.next(); String r = sc.next(); int[] L = Arrays.copyOfRange(zAlgo((l + "$" + a).toCharArray()), l.length() + 1, a.length() + l.length() + 1); int[] R = Arrays.copyOfRange(zAlgo((r + "$" + a).toCharArray()), r.length() + 1, a.length() + r.length() + 1); FenwickTree ft = new FenwickTree(a.length() + 1); ft.point_update(a.length() + 1, 1); int ll = l.length(), rr = r.length(); for (int i = a.length() - l.length(); i >= 0; i--) { if (a.charAt(i) == '0' && l.charAt(0) != '0') continue; int min; if (L[i] == ll || (a.charAt(i + L[i]) > l.charAt(L[i]))) min = i + ll; else min = i + ll + 1; int max; if (R[i] == rr || i + R[i] >= a.length() || (a.charAt(i + R[i]) < r.charAt(R[i]))) max = i + rr; else max = i + rr - 1; if (a.charAt(i) == '0') { min = i + 1; max = i + 1; } ft.point_update(i + 1, ft.rsq(min + 1, max + 1)); } System.out.println(ft.rsq(1, 1)); out.close(); } static int[] zAlgo(char[] s) { int n = s.length; int[] z = new int[n]; for (int i = 1, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]); while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; if (i + z[i] - 1 > r) r = i + z[l = i] - 1; } return z; } static class FenwickTree { int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n + 1]; } int rsq(int b) { int sum = 0; while (b > 0) { sum = (sum + ft[b]) % mod; b -= b & -b; } return sum; } int rsq(int a, int b) { if (b < a || a > n) return 0; b = Math.min(b, n); return (rsq(b) - rsq(a - 1) + mod) % mod; } void point_update(int k, int val) { while (k <= n) { ft[k] = (ft[k] + val) % mod; k += k & -k; } } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
de4eb1221df44583abe17f6ba700c03c
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.function.IntUnaryOperator; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EVasyaAndBigIntegers solver = new EVasyaAndBigIntegers(); solver.solve(1, in, out); out.close(); } } static class EVasyaAndBigIntegers { Modular mod = new Modular(998244353); public void solve(int testNumber, FastInput in, FastOutput out) { char[] a = new char[1000000]; char[] left = new char[1000000]; char[] right = new char[1000000]; int aLen = in.readString(a, 0); int leftLen = in.readString(left, 0); int rightLen = in.readString(right, 0); ZAlgorithm leftLCP = new ZAlgorithm(leftLen + aLen, i -> i < leftLen ? left[i] : a[i - leftLen]); ZAlgorithm rightLCP = new ZAlgorithm(rightLen + aLen, i -> i < rightLen ? right[i] : a[i - rightLen]); int[] dp = new int[aLen + 1]; int[] preSum = new int[aLen + 1]; dp[0] = 1; preSum[0] = 1; for (int i = 1; i <= aLen; i++) { preSum[i] = preSum[i - 1]; int l = i - rightLen; int r = i - leftLen; if (l >= 0) { int lcp = rightLCP.applyAsInt(rightLen + l); if (lcp < rightLen && a[l + lcp] > right[lcp]) { l++; } } else { l = 0; } if (r < 0) { continue; } int lcp = leftLCP.applyAsInt(leftLen + r); if (lcp < leftLen && a[r + lcp] < left[lcp]) { r--; } if (l > r) { continue; } dp[i] = interval(preSum, l, r); preSum[i] = mod.plus(preSum[i - 1], dp[i]); if (a[i - 1] == '0') { preSum[i - 1] = mod.subtract(preSum[i - 1], dp[i - 1]); preSum[i] = mod.subtract(preSum[i], dp[i - 1]); } } // System.err.println(Arrays.toString(dp)); // // int bf = bf(String.valueOf(a, 0, aLen), String.valueOf(left, 0, leftLen), String.valueOf(right, 0, rightLen)); // if (bf != dp[aLen]) { // // throw new RuntimeException(); // } int ans = dp[aLen]; out.println(ans); } public int interval(int[] preSum, int l, int r) { if (l == 0) { return preSum[r]; } return mod.subtract(preSum[r], preSum[l - 1]); } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class ZAlgorithm implements IntUnaryOperator { private int[] z; public ZAlgorithm(int n, IntUnaryOperator s) { int l = 0; int r = -1; z = new int[n]; z[0] = n; for (int i = 1; i < n; i++) { if (r < i) { l = r = i; } else { int t = i - l; int k = r - i + 1; if (z[t] < k) { z[i] = z[t]; continue; } l = i; r++; } while (r < n && s.applyAsInt(r - l) == s.applyAsInt(r)) { r++; } r--; z[i] = r - l + 1; } } public int applyAsInt(int operand) { return z[operand]; } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
9eab162752d37d9d7b4b4bca1ed32086
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.function.IntUnaryOperator; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EVasyaAndBigIntegers solver = new EVasyaAndBigIntegers(); solver.solve(1, in, out); out.close(); } } static class EVasyaAndBigIntegers { Modular mod = new Modular(998244353); public void solve(int testNumber, FastInput in, FastOutput out) { char[] data = new char[3000000]; int aLen = in.readString(data, 0); int leftLen = in.readString(data, aLen); int rightLen = in.readString(data, aLen + leftLen); SAIS sais = new SAIS(data); int[] leftLCP = new int[aLen]; int[] rightLCP = new int[aLen]; int index = sais.queryRank(aLen); int lcp = aLen; for (int i = index; i >= 1 && lcp > 0; i--) { lcp = Math.min(lcp, sais.longestCommonPrefixBetween(i)); int last; if ((last = sais.queryKth(i - 1)) < aLen) { leftLCP[last] = lcp; } } lcp = aLen; for (int i = index + 1; i < data.length && lcp > 0; i++) { lcp = Math.min(lcp, sais.longestCommonPrefixBetween(i)); int last; if ((last = sais.queryKth(i)) < aLen) { leftLCP[last] = lcp; } } index = sais.queryRank(aLen + leftLen); lcp = aLen; for (int i = index; i >= 1 && lcp > 0; i--) { lcp = Math.min(lcp, sais.longestCommonPrefixBetween(i)); int last; if ((last = sais.queryKth(i - 1)) < aLen) { rightLCP[last] = lcp; } } lcp = aLen; for (int i = index + 1; i < data.length && lcp > 0; i++) { lcp = Math.min(lcp, sais.longestCommonPrefixBetween(i)); int last; if ((last = sais.queryKth(i)) < aLen) { rightLCP[last] = lcp; } } int[] dp = new int[aLen + 1]; int[] preSum = new int[aLen + 1]; dp[0] = 1; preSum[0] = 1; for (int i = 1; i <= aLen; i++) { preSum[i] = preSum[i - 1]; int l = i - rightLen; int r = i - leftLen; if (l >= 0) { lcp = rightLCP[l]; if (lcp < rightLen && data[l + lcp] > data[aLen + leftLen + lcp]) { l++; } } else { l = 0; } if (r < 0) { continue; } lcp = leftLCP[r]; if (lcp < leftLen && data[r + lcp] < data[aLen + lcp]) { r--; } if (l > r) { continue; } dp[i] = interval(preSum, l, r); preSum[i] = mod.plus(preSum[i - 1], dp[i]); if (data[i - 1] == '0') { preSum[i - 1] = mod.subtract(preSum[i - 1], dp[i - 1]); preSum[i] = mod.subtract(preSum[i], dp[i - 1]); } } // System.err.println(Arrays.toString(dp)); // // int bf = bf(String.valueOf(data, 0, aLen), String.valueOf(data, aLen, leftLen), String.valueOf(data, aLen + leftLen, rightLen)); // if (bf != dp[aLen]) { // // throw new RuntimeException(); // } int ans = dp[aLen]; out.println(ans); } public int interval(int[] preSum, int l, int r) { if (l == 0) { return preSum[r]; } return mod.subtract(preSum[r], preSum[l - 1]); } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static void reverse(int[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class CompareUtils { private static final int[] BUF8 = new int[1 << 8]; private static final IntegerList INT_LIST = new IntegerList(); private CompareUtils() { } public static void radixSort(int[] data, int l, int r, IntUnaryOperator indexFetcher) { INT_LIST.clear(); INT_LIST.expandWith(0, r - l + 1); int[] output = INT_LIST.getData(); for (int i = 0; i < 4; i++) { int rightShift = i * 8; int mask = BUF8.length - 1; radixSort0(data, output, BUF8, l, r, (x) -> (indexFetcher.applyAsInt(x) >>> rightShift) & mask); System.arraycopy(output, 0, data, l, r - l + 1); } } private static void radixSort0(int[] data, int[] output, int[] buf, int l, int r, IntUnaryOperator indexFetcher) { Arrays.fill(buf, 0); for (int i = l; i <= r; i++) { buf[indexFetcher.applyAsInt(data[i])]++; } for (int i = 1; i < buf.length; i++) { buf[i] += buf[i - 1]; } for (int i = r; i >= l; i--) { output[--buf[indexFetcher.applyAsInt(data[i])]] = data[i]; } } } static class MultiWayIntegerDeque { private int[] values; private int[] next; private int[] prev; private int[] heads; private int[] tails; private int alloc; private int queueNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); prev = Arrays.copyOf(prev, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public void clear() { alloc = 0; Arrays.fill(heads, 0, queueNum, 0); Arrays.fill(tails, 0, queueNum, 0); } public boolean isEmpty(int qId) { return heads[qId] == 0; } public void expandQueueNum(int qNum) { if (qNum <= queueNum) { } else if (qNum <= heads.length) { Arrays.fill(heads, queueNum, qNum, 0); Arrays.fill(tails, queueNum, qNum, 0); } else { Arrays.fill(heads, queueNum, heads.length, 0); Arrays.fill(tails, queueNum, heads.length, 0); heads = Arrays.copyOf(heads, qNum); tails = Arrays.copyOf(tails, qNum); } queueNum = qNum; } public MultiWayIntegerDeque(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; prev = new int[totalCapacity + 1]; heads = new int[qNum]; tails = new int[qNum]; queueNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; if (heads[qId] == 0) { heads[qId] = tails[qId] = alloc; return; } next[tails[qId]] = alloc; prev[alloc] = tails[qId]; tails[qId] = alloc; } public void addFirst(int qId, int x) { alloc(); values[alloc] = x; if (heads[qId] == 0) { heads[qId] = tails[qId] = alloc; return; } next[alloc] = heads[qId]; prev[heads[qId]] = alloc; heads[qId] = alloc; } public int removeFirst(int qId) { int ans = values[heads[qId]]; if (heads[qId] == tails[qId]) { heads[qId] = tails[qId] = 0; } else { heads[qId] = next[heads[qId]]; prev[tails[qId]] = 0; } return ans; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < queueNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static interface IntegerIterator { boolean hasNext(); int next(); } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public int[] getData() { return data; } public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void reverse(int l, int r) { SequenceUtils.reverse(data, l, r); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("index " + i + " out of range"); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public void expandWith(int x, int len) { ensureSpace(len); while (size < len) { data[size++] = x; } } public int tail() { checkRange(0); return data[size - 1]; } public void set(int i, int x) { checkRange(i); data[i] = x; } public int pop() { return data[--size]; } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public boolean isEmpty() { return size == 0; } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class SAIS { private int l; private int[] rank2Index; private int[] index2Rank; private int[] lcp; private int[] data; private static final int TYPE_MINUS = 0; private static final int TYPE_PLUS = 1; public int queryRank(int i) { return index2Rank[i - l]; } public int queryKth(int k) { return rank2Index[k] + l; } public int longestCommonPrefixBetween(int i) { return lcp[i]; } public SAIS(char[] array) { this(array, 0, array.length - 1); } public SAIS(int[] array) { this(array, 0, array.length - 1); } public SAIS(char[] array, int l, int r) { if (l > r) { throw new IllegalArgumentException(); } this.l = l; int n = r - l + 1; data = new int[n]; for (int i = 0; i < n; i++) { data[i] = array[i + l]; } process(); } public SAIS(int[] array, int l, int r) { if (l > r) { throw new IllegalArgumentException(); } int n = r - l + 1; data = new int[n]; for (int i = 0; i < n; i++) { data[i] = array[i + l]; } process(); } private void process() { int n = data.length; rank2Index = new int[n]; index2Rank = new int[n]; lcp = new int[n]; for (int i = 0; i < n; i++) { rank2Index[i] = i; } CompareUtils.radixSort(rank2Index, 0, n - 1, x -> data[x] ^ Integer.MIN_VALUE); int rank = 0; index2Rank[rank2Index[0]] = 0; for (int i = 1; i < data.length; i++) { if (data[rank2Index[i]] > data[rank2Index[i - 1]]) { rank++; } index2Rank[rank2Index[i]] = rank; } System.arraycopy(index2Rank, 0, rank2Index, 0, n); buildSA(rank2Index, new IntegerList(n), new IntegerList(n), new MultiWayIntegerDeque(n, n), index2Rank); for (int i = 0; i < n; i++) { rank2Index[index2Rank[i]] = i; } buildLcp(); } private void buildLcp() { int n = lcp.length; for (int i = 0; i < n; i++) { int ri = index2Rank[i]; if (ri == 0) { continue; } int j = rank2Index[ri - 1]; int same = i == 0 ? 0 : Math.max(lcp[index2Rank[i - 1]] - 1, 0); while (j + same < n && i + same < n && data[j + same] == data[i + same]) { same++; } lcp[index2Rank[i]] = same; } } private static void buildSA(int[] data, IntegerList plus, IntegerList minus, MultiWayIntegerDeque deque, int[] output) { int n = data.length; if (n == 1) { output[0] = 0; return; } byte[] type = new byte[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1 || data[i] > data[i + 1] || data[i] == data[i + 1] && type[i + 1] == TYPE_MINUS) { type[i] = TYPE_MINUS; } else { type[i] = TYPE_PLUS; } } plus.clear(); minus.clear(); // find relation between star type deque.expandQueueNum(n); deque.clear(); for (int i = 1; i < n; i++) { if (type[i - 1] == TYPE_MINUS && type[i] == TYPE_PLUS) { deque.addLast(data[i], i); } } for (int i = 0; i < n; i++) { while (!deque.isEmpty(i)) { plus.add(deque.removeFirst(i)); } } if (!plus.isEmpty()) { induceSort(plus, minus, type, data, deque); minus.clear(); minus.addAll(plus); plus.clear(); for (int i = 0, until = minus.size(); i < until; i++) { int index = minus.get(i); if (index > 0 && type[index - 1] == TYPE_MINUS && type[index] == TYPE_PLUS) { plus.add(index); } } minus.clear(); for (int i = 1; i < n; i++) { if (type[i - 1] == TYPE_MINUS && type[i] == TYPE_PLUS) { minus.add(i); } } int[] order2Index = minus.toArray(); int[] alias = new int[order2Index.length]; int[] index2Order = new int[n]; for (int i = 0; i < order2Index.length; i++) { index2Order[order2Index[i]] = i; } // assign alias int r = 0; alias[index2Order[plus.get(0)]] = r; for (int i = 1; i < order2Index.length; i++) { int l1 = plus.get(i); int l2 = plus.get(i - 1); int r1 = index2Order[l1]; if (r1 + 1 == order2Index.length) { r1 = n - 1; } else { r1 = order2Index[r1 + 1]; } int r2 = index2Order[l2]; if (r2 + 1 == order2Index.length) { r2 = n - 1; } else { r2 = order2Index[r2 + 1]; } if (compareArray(data, l1, r1, data, l2, r2) != 0) { r++; } alias[index2Order[plus.get(i)]] = r; } buildSA(alias, plus, minus, deque, output); int[] index2Rank = output; plus.clear(); plus.expandWith(0, order2Index.length); for (int i = 0; i < order2Index.length; i++) { plus.set(index2Rank[i], order2Index[i]); } } // find relation between minus type induceSort(plus, minus, type, data, deque); plus.reverse(0, plus.size() - 1); minus.reverse(0, minus.size() - 1); // merge int[] index2Rank = output; int rank = 0; while (plus.size() + minus.size() > 0) { if (plus.isEmpty() || (!minus.isEmpty() && data[minus.tail()] <= data[plus.tail()])) { index2Rank[minus.pop()] = rank++; } else { index2Rank[plus.pop()] = rank++; } } return; } private static int compareArray(int[] a, int al, int ar, int[] b, int bl, int br) { for (int i = al, j = bl; i <= ar && j <= br; i++, j++) { if (a[i] != b[j]) { return a[i] - b[j]; } } return -((ar - al) - (br - bl)); } private static void induceSort(IntegerList plus, IntegerList minus, byte[] type, int[] data, MultiWayIntegerDeque deque) { int n = data.length; deque.expandQueueNum(n); minus.clear(); plus.reverse(0, plus.size() - 1); // from star to minus deque.clear(); deque.addFirst(data[n - 1], n - 1); for (int i = 0; i < n; i++) { while (!deque.isEmpty(i)) { int index = deque.removeFirst(i); if (type[index] == TYPE_MINUS) { minus.add(index); } if (index > 0 && type[index - 1] == TYPE_MINUS) { deque.addLast(data[index - 1], index - 1); } } while (!plus.isEmpty() && data[plus.tail()] == i) { int index = plus.pop(); if (index > 0 && type[index - 1] == TYPE_MINUS) { deque.addLast(data[index - 1], index - 1); } } } deque.clear(); int rightScan = minus.size() - 1; // from minus to plus for (int i = n - 1; i >= 0; i--) { while (!deque.isEmpty(i)) { int index = deque.removeFirst(i); if (type[index] == TYPE_PLUS) { plus.add(index); } if (index > 0 && type[index - 1] == TYPE_PLUS) { deque.addLast(data[index - 1], index - 1); } } while (rightScan >= 0 && data[minus.get(rightScan)] == i) { int index = minus.get(rightScan--); if (index > 0 && type[index - 1] == TYPE_PLUS) { deque.addLast(data[index - 1], index - 1); } } } plus.reverse(0, plus.size() - 1); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
244f6c3a53b9851765ad41a8114b4eea
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.stream.IntStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EVasyaAndBigIntegers solver = new EVasyaAndBigIntegers(); solver.solve(1, in, out); out.close(); } } static class EVasyaAndBigIntegers { Modular mod = new Modular(998244353); public void solve(int testNumber, FastInput in, FastOutput out) { char[] data = new char[3000000]; int aLen = in.readString(data, 0); int leftLen = in.readString(data, aLen); int rightLen = in.readString(data, aLen + leftLen); String s = new String(data); int[] sa = SuffixArrayDC3.suffixArray(s); int[] invSA = new int[data.length]; for (int i = 0; i < data.length; i++) { invSA[sa[i]] = i; } int[] lcps = SuffixArrayDC3.lcp(sa, s); int[] leftLCP = new int[aLen]; int[] rightLCP = new int[aLen]; int index = invSA[aLen]; int lcp = aLen; for (int i = index; i >= 1 && lcp > 0; i--) { lcp = Math.min(lcp, lcps[i - 1]); int last; if ((last = sa[i - 1]) < aLen) { leftLCP[last] = lcp; } } lcp = aLen; for (int i = index + 1; i < data.length && lcp > 0; i++) { lcp = Math.min(lcp, lcps[i - 1]); int last; if ((last = sa[i]) < aLen) { leftLCP[last] = lcp; } } index = invSA[aLen + leftLen]; lcp = aLen; for (int i = index; i >= 1 && lcp > 0; i--) { lcp = Math.min(lcp, lcps[i - 1]); int last; if ((last = sa[(i - 1)]) < aLen) { rightLCP[last] = lcp; } } lcp = aLen; for (int i = index + 1; i < data.length && lcp > 0; i++) { lcp = Math.min(lcp, lcps[i - 1]); int last; if ((last = sa[i]) < aLen) { rightLCP[last] = lcp; } } int[] dp = new int[aLen + 1]; int[] preSum = new int[aLen + 1]; dp[0] = 1; preSum[0] = 1; for (int i = 1; i <= aLen; i++) { preSum[i] = preSum[i - 1]; int l = i - rightLen; int r = i - leftLen; if (l >= 0) { lcp = rightLCP[l]; if (lcp < rightLen && data[l + lcp] > data[aLen + leftLen + lcp]) { l++; } } else { l = 0; } if (r < 0) { continue; } lcp = leftLCP[r]; if (lcp < leftLen && data[r + lcp] < data[aLen + lcp]) { r--; } if (l > r) { continue; } dp[i] = interval(preSum, l, r); preSum[i] = mod.plus(preSum[i - 1], dp[i]); if (data[i - 1] == '0') { preSum[i - 1] = mod.subtract(preSum[i - 1], dp[i - 1]); preSum[i] = mod.subtract(preSum[i], dp[i - 1]); } } // System.err.println(Arrays.toString(dp)); // // int bf = bf(String.valueOf(data, 0, aLen), String.valueOf(data, aLen, leftLen), String.valueOf(data, aLen + leftLen, rightLen)); // if (bf != dp[aLen]) { // // throw new RuntimeException(); // } int ans = dp[aLen]; out.println(ans); } public int interval(int[] preSum, int l, int r) { if (l == 0) { return preSum[r]; } return mod.subtract(preSum[r], preSum[l - 1]); } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class SuffixArrayDC3 { static boolean leq(int a1, int a2, int b1, int b2) { return a1 < b1 || a1 == b1 && a2 <= b2; } static boolean leq(int a1, int a2, int a3, int b1, int b2, int b3) { return a1 < b1 || a1 == b1 && leq(a2, a3, b2, b3); } static void radixPass(int[] a, int[] b, int[] r, int offset, int n, int K) { int[] cnt = new int[K + 1]; for (int i = 0; i < n; i++) ++cnt[r[a[i] + offset]]; for (int i = 1; i < cnt.length; i++) cnt[i] += cnt[i - 1]; for (int i = n - 1; i >= 0; i--) b[--cnt[r[a[i] + offset]]] = a[i]; } private static void suffixArray(int[] T, int[] SA, int n, int K) { int n0 = (n + 2) / 3; int n1 = (n + 1) / 3; int n2 = n / 3; int n02 = n0 + n2; //******* Step 0: Construct sample ******** // generate positions of mod 1 and mod 2 suffixes // the "+(n0-n1)" adds a dummy mod 1 suffix if n%3 == 1 int[] R = new int[n02 + 3]; for (int i = 0, j = 0; i < n + (n0 - n1); i++) if (i % 3 != 0) R[j++] = i; //******* Step 1: Sort sample suffixes ******** // lsb radix sort the mod 1 and mod 2 triples int[] SA12 = new int[n02 + 3]; radixPass(R, SA12, T, 2, n02, K); radixPass(SA12, R, T, 1, n02, K); radixPass(R, SA12, T, 0, n02, K); // find lexicographic names of triples and // write them to correct places in R int name = 0; for (int i = 0; i < n02; i++) { if (i == 0 || T[SA12[i]] != T[SA12[i - 1]] || T[SA12[i] + 1] != T[SA12[i - 1] + 1] || T[SA12[i] + 2] != T[SA12[i - 1] + 2]) { ++name; } R[SA12[i] / 3 + (SA12[i] % 3 == 1 ? 0 : n0)] = name; } if (name < n02) { // recurse if names are not yet unique suffixArray(R, SA12, n02, name); // store unique names in R using the suffix array for (int i = 0; i < n02; i++) R[SA12[i]] = i + 1; } else { // generate the suffix array of R directly for (int i = 0; i < n02; i++) SA12[R[i] - 1] = i; } //******* Step 2: Sort nonsample suffixes ******** // stably sort the mod 0 suffixes from SA12 by their first character int[] R0 = new int[n0]; for (int i = 0, j = 0; i < n02; i++) if (SA12[i] < n0) R0[j++] = 3 * SA12[i]; int[] SA0 = new int[n0]; radixPass(R0, SA0, T, 0, n0, K); //******* Step 3: Merge ******** // merge sorted SA0 suffixes and sorted SA12 suffixes for (int p = 0, t = n0 - n1, k = 0; k < n; k++) { int i = SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2; // pos of current offset 12 suffix int j = SA0[p]; // pos of current offset 0 suffix if (SA12[t] < n0 ? // different compares for mod 1 and mod 2 suffixes leq(T[i], R[SA12[t] + n0], T[j], R[j / 3]) : leq(T[i], T[i + 1], R[SA12[t] - n0 + 1], T[j], T[j + 1], R[j / 3 + n0])) { // suffix from SA12 is smaller SA[k] = i; if (++t == n02) // done --- only SA0 suffixes left for (k++; p < n0; p++, k++) SA[k] = SA0[p]; } else { // suffix from SA0 is smaller SA[k] = j; if (++p == n0) // done --- only SA12 suffixes left for (k++; t < n02; t++, k++) SA[k] = SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2; } } } public static int[] suffixArray(CharSequence s) { int n = s.length(); if (n <= 1) return new int[n]; int[] S = IntStream.range(0, n + 3).map(i -> i < n ? s.charAt(i) : 0).toArray(); int[] sa = new int[n]; suffixArray(S, sa, n, 255); return sa; } public static int[] lcp(int[] sa, CharSequence s) { int n = sa.length; int[] rank = new int[n]; for (int i = 0; i < n; i++) rank[sa[i]] = i; int[] lcp = new int[n - 1]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; Math.max(i, j) + h < s.length() && s.charAt(i + h) == s.charAt(j + h); ++h) ; lcp[rank[i]] = h; if (h > 0) --h; } } return lcp; } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
2dd5b8b3593f03c9f427eb32ec2b7328
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
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 Semenov */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static final class TaskE { private static final int MODULO = 998244353; public void solve(int __, InputReader in, PrintWriter out) { char[] number = in.next().toCharArray(); char[] min = in.next().toCharArray(); boolean zeroAllowed = min.length == 1 && min[0] == '0'; char[] max = in.next().toCharArray(); boolean[] lessMin = compareAll(number, min, true); boolean[] lessOrEqualMax = compareAll(number, max, false); TaskE.FenwickTree dp = new TaskE.FenwickTree(number.length + 1); dp.add(0, 1, 1); for (int i = 0; i < number.length; ++i) { int current = dp.get(i); if (current == 0) continue; if (number[i] == '0') { if (zeroAllowed) { dp.add(i + 1, i + 2, current); } } else { int from = i + min.length; if (lessMin[i]) from++; int to = i + max.length; if (!lessOrEqualMax[i]) to--; if (from <= to) { dp.add(from, to + 1, current); } } } out.println(dp.get(number.length)); } private boolean[] compareAll(char[] number, char[] threshold, boolean strict) { char[] temp = new char[threshold.length + number.length + 1]; System.arraycopy(threshold, 0, temp, 0, threshold.length); temp[threshold.length] = '#'; System.arraycopy(number, 0, temp, threshold.length + 1, number.length); int[] z = StringUtils.buildZFunction(temp); int length = number.length; boolean[] result = new boolean[length]; for (int i = 0; i < number.length; ++i) { int j = i + threshold.length + 1; result[i] = z[j] == threshold.length ? !strict : i + threshold.length > length || number[i + z[j]] < threshold[z[j]]; } return result; } static class FenwickTree { private final int[] tree; FenwickTree(int capacity) { tree = new int[capacity]; } void add(int from, int delta) { int at = from; while (at < tree.length) { tree[at] = (tree[at] + delta) % MODULO; at |= at + 1; } } void add(int from, int to, int delta) { add(from, delta); add(to, MODULO - delta); } int get(int at) { int result = 0; while (at >= 0) { result = (result + tree[at]) % MODULO; at = (at & at + 1) - 1; } return result; } } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } static class StringUtils { public static int[] buildZFunction(final char[] string) { final int length = string.length; final int[] zFunction = new int[length]; for (int i = 1, l = 0, r = 0; i < length; ++i) { if (i < r) { zFunction[i] = Math.min(zFunction[i - l], r - i); } while (i + zFunction[i] < length && string[zFunction[i]] == string[i + zFunction[i]]) { zFunction[i]++; } if (i + zFunction[i] > r) { l = i; r = i + zFunction[i]; } } return zFunction; } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
303d550c499710a550796303d6c469f2
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long TIME_START, TIME_END; public static class Task { int mod = 998244353; public class Z { int[] z; public void build(char[] s) { int n = s.length; z = new int[n]; int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } else { int k = i-L; if (z[k] < R-i+1) z[i] = z[k]; else { L = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } } } } } char[] s; char[] L; char[] R; public int findStartingIndex(Z zL, int idx, int lLength) { int actualIdx = idx + lLength + 1; int matchL = zL.z[actualIdx]; if (matchL == lLength) { return idx + lLength; } if (idx + matchL >= s.length) return s.length * 2; if (L[matchL] < s[idx + matchL]) { return idx + lLength; } else { return idx + lLength + 1; } } public int findEndingIndex(Z zR, int idx, int rLength) { int actualIdx = idx + rLength + 1; int matchR = zR.z[actualIdx]; if (matchR == rLength) { return idx + rLength; } if (idx + matchR >= s.length) return s.length * 2; if (R[matchR] < s[idx + matchR]) { return idx + rLength - 1; } else { return idx + rLength; } } public Z buildLR(char[] L, int lLength) { char[] sL = new char[s.length + 1 + lLength]; for (int i = 0; i < lLength; i++) { sL[i] = L[i]; } sL[lLength] = 0; for (int i = 0; i < s.length; i++) { sL[i + lLength + 1] = s[i]; } Z z = new Z(); z.build(sL); return z; } public long sub(long a, long b) { return (a - b + mod) % mod; } public long add(long a, long b) { return (a + b) % mod; } public void solve(Scanner sc, PrintWriter pw) throws IOException { s = sc.next().toCharArray(); L = sc.next().toCharArray(); R = sc.next().toCharArray(); int lLength = L.length; int rLength = R.length; Z zL = buildLR(L, lLength); Z zR = buildLR(R, rLength); long[] dp = new long[s.length * 2]; long curCount = 0; dp[0] = add(dp[0], 1); dp[1] = sub(dp[1], 1); for (int i = 0; i < s.length; i++) { curCount = add(curCount, dp[i]); if (curCount != 0) { if (s[i] == '0') { if (L.length == 1 && L[0] == '0') { dp[i + 1] = add(dp[i + 1], curCount); dp[i + 2] = sub(dp[i + 2], curCount); } } else { int nextMinIdx = findStartingIndex(zL, i, lLength); int nextMaxIdx = findEndingIndex(zR, i, rLength); nextMaxIdx = Math.min(nextMaxIdx, s.length); if (nextMinIdx <= nextMaxIdx) { dp[nextMinIdx] = add(dp[nextMinIdx], curCount); dp[nextMaxIdx + 1] = sub(dp[nextMaxIdx + 1], curCount); } } } } pw.println(add(curCount, dp[s.length])); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); // System.out.println("Memory increased:" + (usedMemoryAfter - usedMemoryBefore) / 1000000); // System.out.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
441cc566d200d2ac9d911bb3f15ca3d2
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
//package com.company; import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long TIME_START, TIME_END; public static class Task { int mod = 998244353; public class Z { int[] z; public void build(char[] s) { int n = s.length; z = new int[n]; int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } else { int k = i-L; if (z[k] < R-i+1) z[i] = z[k]; else { L = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } } } } } char[] s; char[] L; char[] R; public int findStartingIndex(Z zL, int idx, int lLength) { int actualIdx = idx + lLength + 1; int matchL = zL.z[actualIdx]; if (matchL == lLength) { return idx + lLength; } if (idx + matchL >= s.length) return s.length * 2; if (L[matchL] < s[idx + matchL]) { return idx + lLength; } else { return idx + lLength + 1; } } public int findEndingIndex(Z zR, int idx, int rLength) { int actualIdx = idx + rLength + 1; int matchR = zR.z[actualIdx]; if (matchR == rLength) { return idx + rLength; } if (idx + matchR >= s.length) return s.length * 2; if (R[matchR] < s[idx + matchR]) { return idx + rLength - 1; } else { return idx + rLength; } } public Z buildLR(char[] L, int lLength) { char[] sL = new char[s.length + 1 + lLength]; for (int i = 0; i < lLength; i++) { sL[i] = L[i]; } sL[lLength] = 0; for (int i = 0; i < s.length; i++) { sL[i + lLength + 1] = s[i]; } Z z = new Z(); z.build(sL); return z; } public long sub(long a, long b) { return (a - b + mod) % mod; } public long add(long a, long b) { return (a + b) % mod; } public void solve(Scanner sc, PrintWriter pw) throws IOException { s = sc.next().toCharArray(); L = sc.next().toCharArray(); R = sc.next().toCharArray(); int lLength = L.length; int rLength = R.length; Z zL = buildLR(L, lLength); Z zR = buildLR(R, rLength); long[] dp = new long[s.length * 2]; long curCount = 0; dp[0] = add(dp[0], 1); dp[1] = sub(dp[1], 1); for (int i = 0; i < s.length; i++) { curCount = add(curCount, dp[i]); if (curCount != 0) { if (s[i] == '0') { if (L.length == 1 && L[0] == '0') { dp[i + 1] = add(dp[i + 1], curCount); dp[i + 2] = sub(dp[i + 2], curCount); } } else { int nextMinIdx = findStartingIndex(zL, i, lLength); int nextMaxIdx = findEndingIndex(zR, i, rLength); nextMaxIdx = Math.min(nextMaxIdx, s.length); if (nextMinIdx <= nextMaxIdx) { dp[nextMinIdx] = add(dp[nextMinIdx], curCount); dp[nextMaxIdx + 1] = sub(dp[nextMaxIdx + 1], curCount); } } } } pw.println(add(curCount, dp[s.length])); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); // System.out.println("Memory increased:" + (usedMemoryAfter - usedMemoryBefore) / 1000000); // System.out.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
1f8f0ae618cb99a7d5f46fdf522cde9e
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long TIME_START, TIME_END; public static class Task { int mod = 998244353; public class Z { int[] z; public void build(char[] s) { int n = s.length; z = new int[n]; int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } else { int k = i-L; if (z[k] < R-i+1) z[i] = z[k]; else { L = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } } } } } char[] s; char[] L; char[] R; public int findStartingIndex(Z zL, int idx, int lLength) { int actualIdx = idx + lLength + 1; int matchL = zL.z[actualIdx]; if (matchL == lLength) { return idx + lLength; } if (idx + matchL >= s.length) return s.length * 2; if (L[matchL] < s[idx + matchL]) { return idx + lLength; } else { return idx + lLength + 1; } } public int findEndingIndex(Z zR, int idx, int rLength) { int actualIdx = idx + rLength + 1; int matchR = zR.z[actualIdx]; if (matchR == rLength) { return idx + rLength; } if (idx + matchR >= s.length) return s.length * 2; if (R[matchR] < s[idx + matchR]) { return idx + rLength - 1; } else { return idx + rLength; } } public Z buildLR(char[] L, int lLength) { char[] sL = new char[s.length + 1 + lLength]; for (int i = 0; i < lLength; i++) { sL[i] = L[i]; } sL[lLength] = 0; for (int i = 0; i < s.length; i++) { sL[i + lLength + 1] = s[i]; } Z z = new Z(); z.build(sL); return z; } public long sub(long a, long b) { return (a - b + mod) % mod; } public long add(long a, long b) { return (a + b) % mod; } public void solve(Scanner sc, PrintWriter pw) throws IOException { s = sc.next().toCharArray(); L = sc.next().toCharArray(); R = sc.next().toCharArray(); int lLength = L.length; int rLength = R.length; Z zL = buildLR(L, lLength); Z zR = buildLR(R, rLength); long[] dp = new long[s.length * 2]; long curCount = 0; dp[0] = add(dp[0], 1); dp[1] = sub(dp[1], 1); for (int i = 0; i < s.length; i++) { curCount = add(curCount, dp[i]); if (curCount != 0) { if (s[i] == '0') { if (L.length == 1 && L[0] == '0') { dp[i + 1] = add(dp[i + 1], curCount); dp[i + 2] = sub(dp[i + 2], curCount); } } else { int nextMinIdx = findStartingIndex(zL, i, lLength); int nextMaxIdx = findEndingIndex(zR, i, rLength); nextMaxIdx = Math.min(nextMaxIdx, s.length); if (nextMinIdx <= nextMaxIdx) { dp[nextMinIdx] = add(dp[nextMinIdx], curCount); dp[nextMaxIdx + 1] = sub(dp[nextMaxIdx + 1], curCount); } } } } pw.println(add(curCount, dp[s.length])); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); // System.out.println("Memory increased:" + (usedMemoryAfter - usedMemoryBefore) / 1000000); // System.out.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
35dcc736199f20091e3a1b17d98007b8
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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() { 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); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } int[] findZValue(char[] s) { int[] z = new int[s.length]; int l = 0, r = 0; for(int i = 1; i < s.length; ++i) { if(i > r) { l = i; r = i - 1; while(r + 1 < s.length && s[r + 1] == s[r + 1 - l]) r++; z[i] = r - l + 1; } else { if(r - i + 1 <= z[i - l]) { l = i; while(r + 1 < s.length && s[r + 1] == s[r + 1 - l]) r++; z[i] = r - l + 1; } else z[i] = z[i - l]; } } return z; } int[] solve(char[] l, char[] a) { char[] s = new char[a.length + l.length + 1]; for(int i = 0; i < l.length; ++i) s[i] = l[i]; s[l.length] = '$'; for(int i = 0; i < a.length; ++i) s[l.length + 1 + i] = a[i]; int[] z = findZValue(s); int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = z[l.length + 1 + i]; return ans; } int compare(char[] l, char[] a, int[] z, int ind) { if(z[ind] == l.length) return 0; if(l[z[ind]] > a[ind + z[ind]]) return 1; return -1; } long mod = (long)998244353; long dp[], sum[]; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); char[] a = sc.next().toCharArray(); char[] l = sc.next().toCharArray(); char[] r = sc.next().toCharArray(); int[] zla = solve(l, a); int[] zra = solve(r, a); boolean canBeZero = (l.length == 1 && l[0] == '0'); int n = a.length; dp = new long[n + 1]; sum = new long[n + 1]; long[] actdp = new long[n + 1]; dp[0] = 1L; sum[0] = 1L; actdp[0] = 1L; for(int i = 0; i < n; ++i) { if(canBeZero && a[i] == '0') dp[i + 1] = dp[i]; if(l.length == r.length && i - l.length + 1 >= 0) { if(compare(l, a, zla, i - l.length + 1) <= 0 && compare(r, a, zra, i - l.length + 1) >= 0) dp[i + 1] = (dp[i + 1] + actdp[i - l.length + 1]) % mod; } else { if(i - l.length + 1 >= 0 && compare(l, a, zla, i - l.length + 1) <= 0) dp[i + 1] = (dp[i + 1] + actdp[i - l.length + 1]) % mod; if(i - l.length >= 0) dp[i + 1] = (dp[i + 1] + sum[i - l.length]) % mod; if(i - r.length + 1 >= 0) dp[i + 1] = (dp[i + 1] - sum[i - r.length + 1] + mod) % mod; if(i - r.length + 1 >= 0 && compare(r, a, zra, i - r.length + 1) >= 0) dp[i + 1] = (dp[i + 1] + actdp[i - r.length + 1]) % mod; } if(i + 1 < n && a[i + 1] != '0') { sum[i + 1] = (sum[i] + dp[i + 1]) % mod; actdp[i + 1] = dp[i + 1]; } else if(i + 1 < n) sum[i + 1] = sum[i]; } w.print(dp[n]); w.close(); } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
113cb4425a6807b297a1cf834a95bcfe
train_000.jsonl
1537454700
Vasya owns three big integers β€” $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
256 megabytes
import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.*; import java.io.*; public class Main { private static char [] A,L,R; private static long mod = 998244353; private static long add(long a,long b) { a += b; if (a >= mod) a -= mod; if (a < 0) a += mod; return a; } private static int solve(){ long [] dp = new long[A.length+1]; long [] suff = new long[A.length+2]; dp[A.length] = 1; suff[A.length] = 1; DS dsL = new DS(L,A); DS dsR = new DS(R,A); boolean LIsZero = L.length == 1 && L[0] == '0'; for (int i = A.length-1;i >= 0;i--) { if (A[i] != '0' && dsL.cmp(i,A.length-1) <= 0) { int s = i,e = A.length-1; while (s < e) { int m = (s + e) >> 1; if (dsL.cmp(i,m) <= 0) e = m; else s = m+1; } int l = s; if (dsR.cmp(i,l) >= 0) { e = A.length-1; while (s < e) { int m = s + (e-s+1)/2; if (dsR.cmp(i,m) >= 0) s = m; else e = m-1; } int r = s; dp[i] = add(suff[l+1],-suff[r+2]); // int bf = 0; // for (int j = l;j <= r;j++) // bf += dp[j+1]; // System.err.println(i + " " + A[i] + ": " + l + " " + r); } } else if (A[i] == '0' && LIsZero) { dp[i] = dp[i+1]; } suff[i] = add(dp[i],suff[i+1]); // System.err.println(dp[i]); } return (int)dp[0]; } private static void canon(char [] C,Random g) { if (C.length == 1) return; if (C[0] == '0') C[0] = (char)(Math.abs(g.nextInt()%9) + '1'); } private static void canon(char [] L,char [] R,Random g) { if (L.length != R.length) return; int i = 0; while (i < L.length && L[i] == R[i]) i++; if (i == R.length) return; if (L[i] < R[i]) return; while (R[i] < L[i]) R[i]++; for (int c = Math.abs(g.nextInt()%3);c > 0 && R[i] < '8';c--) R[i]++; } private static void gen(){ Random g = new Random(); int a = Math.abs(g.nextInt()%10) + 1; int l = Math.abs(g.nextInt()%6) + 1; int r = l + Math.abs(g.nextInt()%2); A = new char[a]; L = new char[l]; R = new char[r]; for (int i = 0;i < a;i++) A[i] = (char)('0' + Math.abs(g.nextInt()%10)); for (int i = 0;i < l;i++) L[i] = (char)('0' + Math.abs(g.nextInt()%10)); for (int i = 0;i < r;i++) R[i] = (char)('0' + Math.abs(g.nextInt()%10)); canon(A,g); canon(L,g); canon(R,g); canon(L,R,g); } private static int bf(){ int [] dp = new int[A.length+1]; dp[A.length] = 1; int l = 0,r = 0; for (char c : L) l = l*10 + c - '0'; for (char c : R) r = r*10 + c - '0'; for (int i = A.length-1;i >= 0;i--) { int j = i; int num = 0; while (j < A.length && num*10+A[j]-'0' < l) { num = num*10 + A[j] - '0'; j++; } int s = j,e = j; while (j < A.length && num*10+A[j]-'0' <= r){ num = num*10 + A[j] - '0'; e = j; j++; } if (s == A.length) continue; if (A[i] != '0') { for (j = s;j <= e;j++) dp[i] += dp[j+1]; } else { if (s == i) dp[i] = dp[i+1]; } } return dp[0]; } private static void test() throws Exception{ for (int t = 1;t <= 1000;t++){ gen(); int correct = bf(); int mine = solve(); if (correct != mine) { throw new Exception("failed on\n" + new String(A) + "\n" + new String(L) + "\n" + new String(R) + "\n" + "expected " + correct + " found " + mine); } } System.out.println("AC :)"); } public static void main(String[] args) throws Exception { IO io ; try { io = new IO("in.in", null); } catch (IOException e) { io = new IO(null, null); } A = io.getNext().toCharArray(); L = io.getNext().toCharArray(); R = io.getNext().toCharArray(); io.println(solve()); // test(); io.close(); } private static final int onebillion7 = 1000000007; } class DS{ char [] txt; int pattLen; int [] Z; private void buildZ(){ Z = new int[txt.length]; int l = 0,r = 0; for (int i = 1;i < txt.length;i++) { if (i > r) { l = r = i; while (r < txt.length && txt[r-l] == txt[r]) r++; Z[i] = r-l; r--; } else { int k = i-l; if (Z[k] < r-i+1) Z[i] = Z[k]; else { l = i; while (r < txt.length && txt[r-l]==txt[r]) r++; Z[i] = r-l; r--; } } } } public DS(char [] P,char [] T) { txt = new char[P.length+1+T.length]; pattLen = P.length; int m = 0; for (char c : P) txt[m++] = c; txt[m++] = '$'; for (char c : T) txt[m++] = c; buildZ(); } public int cmp(int s,int e) { s += pattLen+1; e += pattLen+1; int len = e-s+1; if (len != pattLen) return pattLen - len; int l = Math.min(Z[s],len); char a = txt[l]; char b = '$'; if (s + l <= e) b = txt[s + l]; return a - b; } } class pair implements Comparable<pair>{ int k,s; public pair(int a,int b) { k = a; s = b; } @Override public int compareTo(pair o) { if (k == o.k) return (s - o.s); return -(k - o.k); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public boolean hasMore() throws IOException{ if(st != null && st.hasMoreTokens()) return true; if(br != null && br.ready()) return true; return false; } public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } public void outputArr(Object [] A) throws IOException{ int L = A.length; for (int i = 0;i < L;i++) { if(i > 0) writer.print(" "); writer.print(A[i]); } writer.print("\n"); } } //class PollardRho { // private final static BigInteger ZERO = new BigInteger("0"); // private final static BigInteger ONE = new BigInteger("1"); // private final static BigInteger TWO = new BigInteger("2"); // private final static SecureRandom random = new SecureRandom(); // private static ArrayList<Long> primes = new ArrayList<>(); // // private static BigInteger rho(BigInteger N) { // BigInteger divisor; // BigInteger c = new BigInteger(N.bitLength(), random); // BigInteger x = new BigInteger(N.bitLength(), random); // BigInteger xx = x; // // // check divisibility by 2 // if (N.base(TWO).compareTo(ZERO) == 0) return TWO; // // do { // x = x.multiply(x).base(N).add(c).base(N); // xx = xx.multiply(xx).base(N).add(c).base(N); // xx = xx.multiply(xx).base(N).add(c).base(N); // divisor = x.subtract(xx).gcd(N); // } while((divisor.compareTo(ONE)) == 0); // // return divisor; // } // // private static void factor(BigInteger N) { // if (N.compareTo(ONE) == 0) return; // if (N.isProbablePrime(20)) { // primes.add(N.longValue()); // return; // } // BigInteger divisor = rho(N); // factor(divisor); // factor(N.divide(divisor)); // } // // // public static ArrayList<Long> factor(Long n) { // primes.clear(); // factor(BigInteger.valueOf(n)); // return primes; // } //} class complex{ BigDecimal real,imag; private static DecimalFormat df = new DecimalFormat("#.###"); public complex(double x,double y){ real = new BigDecimal(x); imag = new BigDecimal(y); } public complex(BigDecimal x,BigDecimal y) { real = new BigDecimal(x.toString()); imag = new BigDecimal(y.toString()); } public complex(double t) { real = new BigDecimal(Math.cos(t)); imag = new BigDecimal(Math.sin(t)); } public complex add(complex o){ return new complex(real.add(o.real),imag.add(o.imag)); } public complex sub(complex o) { return new complex(real.subtract(o.real),imag.subtract(o.imag)); } public complex mult(double c) { BigDecimal bc = new BigDecimal(c); return new complex(real.multiply(bc),imag.multiply(bc)); } public complex mult(complex o) { BigDecimal a = real.multiply(o.real).subtract(imag.multiply(o.imag)); BigDecimal b = real.multiply(o.imag).add(imag.multiply(o.real)); return new complex(a,b); } public complex divide(complex o) { return this.mult(new complex(o.real,o.imag.negate())).divide(o.norm2()); } public complex divide(double c) { BigDecimal bc = new BigDecimal(c); return new complex(real.divide(bc),imag.divide(bc)); } public complex divide(BigDecimal bc) { return new complex(real.divide(bc),imag.divide(bc)); } public BigDecimal norm2(){ return real.multiply(real).add(imag.multiply(imag)); } public double norm(){ return Math.sqrt(norm2().doubleValue()); } @Override public String toString(){ return "(" + df.format(real) + ", " + df.format(imag) + ")"; } } class FFT{ public static long [] mult(long [] A,long [] B) { int n = A.length; while (n != (n & -n)) n++; n <<= 1; complex [] pA = new complex[n]; complex [] pB = new complex[n]; complex [] pC = new complex[n]; for (int i = 0;i < n;i++) { if (i < A.length){ pA[i] = new complex(A[i],0); pB[i] = new complex(B[i],0); } else { pA[i] = new complex(0,0); pB[i] = new complex(0,0); } } pA = fft(pA,false); pB = fft(pB,false); for (int i = 0;i < pC.length;i++) pC[i] = pA[i].mult(pB[i]); pC = fft(pC,true); long [] C = new long[n]; for (int i = 0;i < n;i++) { long mod = 1000*1000*1000; BigDecimal bc = pC[i].real.remainder(new BigDecimal(mod)); C[i] %= Math.round(bc.doubleValue()); } return C; } private static complex[] fft(complex [] f,boolean inv) { if (f.length == 1) return f; int n = f.length; complex wn = new complex((inv ? -1 : 1)*2*Math.PI/n),w = new complex(1,0); complex [] E = new complex[n/2],O = new complex[n/2]; for (int i = 0;i < n;i++){ if (i%2 == 0) E[i >> 1] = f[i]; else O[i >> 1] = f[i]; } E = fft(E,inv); O = fft(O,inv); for (int k = 0;k < n/2;k++){ f[k] = E[k].add(w.mult(O[k])); f[k+n/2] = E[k].sub(w.mult(O[k])); w = w.mult(wn); } return f; } }
Java
["135\n1\n15", "10000\n0\n9"]
1 second
["2", "1"]
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
Java 8
standard input
[ "dp", "hashing", "data structures", "binary search", "strings" ]
0d212ea4fc9f03fdd682289fca9b517e
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
2,600
Print a single integer β€” the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
standard output
PASSED
2273f2faca49d0e694cc9e1f1ce64112
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(), m = scan.nextInt(); int[][] a = new int[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) a[i][j] = scan.nextInt(); for(int it = 1; it <= n; it++){ int[][] cur = new int[it][m]; for(int i = 0; i < it; i++) for(int j = 0; j < m; j++) cur[i][j] = a[i][j]; boolean good = true; while(cur.length < n){ int[][] temp = new int[cur.length*2][m]; for(int i = 0; i < cur.length; i++) temp[i] = cur[i].clone(); for(int i = cur.length, ii = cur.length-1; i < cur.length*2; i++, ii--) temp[i] = cur[ii].clone(); cur = temp.clone(); } if(cur.length > n) good = false; else { for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(cur[i][j] != a[i][j]) good = false; } } } if(good) { out.println(it); break; } } out.close(); } static 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 String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { 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 int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
d376d3cfa40cef70c20c38dc29e21558
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Integer.*; public class Main { public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { // GCD && LCM long gcd(long a ,long b){return b == 0 ? a : gcd(b , a % b);} long lcm(long a , long b){return a*(b/gcd(a, b));} // REverse a String String rev(String s){ return new StringBuilder(s).reverse().toString(); } /* SOLUTION IS RIGHT HERE */ public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{ //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc = new Scanner(System.in); int n = in.nextInt() , m = in.nextInt(); int[][] grid = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) grid[i][j] = in.nextInt(); } int row = n; boolean bool = true; while(bool){ if(row % 2 != 0)break; for(int i = 0; i < row/2; i++){ for(int j = 0; j < m; j++){ if(grid[i][j] != grid[row - i -1][j]){ bool = false; break; } } } if(bool)row = row /2; } out.println(row); } } // ||||||| INPUT READER |||||||| static class InputReader { private byte[] buf = new byte[8000]; private int index; private int total; private InputStream in; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream){ in = stream; } public int scan(){ if(total == -1) throw new InputMismatchException(); if(index >= total){ index = 0; try{ total = in.read(buf); }catch(IOException e){ throw new InputMismatchException(); } if(total <= 0) return -1; } return buf[index++]; } public long scanlong(){ long integer = 0; int n = scan(); while(isWhiteSpace(n)) n = scan(); int neg = 1; if(n == '-'){ neg = -1; n = scan(); } while(!isWhiteSpace(n)){ if(n >= '0' && n <= '9'){ integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg*integer; } private int scanInt() { int integer = 0; int n = scan(); while(isWhiteSpace(n)) n = scan(); int neg = 1; if(n == '-'){ neg = -1; n = scan(); } while(!isWhiteSpace(n)){ if(n >= '0' && n <= '9'){ integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scandouble(){ double doubll = 0; int n = scan(); int neg = 1; while(isWhiteSpace(n)) n = scan(); if(n == '-'){ neg = -1; n = scan(); } while(!isWhiteSpace(n) && n != '.'){ if(n >= '0' && n <= '9'){ doubll *= 10; doubll += n - '0'; n = scan(); } } if(n == '.'){ n = scan(); double temp = 1; while(!isWhiteSpace(n)){ if(n >= '0' && n <= '9'){ temp /= 10; doubll += (n - '0')*temp; n = scan(); } } } return neg*doubll; } private float scanfloat() { float doubll = 0; int n = scan(); int neg = 1; while(isWhiteSpace(n)) n = scan(); if(n == '-'){ neg = -1; n = scan(); } while(!isWhiteSpace(n) && n != '.'){ if(n >= '0' && n <= '9'){ doubll *= 10; doubll += n - '0'; n = scan(); } } if(n == '.'){ n = scan(); double temp = 1; while(!isWhiteSpace(n)){ if(n >= '0' && n <= '9'){ temp /= 10; doubll += (n - '0')*temp; n = scan(); } } } return neg*doubll; } public String scanstring(){ StringBuilder sb = new StringBuilder(); int n = scan(); while(isWhiteSpace(n)) n = scan(); while(!isWhiteSpace(n)){ sb.append((char)n); n = scan(); } return sb.toString(); } public String scan_nextLine() { int n = scan(); while (isWhiteSpace(n)) n = scan(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(n); n = scan(); } while (!isEndOfLine(n)); return res.toString(); } public boolean isWhiteSpace(int n){ if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } /// Input module public int nextInt(){ return scanInt(); } public long nextLong(){ return scanlong(); } public double nextDouble(){ return scandouble(); } public float nextFloat(){ return scanfloat(); } public String next(){ return scanstring(); } public String nextLine() throws IOException{ return scan_nextLine(); } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
b25fb1c3f6831c66c4670b9ee5aec1f1
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(); int[][] a = new int[n][m]; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) a[i][j] = sc.nextInt(); int rows = n; while(cut(a, rows)) rows >>= 1; out.println(rows); out.flush(); out.close(); } static boolean cut(int[][] a, int rows) { if(rows%2 == 1) return false; for(int i = 0; i < rows>>1; ++i) if(!match(a[i], a[rows-i-1])) return false; return true; } static boolean match(int[] x, int[] y) { for(int i = 0; i < x.length; ++i) if(x[i] != y[i]) return false; return true; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} 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
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
4fb1c13927a117d8c74946a76ff9981b
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionB { public static void main(String[] args) { new SolutionB().run(); } int a[][]; int b[][]; int n; int m; void go(int x){ if(x == n) return; for(int i = 0; i < x; i++){ for(int j = 0; j < m; j++){ b[2 *x - 1 - i][j] = b[i][j]; } } go(2 * x); } boolean check(int x){ while(x % 2 ==0) x/=2; return x == 1; } void solve() { n = in.nextInt(); m = in.nextInt(); a = new int[n][m]; b = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ a[i][j] = in.nextInt(); } } int c = 1; for(int i = 1; i<=n; i++){ if(n % i == 0 && check(n/i)){ for(int k = 0; k < i; k++) for(int j = 0; j < m; j++) b[k][j] = a[k][j]; go(i); boolean ok = true; for(int k = 0; k < n; k++) for(int j=0; j < m; j++) if(a[k][j] != b[k][j]) ok = false; if(ok){ out.println(i); return; } } } } class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (o.x == x) return ((Integer) y).compareTo(o.y); return ((Integer) x).compareTo(o.x); } } FastScanner in; PrintWriter out; void run() { in = new FastScanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } void runIO() { try { in = new FastScanner(new File("expr.in")); out = new PrintWriter(new FileWriter(new File("expr.out"))); solve(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(File f) { try { bf = new BufferedReader(new FileReader(f)); } catch (IOException ex) { ex.printStackTrace(); } } public FastScanner(InputStream is) { bf = new BufferedReader(new InputStreamReader(is), 32768); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException ex) { ex.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { try { return bf.readLine(); } catch (Exception ex) { ex.printStackTrace(); } return ""; } long nextLong() { return Long.parseLong(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
40c847a2c26543f60e60dcd6ea4a0105
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; public class Codeforces243B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); int[][] ma = new int[n][]; for (int i = 0; i < n; i++) { ma[i] = new int[m]; for (int j = 0; j < m; j++) { ma[i][j] = in.nextInt(); } } int nn = n; while (isMirror(ma, nn)) { nn /= 2; } System.out.println(nn); } public static boolean isMirror(int[][] ma, int n) { if (n % 2 != 0) return false; for (int i = 0; i < n / 2; i++) { if (!Arrays.equals(ma[i], ma[n - 1 - i])) { return false; } } return true; } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
3a604f7a0c3279066cd9cee129f77b80
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.*; import java.util.*; public class CodeForce { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder sb = new StringBuilder(); public static int checkreverse(int[][] arr,int n) { if(n%2==1) return n; for(int i=n/2-1;i>=0;i--) { for(int j=0;j<arr[0].length;j++) { if(arr[i][j]!=arr[n-i-1][j]) return n; } } return checkreverse(arr,n/2); } static boolean flag = false; static int next(String [] sr,int ind) { return Integer.parseInt(sr[ind]); } public static void main(String[] args) throws IOException { String[] sr=br.readLine().split(" "); int n=next(sr,0); int m=next(sr,1); int[][] arr=new int[n][m]; for(int i=0;i<n;i++) {sr=br.readLine().split(" "); for(int j=0;j<m;j++) arr[i][j]=next(sr,j); } System.out.println(checkreverse(arr,n)); }}
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
182ddac0ece6588e5932ad31fc9af3a6
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws InterruptedException { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static void solve(MyScanner in, PrintWriter out) { int n,m; n = in.nextInt(); m = in.nextInt(); int[][] mt = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0;j < m; j++) { mt[i][j] = in.nextInt(); } } int ans = n; while (ans % 2 == 0 && isSym(mt, ans)) { ans /= 2; } out.println(ans); } static boolean isSym(int[][] mt, int len) { int up = len / 2 - 1; int down = len / 2; int m = mt[0].length; while (up >= 0) { for (int i = 0; i < m; i++) { if (mt[up][i] != mt[down][i]) { return false; } } up--; down++; } return true; } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
740e831fafd106cb994d5f30530ce3c4
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SerejaMirroring { void solve() { int n = in.nextInt(), m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = in.nextInt(); boolean[][] same = new boolean[n][n]; for (int i = 0; i < n; i++) { same[i][i] = true; for (int j = i + 1; j < n; j++) { same[i][j] = true; for (int k = 0; k < m; k++) { if (a[i][k] != a[j][k]) { same[i][j] = false; break; } } same[j][i] = same[i][j]; } } int ans = n; while (n % 2 == 0) { boolean ok = true; for (int i = 0; i < n / 2; i++) { int j = n - 1 - i; if (!same[i][j]) { ok = false; break; } } if (!ok) break; ans = n / 2; n /= 2; } out.println(ans); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SerejaMirroring().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
853126cb882e2ce8521b0967e7d6a8d2
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.*; import java.util.*; public class CF426B { static boolean equal(int[] aa, int[] bb, int m) { for (int j = 0; j < m; j++) if (aa[j] != bb[j]) return false; return true; } static int solve(int[][] aa, int n, int m) { if (n % 2 == 1) return n; for (int i = 0, j = n - 1; i < j; i++, j--) if (!equal(aa[i], aa[j], m)) return n; return solve(aa, n / 2, m); } 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[][] aa = new int[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < m; j++) aa[i][j] = Integer.parseInt(st.nextToken()); } System.out.println(solve(aa, n, m)); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
f093205dfcfdc55a1b0f8c0f25958441
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.awt.Point; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import javax.security.auth.kerberos.KerberosKey; import javax.tools.JavaFileObject.Kind; import static java.lang.Math.*; public class Main { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } int fib(int n) { if (n == 1) return 1; if (n == 2) return 2; else return fib(n - 1) + fib(n - 2); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Main().run(); // Sworn to fight and die } public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int levtIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (levtIndex < rightIndex) { if (rightIndex - levtIndex <= MAGIC_VALUE) { insertionSort(a, levtIndex, rightIndex); } else { int middleIndex = (levtIndex + rightIndex) / 2; mergeSort(a, levtIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, levtIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int levtIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - levtIndex + 1; int length2 = rightIndex - middleIndex; int[] levtArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, levtIndex, levtArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = levtArray[i++]; } else { a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int levtIndex, int rightIndex) { for (int i = levtIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= levtIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LOL implements Comparable<LOL> { int x; int y; public LOL(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(LOL o) { //if (y == o.y) // return (o.x - x); return x - o.x; // ----> // return o.x - x; // <---- // return o.y-y; } } public int binarySearch(int []a, int k) { int l = 0, r = a.length - 1; while (l <= r) { int m = (l + r)/2; if (a[m] == k) return m; else if (a[m] > k) r = m - 1; else l = m + 1; } return -1; } public long prxor(long n) { int m = (int) (n%4); switch (m) { case 0 : return n; case 1 : return 1; case 2 : return n+1; case 3 : return 0; } return 1; } public void solve() throws IOException { int n = readInt(); int m = readInt(); boolean f = true; int[][] a = new int[n][m]; for ( int i = 0; i < n; i++) for (int j = 0; j < m ; j++) a[i][j] = readInt(); while (n%2==0 && f) { for ( int i = 0; i < n/2; i++) for (int j = 0; j < m ; j++) if (a[i][j] != a [n - i - 1][j]) f = false; if (f) n/=2; } out.print(n); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
a2df5f49b165beb92381a49685406d69
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Machis */ public class SerejaandMirroring { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); long[][] a = new long[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(bf.readLine()); for (int j = 0; j < m; j++) { a[i][j] = Integer.parseInt(st.nextToken()); } } boolean end = n%2!=0; while (n%2==0 && !end){ for (int i = 0; i < n/2 && !end;i++){ for (int j = 0; j < m; j++) { if (a[i][j]!=a[n-(i+1)][j]){ end = !end; break; } } } if (!end)n = n/2; } System.out.println(n); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
19aa3d5eb0bc5c47ab886b38935bc47a
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.Scanner; public class SerejaAndMirroring { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows = scan.nextInt(); int columns = scan.nextInt(); if (rows % 2 == 1) { System.out.println(rows); System.exit(0); } if (rows == 1) { System.out.println(rows); System.exit(0); } int result = 0; int[][] mat = new int[rows + 1][columns + 1]; for (int i = 1; i <= rows; ++i) { for (int j = 1; j <= columns; ++j) { mat[i][j] = scan.nextInt(); } } int m = 0; while (rows % 2 == 0) { for (int i = 1; i <= rows / 2 && m != 1; ++i) { for (int j = 1; j <= columns; ++j) { if (mat[i][j] != mat[rows - i + 1][j]) { m = 1; break; } } } if (m == 1) { break; } else { rows /= 2; } } System.out.println(rows); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
e96a5fac26c15609dc5d0a8dc7cc4141
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class B426 { static int n, m; static int[][] a; public static int minPart(int min, int max){ int part = max-min + 1; int high = max; int low = min; if(part % 2 == 0 && min != max){ while(low <= high){ for(int i=0; i<m; i++) if(a[high][i] != a[low][i]) return part; low++; high--; } return Math.max(minPart(min, high), minPart(low, max)); } return part; } public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); m = s.nextInt(); a = new int[n][m]; for(int i=0; i<n; i++) for(int j=0; j<m; j++) a[i][j] = s.nextInt(); System.out.println(minPart(0, n-1)); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
775ac19ebd7a409369c63257655a3da5
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class seeraja_and_mirroring { public static boolean is_a_powerOf2(long n) { return n!=0 && ((n&(n-1)) == 0); } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new BufferedReader(new InputStreamReader(System.in))); String str[]=br.readLine().split(" "); int n=Integer.parseInt(str[0]); int m=Integer.parseInt(str[1]); int a[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++) { String str1[]=br.readLine().split(" "); for(int j=1;j<=m;j++) { a[i][j]=Integer.parseInt(str1[j-1]); } } if(n%2!=0) System.out.println(n); else { int count=0; for(int r=1;r<=n;r++) { boolean check = false; // System.out.println(count); if (n % r == 0 && is_a_powerOf2(n / r)) { //System.out.println(n / r+" "+r); for (int x = r; x <= n - r; x += r) { //System.out.println(n/r); int range = 1; for (int i = x, j = x + 1; range <= r; i--, j++, range++) { for (int k = 1; k <= m; k++) { //System.out.print(a[i][k] + " " + a[j][k]); if (a[i][k] != a[j][k]) { //System.out.println(a[i][k]+" "+a[j][k]+" "+i+" "+j+" "+r+" true"); check = true; break; } } if (check) { break; } } if (check) { break; } } //System.out.println(r); //System.out.println(check+" "+r); if (!check) { count = r; //System.out.println(r); break; } } } if(count==0) System.out.println(n); else System.out.println(count); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
341f3af5e39adc4b645d25abed97fcf5
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { FastIO io; int check(int[][] a, int n) { if (n % 2 == 1) { return n; } int x = n / 2; for (int i = 0; i < x; i++) { if (!Arrays.equals(a[i], a[n - i - 1])) { return n; } } return check(a, x); } // File names!!! void solve() throws IOException { int n = io.nextInt(); int m = io.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = io.nextInt(); } } io.println(check(a, n)); } void run() { try { io = new FastIO(); solve(); io.close(); } catch (Exception e) { e.printStackTrace(); System.exit(abs(-1)); } } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception ignore) { } new Main().run(); } class FastIO extends PrintWriter { private BufferedReader in; private StringTokenizer stok; FastIO() { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } FastIO(String s) throws FileNotFoundException { super("".equals(s) ? "output.txt" : s + ".out"); in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : s + ".in")); } public void close() { super.close(); try { in.close(); } catch (IOException ignored) { } } String next() { while (stok == null || !stok.hasMoreTokens()) { try { stok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return stok.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return null; } } char[] nextCharArray() { return next().toCharArray(); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
fdc9c8b131c4b9441a86cfc5c2203abf
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
/* Author LAVLESH */ import java.util.*; import java.io.*; import java.math.BigInteger; public class solution { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st=new StringTokenizer(""); static public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } /*static boolean isPalindrome(char[]a){ for(int i=0,j=a.length-1;i<a.length;i++,j--) if(a[i]!=a[j])return false; return true; }*/ // static int gcd(int a,int b){return b==0?a:gcd(b,a%b);} /* public static int lcm(int a,int b, int c){ return lcm(lcm(a,b),c); } public static int lcm(int a, int b){ return a*b/gcd(a,b); }*/ //static long max(long a,long b){return a>b?a:b;} //static int min(int a,int b){return a>=b?b:a;} //static int mod=(int)1e9+7; /*static boolean isprime[]=new boolean[100015]; static void sieve(){ Arrays.fill(isprime,true); boolean visited[]=new boolean[100015]; isprime[0]=false; isprime[1]=false; for(int i=2;i*i<=100015;i++){ visited[i]=true; for(int j=i*i;j<100015;j+=i){ if(!visited[j]){ visited[j]=true; isprime[j]=false; } } } }*/ /*static int[] nextArray(int n,int x,int y){ int []a=new int[n]; for(int i=x;i<y;i++) a[i]=Integer.parseInt(next()); return a; }*/ /*static void ArrayPrint(int[]a){ for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); }*/ public static void main(String[]args)throws IOException{ PrintWriter op =new PrintWriter(System.out); int n=Integer.parseInt(next()); int m=Integer.parseInt(next()); String[]s=new String[n]; for(int i=0;i<n;i++) s[i]=br.readLine(); if(n%2==1){System.out.println(n);return;} int x=n; while(x%2==0)x/=2; boolean flag=true; for(int i=0;i<=n/2;i++){ if(!s[i].equals(s[n-1-i])){flag=false;break;} } if(!flag){System.out.println(n);return;} while(x<=n/2){ flag=true; for(int i=0;i<x;i++){ if(!s[i].equals(s[2*x-1-i])){flag=false;break;} } if(flag)break; x*=2; } op.println(x); op.close(); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
156af0ec816194fb9b948290205377c9
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int x = sc.nextInt(), y = sc.nextInt(); int mat[][] = new int[x][y]; for (int i = 0; i < x; ++i) for (int j = 0; j < y; ++j) mat[i][j] = sc.nextInt(); if (x % 2 == 1) { System.out.println(x); } else { while (true) { boolean ok = true; for (int i = 0; i < x / 2 && ok; ++i) { for (int j = 0; j < y; ++j) { if (mat[i][j] != mat[x - i - 1][j]) {ok = false;break;} } } if(!ok){System.out.println(x);return;} else if(ok && (x/2)%2==1){System.out.println(x/2);return;} else x/=2; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } 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
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
fda0844ec1b41c7aab06a05962e873bb
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.math.*; import java.io.*; import java.util.*; public class C426B{ public static void main(String[] args) throws IOException{ Scanner sc=new Scanner(System.in); int N=sc.nextInt(); int S=sc.nextInt(); int[][] ar=new int[N][S]; for(int x=0;x<N;x++) for(int y=0;y<S;y++) ar[x][y]=sc.nextInt(); if(N%2!=0) System.out.println(N); else{ int temp=N; int min=N; while(temp%2==0){ if(check(ar,temp)) min=temp/2; else break; temp=temp/2; } System.out.println(min); } } public static boolean check(int[][] ar,int temp){ for(int x=0;x<temp/2;x++) for(int z=0;z<ar[0].length;z++){ if(ar[x][z]!=ar[temp-x-1][z]) return false; } return true; } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
b6cecab71b367dcd53ef8fb36f27c70a
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } boolean isSame(int [][] a, int i1, int i2, int j1, int j2){ int m = a[0].length; for(int i = 0; i < i2 - i1; i++){ for(int j = 0; j < m; j++) if(a[i1 + i][j] != a[j2 - i - 1][j]) return false; } return true; } private void solve() throws IOException { int n = nextInt(); int m = nextInt(); int a[][] = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) a[i][j] = nextInt(); } int ans = n; while(ans % 2 == 0){ int _ans = ans / 2; if(isSame(a, 0, _ans, _ans, 2 * _ans)){ ans /= 2; } else { break; } } out.println(ans); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
01c57a69a4d627dccc8e07bb98b1ebe5
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BSerejaAndMirroring solver = new BSerejaAndMirroring(); solver.solve(1, in, out); out.close(); } static class BSerejaAndMirroring { private InputReader in; private PrintWriter out; public void solve(int testNumber, InputReader in, PrintWriter out) { this.in = in; this.out = out; int n = in.nextInt(); int m = in.nextInt(); int[][] a = in.nextIntTable(n, m, 1, 1); while (true) { if (n % 2 != 0) { out.println(n); return; } boolean f = false; for (int i = 1; i <= n / 2; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] != a[n - i + 1][j]) { f = true; break; } } } if (f) { out.println(n); break; } n /= 2; } } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public 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 int[][] nextIntTable(int row, int col, int rowSt, int colSt) { int[][] arr = new int[row + rowSt][col + colSt]; for (int i = rowSt; i < row + rowSt; i++) { for (int j = colSt; j < col + colSt; j++) { arr[i][j] = nextInt(); } } return arr; } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
0a43fea9602803037f53b27285d7cef3
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } int ans = n; while (ans % 2 == 0 && ans > 0 && mir(a, ans)) { ans /= 2; } out.println(ans); } boolean mir(int[][] a, int h) { for (int i = 0; i < h / 2; i++) { for (int j = 0; j < a[0].length; j++) { if (a[i][j] != a[h - i - 1][j]) { return false; } } } return true; } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
a7bb3e28fd2bea69efda2c7411c5f6bd
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
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 ATailouloute */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { String[] a; public void solve(int testNumber, QuickScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); a = new String[n]; for (int i = 0; i < n; i++) { a[i] = StringUtils.toString(in.nextIntArray(m)); } int ans = n; while (true) { if (ans % 2 != 0) break; int b = ans / 2; boolean ok = true; for (int i = 0; i < n; i += 2 * b) { if (!ok(i, i + 2 * b - 1)) { ok = false; } } if (!ok) break; ans = b; } out.println(ans); } private boolean ok(int i, int j) { while (i < j) { if (!a[i].equals(a[j])) return false; i++; j--; } return true; } } static class QuickScanner { BufferedReader br; StringTokenizer st; InputStream is; public QuickScanner(InputStream stream) { is = stream; br = new BufferedReader(new InputStreamReader(stream), 32768); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public int[] nextIntArray(int len) { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } } static class StringUtils { public static String toString(int[] a) { StringBuffer sb = new StringBuffer(); for (int x : a) sb.append(x); return sb.toString(); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
c0a06555ec78af6f7e52ae2df5cba340
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class RookBishopKing { private static int n,m; private static int arr[][]; public static int Find(int start, int end){ int size = end-start+1; if (size%2!=0) return size; size/=2; boolean mirror =true; for (int i=0;i<size && mirror == true;++i){ for (int j=0;j<m;++j){ if (arr[i][j] != arr[end-i][j]){ mirror = false; break; } } } if (mirror ==false) return size*2; return Find(0, size-1); } public static void main (String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); arr = new int[n][m]; for (int i=0;i <n; ++i){ for (int j=0;j<m;++j){ arr[i][j] = sc.nextInt(); } } int res = Find(0,n-1); System.out.println(res); sc.close(); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
45126d64aa9f3e1397afa34d9977599f
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.Scanner; public class SerejaandMirroring { public static void main(String asd[])throws Exception{ Scanner in=new Scanner(System.in); int n=in.nextInt(); int m=in.nextInt(); int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=in.nextInt(); if(n%2!=0) System.out.println(n); else{ boolean f=true; while(f && n%2==0){ outer: for(int i=0;i<n/2;i++) { for(int j=0;j<m;j++) if(a[i][j]!=a[n-1-i][j]) { f=false; break outer; } } //System.out.println(f); if(f==true && n%2==0) n/=2; } System.out.println(n); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
4224e8605cf7a9739fe6b809b8cc06e5
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int count = 0; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.out = out; int n = in.nextInt(); int m = in.nextInt(); int[][] mas = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mas[i][j] = in.nextInt(); } } runing(mas); if (count == 0) out.println(n); else out.println(count); } private void runing(int[][] mas) { if (mas.length % 2 == 0) { boolean bol = true; int[][] ar = new int[mas.length / 2][mas[0].length]; for (int i = 0; i < mas.length / 2; i++) { for (int j = 0; j < mas[0].length; j++) { if (mas[i][j] == mas[mas.length - 1 - i][j]) ar[i][j] = mas[i][j]; else { bol = false; break; } } if (bol == false) break; } if (bol) { count = ar.length; runing(ar); } } } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
38e1aa9e9aeb39108ec2d44e83e812ac
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class SerejaAndMirroring { public static void main(String[] args) { PrintWriter pw = new PrintWriter(System.out); reader(System.in); int n = nI(); int m = nI(); if (n % 2 == 1) { System.out.println(n); return; } int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nI(); boolean ok = true; while (n % 2 != 1 && ok) { for (int i = 0; i < n / 2 && ok; i++) { for (int j = 0; j < m && ok; j++) { if (arr[i][j] != arr[n - 1 - i][j]) { ok = false; } } } if (ok) n /= 2; } pw.println(n); pw.close(); } private static BufferedReader br; private static StringTokenizer st; static void reader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } static String n() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nI() { return Integer.parseInt(n()); } static long nL() { return Long.parseLong(n()); } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
59e61f91fe17c2e91118d14d578664fe
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.io.*; import java.lang.*; public class codeforces { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); //Code Starts Here int n = in.nextInt(); int m = in.nextInt(); String[] s = new String[n]; for(int i=0; i<n; i++) s[i] = in.nextLine(); if(n%2==0) { int ans = n; while(ans>0 && ans%2==0) { boolean flag = true; int j = ans/2; for(int i=0; i<ans/2; i++) { if(s[j-1-i].compareTo(s[j+i])!=0) { // pw.println(j-i-1+" "+(j+i)); flag = false; break; } } if(flag == true) ans /= 2; else { break; } } pw.println(ans); } else pw.println(n); //Code Ends Here pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } static boolean coprime(long u, long v) { if (((u | v) & 1) == 0) return false; while ((u & 1) == 0) u >>= 1; if (u == 1) return true; do { while ((v & 1) == 0) v >>= 1; if (v == 1) return true; if (u > v) { long t = v; v = u; u = t; } v -= u; } while (v != 0); return false; } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
c25897125b9161f5d8919586df9ad142
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable{ static LinkedList <Integer> adj[]; static int co=0; static void Check2(int n){ adj=new LinkedList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new LinkedList(); } } static void add(int i,int j){ adj[i].add(j); } public static void main(String[] args) throws Exception { new Thread(null, new Main(), "Check2", 1<<26).start();// to increse stack size in java } public void run(){ /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ //Scanner in=new Scanner(System.in); InputReader in=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++)a[i][j]=in.nextInt(); if(n%2!=0){ w.println(n); } else{ int min=Integer.MAX_VALUE; for(int i=1;i<=n;i++){ int val=n/i; if(n%i==0&&((val&(val-1))==0)){ if(sym(a,i,n,m)){ min=min(min,i); } } } w.println(min(min,n)); } w.close(); } static boolean sym(int a[][],int len,int n,int m){ int b[][]=new int[len][m]; int gap=len; for(int i=0;i<len;i++){ for(int j=0;j<m;j++)b[i][j]=a[i][j]; } int co=0; while(len<n){ if(co%2==0){ int point=gap-1; for(int i=len;i<len+gap;i++){ for(int j=0;j<m;j++){ if(a[i][j]!=b[point][j])return false; } point--; } } else{ int point=0; for(int i=len;i<len+gap;i++){ for(int j=0;j<m;j++){ if(a[i][j]!=b[point][j])return false; } point++; } } len=len+gap; co++; } return true; } static int b[]; static int sum[]; static long dp[][]; static long mod=(long)(1e9+7); /* static long rec(int i,int m,int msb,int n){ if(i>n)return 0; if(i==n){ if(m==0)return 1; else return 0; } } */ static int flag=0; static ArrayList <Integer> flist; static void dfs(int i,int v[],ArrayList <Integer> list){ if(v[i]==0){ v[i]=1; list.add(i); Iterator <Integer>p=adj[i].iterator(); while(p.hasNext()){ Integer ne=p.next(); if(list.contains(ne)){ for(Integer pq:list){ // System.out.println(i+" "+pq+" "+ne); flist.add(pq); } flag=1; } dfs(ne,v,list); } list.remove(new Integer(i)); } } static class node{ int y; int val; node(int a,int b){ y=a; val=b; } } 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); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output
PASSED
4c3bfac33ab1f6d01c17a85c78dc8e12
train_000.jsonl
1398612600
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
256 megabytes
import java.util.Scanner; /** * Created by Mehedi on 6/20/2015. */ public class Main { static int ar[][]=new int[102][102],sum[]=new int[102]; static int check(int n,int m){ if((n%2)!=0) return n; for(int i=1;i<=(n/2);i++){ if(sum[i]==sum[n-i+1]){ boolean flag=true; for(int j=1;j<=m;j++){ if(ar[i][j]!=ar[n-i+1][j]) return n; } } else return n; } return check(n/2,m); } public static void main(String args[]){ int n,m; Scanner input=new Scanner(System.in); while(input.hasNextInt()){ n=input.nextInt(); m=input.nextInt(); for(int i=1;i<=n;i++){ sum[i]=0; for(int j=1;j<=m;j++){ ar[i][j]=input.nextInt(); sum[i]+=ar[i][j]; } } System.out.println(check(n,m)); } } }
Java
["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"]
1 second
["2", "3", "2"]
NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001
Java 8
standard input
[ "implementation" ]
90125e9d42c6dcb0bf3b2b5e4d0f845e
The first line contains two integers, n and m (1 ≀ n, m ≀ 100). Each of the next n lines contains m integers β€” the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 1) β€” the i-th row of the matrix a.
1,300
In the single line, print the answer to the problem β€” the minimum number of rows of matrix b.
standard output