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
5f8f295135ec3980853476326b6c383a
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; public class taskD { class Point { int x, y; int _len2 = -1; public Point(int x, int y) { this.x = x; this.y = y; } int len2() { if (_len2 != -1) { return _len2; } _len2 = x*x + y*y; return _len2; } boolean angleIs90(Point other) { return x * other.x + y * other.y == 0; } } public static void main(String[] args) { new taskD().main(); } Scanner in = new Scanner(System.in); ArrayList<Point> points = new ArrayList<Point>(); ArrayList<Integer> res = new ArrayList<Integer>(), perm = new ArrayList<Integer>(); boolean[] used = new boolean[8]; int usedc = 0; void input() { for (int i = 0; i < 8; i++) { points.add(new Point(in.nextInt(), in.nextInt())); used[i] = false; } } boolean isSquare(Point A, Point B, Point C, Point D) { Point AB = new Point(A.x - B.x, A.y - B.y), BC = new Point(B.x - C.x, B.y - C.y), CD = new Point(C.x - D.x, C.y - D.y), DA = new Point(D.x - A.x, D.y - A.y); return AB.len2() == BC.len2() && BC.len2() == CD.len2() && CD.len2() == DA.len2() && AB.angleIs90(BC) && BC.angleIs90(CD) && CD.angleIs90(DA); } boolean isRect(Point A, Point B, Point C, Point D) { Point AB = new Point(A.x - B.x, A.y - B.y), BC = new Point(B.x - C.x, B.y - C.y), CD = new Point(C.x - D.x, C.y - D.y), DA = new Point(D.x - A.x, D.y - A.y); return AB.len2() == CD.len2() && BC.len2() == DA.len2() && AB.angleIs90(BC) && BC.angleIs90(CD) && CD.angleIs90(DA); } void check() { if (res.size() > 0) { return; } if (isSquare(points.get(perm.get(0)), points.get(perm.get(1)), points.get(perm.get(2)), points.get(perm.get(3))) && isRect(points.get(perm.get(4)), points.get(perm.get(5)), points.get(perm.get(6)), points.get(perm.get(7)))) { for (int x : perm) { res.add(x); } } } void solve() { if (usedc == 8) { check(); } else { for (int i = 0; i < 8; i++) { if (!used[i]) { used[i] = true; usedc++; perm.add(i); solve(); perm.remove(perm.size() - 1); usedc--; used[i] = false; } } } } void output() { if (res.size() > 0) { System.out.println("YES"); for (int i = 0; i < 8; i++) { System.out.print(res.get(i) + 1); System.out.print(i % 4 == 3 ? '\n' : ' '); } } else { System.out.println("NO"); } } void main() { input(); solve(); output(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
2da27dde83a0d66e4982852c7de67af9
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Saransh */ import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { /** * @param args the command line arguments */ static int arr[][] = new int[8][2]; public static void main(String[] args) { // TODO code application logic here try { Parserdoubt pd = new Parserdoubt(System.in); PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < arr.length; i++) { arr[i][0] = pd.nextInt(); arr[i][1] = pd.nextInt(); } for (int i = 0; i < (1 << 8); i++) { //System.out.println(i); if (Integer.bitCount(i) == 4) { boolean k = check(i); if(k) { System.out.println("YES"); int tmpi=i; for(int j=1;j<=8;j++) { if(i%2==1) System.out.print(j+" "); i/=2; } System.out.println(); for(int j=1;j<=8;j++) { if(tmpi%2==0) System.out.print(j+" "); tmpi/=2; } return; } } } System.out.println("NO"); } catch (Exception e) { e.printStackTrace(); } } static int arr2[][]; public static boolean check(int a) { int arr1[][]=new int[4][2]; arr2=new int[4][2]; int c1=0; int c2=0; for(int i=0;i<8;i++) { if(a%2==0) { arr1[c1][0]=arr[i][0]; arr1[c1][1]=arr[i][1]; c1++; } else { arr2[c2][0]=arr[i][0]; arr2[c2][1]=arr[i][1]; c2++; }a/=2; } if(isRectangle(arr1[0][0],arr1[0][1],arr1[1][0],arr1[1][1],arr1[2][0],arr1[2][1],arr1[3][0],arr1[3][1])) { if(isRectangle(arr2[0][0],arr2[0][1],arr2[1][0],arr2[1][1],arr2[2][0],arr2[2][1],arr2[3][0],arr2[3][1])) { if(check(0,2,3,1)||check(0,1,2,3)||check(0,1,3,2)) { return true; } } } return false; } public static boolean check(int a,int b,int c,int d) { if(eq(a,b,a,c)&&eq(a,b,c,d)) return true; return false; } public static boolean eq(int a,int b,int c,int d) { if(Math.abs(dist(a,b)-dist(c,d))<1e-8) return true; return false; } public static double dist(int a,int b) { double x=arr2[a][0]-arr2[b][0]; double y=arr2[a][1]-arr2[b][1]; return Math.sqrt(x*x+y*y); } public static boolean isRectangle(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double cx, cy; double dd1, dd2, dd3, dd4; cx = (x1 + x2 + x3 + x4) / 4; cy = (y1 + y2 + y3 + y4) / 4; dd1 = sqr(cx - x1) + sqr(cy - y1); dd2 = sqr(cx - x2) + sqr(cy - y2); dd3 = sqr(cx - x3) + sqr(cy - y3); dd4 = sqr(cx - x4) + sqr(cy - y4); return dd1 == dd2 && dd1 == dd3 && dd1 == dd4; } public static double sqr(double a) { return a*a; } } class Parserdoubt { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb = new StringBuffer(""); byte c = read(); while (c <= ' ') { c = read(); } do { sb.append((char) c); c = read(); } while (c > ' '); return sb.toString(); } public char nextChar() throws Exception { byte c = read(); while (c <= ' ') { c = read(); } return (char) c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) { return -ret; } return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) { return -ret; } return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws Exception { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
b25f4af13fe49b555b23ef082506ed8a
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class ProblemD { public static int[][] points; public static int INVALID = -1000000; public static int isrect(int[] a) { int ax = points[a[0]][0]; int ay = points[a[0]][1]; int maxdist = 0; int maxbidx = 0; for (int bidx = 1; bidx < 4 ; bidx++) { int bx = points[a[bidx]][0]; int by = points[a[bidx]][1]; int dist = (ax-bx)*(ax-bx)+(ay-by)*(ay-by); if (maxdist < dist) { maxdist = dist; maxbidx = bidx; } } if (maxbidx == 0) { return -1; } int bidx = maxbidx; int bx = points[a[bidx]][0]; int by = points[a[bidx]][1]; int cx = INVALID, cy = INVALID; int dx = INVALID, dy = INVALID; for (int b = 1 ; b < 4 ; b++) { if (b == bidx) { continue; } if (cx == INVALID) { cx = points[a[b]][0]; cy = points[a[b]][1]; continue; } if (dx == INVALID) { dx = points[a[b]][0]; dy = points[a[b]][1]; continue; } } int acx = cx - ax; int acy = cy - ay; int adx = dx - ax; int ady = dy - ay; int bcx = cx - bx; int bcy = cy - by; int bdx = dx - bx; int bdy = dy - by; if ((acx * ady - adx * acy) != 0) { if (acx * adx + acy * ady == 0) { if (bcx * bdx + bcy * bdy == 0) { int acac = acx*acx + acy*acy; int adad = adx*adx + ady*ady; int bcbc = bcx*bcx + bcy*bcy; int bdbd = bdx*bdx + bdy*bdy; int min = acac; int max = acac; min = Math.min(min, adad); min = Math.min(min, bcbc); min = Math.min(min, bdbd); max = Math.max(max, adad); max = Math.max(max, bcbc); max = Math.max(max, bdbd); if (min == max) { return 2; } return 1; } } } return -1; } public static boolean printarray(int[] a) { for (int i = 0 ; i < a.length - 1 ; i++) { System.out.print((a[i] + 1) + " "); } System.out.print(a[a.length-1] + 1); System.out.println(); return false; } public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); points = new int[8][2]; for (int i = 0 ; i < 8 ; i++) { String[] info = s.readLine().split(" "); points[i][0] = Integer.valueOf(info[0]); points[i][1] = Integer.valueOf(info[1]); } // System.out.println(isrect(new int[]{4,5,6,7})); for (int i = 0 ; i < (1<<8) ; i++) { if (Integer.bitCount(i) == 4) { int[] a = new int[4]; int[] b = new int[4]; int aidx = 0; int bidx = 0; for (int j = 0 ; j < 8 ; j++) { if ((i & (1 << j)) >= 1) { a[aidx++] = j; } else { b[bidx++] = j; } } if (isrect(a) >= 2 && isrect(b) >= 1) { System.out.println("YES"); printarray(a); printarray(b); return; } } } System.out.println("NO"); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
aa499bf45195e85a82a898acbf6211ce
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class D { class Point { int idx; long x, y; Point(int idx, long x, long y) { this.idx = idx; this.x = x; this.y = y; } } int ccw(Point A, Point B, Point C) { long dx1 = B.x - A.x, dy1 = B.y - A.y; long dx2 = C.x - A.x, dy2 = C.y - A.y; return Long.signum(dx1 * dy2 - dx2 * dy1); } Point[] sort(Point[] a) { int imin = 0; for (int i = 0; i < 4; ++i) { if (a[i].y < a[imin].y || (a[i].y == a[imin].y && a[i].x < a[imin].x)) { imin = i; } } final Point O = new Point(a[imin].idx, a[imin].x, a[imin].y); Arrays.sort(a, new Comparator<Point>() { @Override public int compare(Point A, Point B) { int c = ccw(O, A, B); if (c != 0) { return -c; } return Long.signum(sqr(A.x - O.x) + sqr(A.y - O.y) - sqr(B.x - O.x) - sqr(B.y - O.y)); } }); return a; } boolean isPerpendicular(Point A, Point B, Point C) { long x1 = A.x - B.x, y1 = A.y - B.y; long x2 = C.x - B.x, y2 = C.y - B.y; return x1 * x2 + y1 * y2 == 0; } long sqr(long x) { return x * x; } boolean isRectangle(Point[] a) { a = sort(a); for (int i = 0; i < 4; ++i) { if (!isPerpendicular(a[i], a[(i + 1) % 4], a[(i + 2) % 4])) { return false; } } return true; } boolean isSquare(Point[] a) { a = sort(a); if (!isRectangle(a)) { return false; } long side = sqr(a[0].x - a[1].x) + sqr(a[0].y - a[1].y); for (int i = 0; i < 4; ++i) { long now = sqr(a[i].x - a[(i + 1) % 4].x) + sqr(a[i].y - a[(i + 1) % 4].y); if (now != side) { return false; } } return true; } public void run() { Scanner scanner = new Scanner(System.in); Point[] a = new Point[8]; long x, y; for (int i = 0; i < 8; ++i) { x = scanner.nextLong(); y = scanner.nextLong(); a[i] = new Point(i + 1, x, y); } boolean found = false; for (int state = 0; state < (1 << 8); ++state) { if (Integer.bitCount(state) == 4) { Point[] square = new Point[4]; Point[] rectangle = new Point[4]; int ns = 0, nr = 0; for (int i = 0; i < 8; ++i) { if (((state >> i) & 1) == 1) { square[ns++] = new Point(a[i].idx, a[i].x, a[i].y); } else { rectangle[nr++] = new Point(a[i].idx, a[i].x, a[i].y); } } if (isSquare(square) && isRectangle(rectangle)) { found = true; System.out.println("YES"); for (int i = 0; i < 4; ++i) { System.out.print(square[i].idx + " "); } System.out.println(); for (int i = 0; i < 4; ++i) { System.out.print(rectangle[i].idx + " "); } System.out.println(); break; } } } if (!found) { System.out.println("NO"); } scanner.close(); } public static void main(String[] args) { new D().run(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
b9af9d8493826a97f98ad55fc3375f48
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //Scanner in = new Scanner(new FileReader("Input.txt")); PrintWriter out = new PrintWriter(System.out); int n = 8; Point[] points = new Point[8]; for (int i = 0; i< n; ++i) { points[i] = new Point(i + 1, in.nextInt(), in.nextInt()); } boolean possible = false; for (int mask = (1 << 7); mask < (1 << 8); ++mask) { if (Integer.bitCount(mask) == 4) { ArrayList<Point> firstSet = new ArrayList<Point>(); ArrayList<Point> secondSet = new ArrayList<Point>(); for (int i = 0; i < n; ++i) { if ((mask & (1 << i)) == 0) secondSet.add(points[i]); else firstSet.add(points[i]); } int first = 0, second = 0; for (int w = 0; w < 4; ++w) { for (int x = 0; x < 4; ++x) { if (x == w) continue; for (int y = 0; y < 4; ++y) { if (y == w || y == x) continue; for (int z = 0; z < 4; ++z) { if (z == w || z == y || z == x) continue; Point midPointDiagonal1 = new Point(-1, firstSet.get(w).x + firstSet.get(y).x, firstSet.get(w).y + firstSet.get(y).y); Point midPointDiagonal2 = new Point(-1, firstSet.get(x).x + firstSet.get(z).x, firstSet.get(x).y + firstSet.get(z).y); if (midPointDiagonal1.x == midPointDiagonal2.x && midPointDiagonal1.y == midPointDiagonal2.y) { if (firstSet.get(w).distance(firstSet.get(y)) == firstSet.get(x).distance(firstSet.get(z)) && firstSet.get(w).distance(firstSet.get(y)) != 0) { first = 1; long distance1 = firstSet.get(w).distance(firstSet.get(x)); long distance2 = firstSet.get(x).distance(firstSet.get(y)); long distance3 = firstSet.get(y).distance(firstSet.get(z)); long distance4 = firstSet.get(z).distance(firstSet.get(w)); if (distance1 == distance2 && distance2 == distance3 && distance3 == distance4 && distance4 == distance1 && distance1 != 0) { first = 2; } } } } } } } for (int w = 0; w < 4; ++w) { for (int x = 0; x < 4; ++x) { if (x == w) continue; for (int y = 0; y < 4; ++y) { if (y == w || y == x) continue; for (int z = 0; z < 4; ++z) { if (z == w || z == y || z == x) continue; Point midPointDiagonal1 = new Point(-1, secondSet.get(w).x + secondSet.get(y).x, secondSet.get(w).y + secondSet.get(y).y); Point midPointDiagonal2 = new Point(-1, secondSet.get(x).x + secondSet.get(z).x, secondSet.get(x).y + secondSet.get(z).y); if (midPointDiagonal1.x == midPointDiagonal2.x && midPointDiagonal1.y == midPointDiagonal2.y) { if (secondSet.get(w).distance(secondSet.get(y)) == secondSet.get(x).distance(secondSet.get(z)) && secondSet.get(w).distance(secondSet.get(y)) != 0) { second = 1; long distance1 = secondSet.get(w).distance(secondSet.get(x)); long distance2 = secondSet.get(x).distance(secondSet.get(y)); long distance3 = secondSet.get(y).distance(secondSet.get(z)); long distance4 = secondSet.get(z).distance(secondSet.get(w)); if (distance1 == distance2 && distance2 == distance3 && distance3 == distance4 && distance4 == distance1 && distance1 != 0) { second = 2; } } } } } } } if ((first == 1 && second == 2) || (first == 2 && second == 1) || (first == 2 && second == 2)) { out.println("YES"); int square = (first == 2) ? 1 : 2; int rectangle = (square == 1) ? 2 : 1; if (square == 1) printPointList(firstSet, out); else printPointList(secondSet, out); if (rectangle == 1) printPointList(firstSet, out); else printPointList(secondSet, out); possible = true; break; } } } if (!possible) out.println("NO"); in.close(); out.close(); } public static void printPointList(ArrayList<Point> points, PrintWriter out) { for (int i = 0; i < points.size(); ++i) { out.print(points.get(i).id); if (i != points.size() - 1) out.print(" "); } out.println(); } public static class Point { int id, x, y; public Point(int id, int x, int y) { this.id = id; this.x = x; this.y = y; } public long distance(Point another) { int dx = this.x - another.x; int dy = this.y - another.y; return (long) (dx * dx + dy * dy); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
2b2d3d34938a4a55bce7114ee4496cde
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Scanner; public class D { static int[] x,y; static int sol; static boolean found; public static void find(int rem,int mask) { if(found) return; if(rem==0) { long[] sqx=new long[4]; long[] sqy=new long[4]; long[] recx=new long[4]; long[] recy=new long[4]; int idxsq=0,idxrec=0; for(int i=0;i<8;i++) { if(((1<<i)|mask)==mask){ sqx[idxsq]=x[i]; sqy[idxsq++]=y[i]; }else { recx[idxrec]=x[i]; recy[idxrec++]=y[i]; } } boolean sq=false,rec=false; for(int i=1;i<4;i++) { long hyp=(sqx[i]-sqx[0])*(sqx[i]-sqx[0])+(sqy[i]-sqy[0])*(sqy[i]-sqy[0]); long len1,len2,len3,len4; if(i==1){ len1=(sqx[2]-sqx[0])*(sqx[2]-sqx[0])+(sqy[2]-sqy[0])*(sqy[2]-sqy[0]); len2=(sqx[2]-sqx[1])*(sqx[2]-sqx[1])+(sqy[2]-sqy[1])*(sqy[2]-sqy[1]); len3=(sqx[3]-sqx[0])*(sqx[3]-sqx[0])+(sqy[3]-sqy[0])*(sqy[3]-sqy[0]); len4=(sqx[3]-sqx[1])*(sqx[3]-sqx[1])+(sqy[3]-sqy[1])*(sqy[3]-sqy[1]); if(len1+len2==hyp&&len3+len4==hyp){ if(len1==len2&&len2==len3&&len3==len4) sq=true; break; } }else if(i==2){ len1=(sqx[1]-sqx[0])*(sqx[1]-sqx[0])+(sqy[1]-sqy[0])*(sqy[1]-sqy[0]); len2=(sqx[1]-sqx[2])*(sqx[1]-sqx[2])+(sqy[1]-sqy[2])*(sqy[1]-sqy[2]); len3=(sqx[3]-sqx[0])*(sqx[3]-sqx[0])+(sqy[3]-sqy[0])*(sqy[3]-sqy[0]); len4=(sqx[3]-sqx[2])*(sqx[3]-sqx[2])+(sqy[3]-sqy[2])*(sqy[3]-sqy[2]); if(len1+len2==hyp&&len3+len4==hyp){ if(len1==len2&&len2==len3&&len3==len4) sq=true; break; } }else{ len1=(sqx[1]-sqx[0])*(sqx[1]-sqx[0])+(sqy[1]-sqy[0])*(sqy[1]-sqy[0]); len2=(sqx[1]-sqx[3])*(sqx[1]-sqx[3])+(sqy[1]-sqy[3])*(sqy[1]-sqy[3]); len3=(sqx[2]-sqx[0])*(sqx[2]-sqx[0])+(sqy[2]-sqy[0])*(sqy[2]-sqy[0]); len4=(sqx[2]-sqx[3])*(sqx[2]-sqx[3])+(sqy[2]-sqy[3])*(sqy[2]-sqy[3]); if(len1+len2==hyp&&len3+len4==hyp){ if(len1==len2&&len2==len3&&len3==len4) sq=true; break; } } } for(int i=1;i<4;i++) { long hyp=(recx[i]-recx[0])*(recx[i]-recx[0])+(recy[i]-recy[0])*(recy[i]-recy[0]); long len1,len2,len3,len4; if(i==1){ len1=(recx[2]-recx[0])*(recx[2]-recx[0])+(recy[2]-recy[0])*(recy[2]-recy[0]); len2=(recx[2]-recx[1])*(recx[2]-recx[1])+(recy[2]-recy[1])*(recy[2]-recy[1]); len3=(recx[3]-recx[0])*(recx[3]-recx[0])+(recy[3]-recy[0])*(recy[3]-recy[0]); len4=(recx[3]-recx[1])*(recx[3]-recx[1])+(recy[3]-recy[1])*(recy[3]-recy[1]); if(len1+len2==hyp&&len3+len4==hyp){ rec=true; break; } }else if(i==2){ len1=(recx[1]-recx[0])*(recx[1]-recx[0])+(recy[1]-recy[0])*(recy[1]-recy[0]); len2=(recx[1]-recx[2])*(recx[1]-recx[2])+(recy[1]-recy[2])*(recy[1]-recy[2]); len3=(recx[3]-recx[0])*(recx[3]-recx[0])+(recy[3]-recy[0])*(recy[3]-recy[0]); len4=(recx[3]-recx[2])*(recx[3]-recx[2])+(recy[3]-recy[2])*(recy[3]-recy[2]); if(len1+len2==hyp&&len3+len4==hyp){ rec=true; break; } }else{ len1=(recx[1]-recx[0])*(recx[1]-recx[0])+(recy[1]-recy[0])*(recy[1]-recy[0]); len2=(recx[1]-recx[3])*(recx[1]-recx[3])+(recy[1]-recy[3])*(recy[1]-recy[3]); len3=(recx[2]-recx[0])*(recx[2]-recx[0])+(recy[2]-recy[0])*(recy[2]-recy[0]); len4=(recx[2]-recx[3])*(recx[2]-recx[3])+(recy[2]-recy[3])*(recy[2]-recy[3]); if(len1+len2==hyp&&len3+len4==hyp){ rec=true; break; } } } if(sq&&rec) { found=true; sol=mask; } } else { for(int i=0;i<8;i++) { if(((1<<i)|mask)!=mask){ find(rem-1,mask|(1<<i)); } } } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); x=new int[8]; y=new int[8]; for(int i=0;i<8;i++){ x[i]=sc.nextInt(); y[i]=sc.nextInt(); } sol=0; found=false; find(4,0); if(found){ System.out.println("YES"); for(int i=0;i<8;i++) { if(((1<<i)|sol)==sol){ System.out.print((i+1)+" "); } } System.out.println(); for(int i=0;i<8;i++) { if(((1<<i)|sol)!=sol){ System.out.print((i+1)+" "); } } System.out.println(); }else { System.out.println("NO"); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
fb8f7a31c40a04a890e85cad2d944158
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.StringTokenizer; public class Q136D implements Runnable { int[] x = new int[8]; int[] y = new int[8]; private void solve() throws IOException { for (int i = 0; i < 8; i++) { x[i] = nextInt(); y[i] = nextInt(); } for (int i = 15; i < (1 << 8); i++) { BigInteger bits = BigInteger.valueOf(i); if (bits.bitCount() == 4) { int pc = 0; int zc = 0; int[] p = new int[4]; int[] z = new int[4]; for (int s = 0; s < 8; s++) { if (bits.testBit(s)) p[pc++] = s; else z[zc++] = s; } if (isPR(p) && isPR(z)) { int[] res = null; int[] res2 = null; if (isSQ(p)) { res = p; res2 = z; } else if (isSQ(z)) { res = z; res2 = p; } if (res != null) { writer.println("YES"); for (int q = 0; q < 4; q++) { writer.print(res[q] + 1); if (q < 3) writer.print(" "); } writer.println(); for (int q = 0; q < 4; q++) { writer.print(res2[q] + 1); if (q < 3) writer.print(" "); } return; } } } } writer.print("NO"); } private boolean isSQ(int[] p) { return isSQ(p, 1, 2, 3, 4) || isSQ(p, 1, 2, 4, 3) || isSQ(p, 1, 3, 2, 4); } private boolean isSQ(int[] p, int x1, int x2, int x3, int x4) { double d12 = dist(p, x1, x2); double d23 = dist(p, x2, x3); double d34 = dist(p, x3, x4); double d14 = dist(p, x1, x4); if (eq(d12, d23) && eq(d23, d34) && eq(d34, d14) && eq(d14, d12)) { if (eq(dot(p, x2, x1, x3) / (d12 * d23), 0) && eq(dot(p, x3, x2, x4) / (d23 * d34), 0) && eq(dot(p, x4, x3, x1) / (d34 * d14), 0) && eq(dot(p, x1, x4, x2) / (d14 * d12), 0)) { return true; } } return false; } private boolean isPR(int[] p) { return isPR(p, 1, 2, 3, 4) || isPR(p, 1, 2, 4, 3) || isPR(p, 1, 3, 2, 4); } double dist(int[] p, int x1, int x2) { int xx = x[p[x1-1]] - x[p[x2-1]]; int yy = y[p[x1-1]] - y[p[x2-1]]; return Math.sqrt(xx * xx + yy * yy); } private boolean isPR(int[] p, int x1, int x2, int x3, int x4) { double d12 = dist(p, x1, x2); double d23 = dist(p, x2, x3); double d34 = dist(p, x3, x4); double d14 = dist(p, x1, x4); if (eq(d12, d34) && eq(d23, d14)) { if (eq(dot(p, x2, x1, x3) / (d12 * d23), 0) && eq(dot(p, x3, x2, x4) / (d23 * d34), 0) && eq(dot(p, x4, x3, x1) / (d34 * d14), 0) && eq(dot(p, x1, x4, x2) / (d14 * d12), 0)) { return true; } } return false; } private boolean eq(double x1, double x2) { return Math.abs(x1 - x2) < 0.0000001; } //|A||B|Cos(θ) //Compute the dot product AB ⋅ BC int dot(int[] p, int x1, int x2, int x3) { int[] AB = new int[2]; int[] BC = new int[2]; AB[0] = x[p[x2-1]] - x[p[x1-1]]; AB[1] = y[p[x2-1]] - y[p[x1-1]]; BC[0] = x[p[x3-1]] - x[p[x1-1]]; BC[1] = y[p[x3-1]] - y[p[x1-1]]; int dot = AB[0] * BC[0] + AB[1] * BC[1]; return dot; /* * AB[0] = B[0] - A[0]; AB[1] = B[1] - A[1]; AC[0] = C[0] - A[0]; AC[1] = C[1] - A[1]; int cross = AB[0] * AC[1] - AB[1] * AC[0];*/ } public static void main(String[] args) { new Q136D().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new BufferedReader(new InputStreamReader(System.in)) : new BufferedReader(new FileReader(new File("input.txt"))); tokenizer = null; writer = new PrintWriter(System.out); long start = System.currentTimeMillis(); solve(); reader.close(); if (!oj) writer.print("\nTime: " + (System.currentTimeMillis() - start) + "\n"); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } 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 nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
a80ca78eb231e576367b9f165ab66a49
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.util.*; public class Main { boolean eof; public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public static int comp(double a, double b) { double eps = 1e-9; if (Math.abs(a - b) < eps) return 0; else if (a - b > eps) return 1; else return -1; } static class Point implements Comparable<Point> { static Point NULL = new Point(0, 0, 0); int x, y, id; Point(int x, int y, int id) { this.x = x; this.y = y; this.id = id; } public int compareTo(Point p) { if (polarAngle() > p.polarAngle() || polarAngle() == p.polarAngle() && distance(NULL) > p.distance(NULL)) { return 1; } else { return -1; } } public double polarAngle() { double a = Math.atan2(y, x); if (a < 0) { a += 2 * Math.PI; } return a; } public double dotProduct(Point v) { return x * v.x + y * v.y; } public double crossProduct(Point v) { return x * v.y - y * v.x; } public Point vector(Point p) { return new Point(p.x - x, p.y - y, 0); } public double distance(Point p) { return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); } } boolean sq(int[] b) { for (int i = 0; i < 4; ++i) { if (a[b[i]].vector(a[b[(i - 1 + 4) % 4]]).dotProduct( a[b[i]].vector(a[b[(i + 1) % 4]])) != 0 || comp(a[b[i]].distance(a[b[(i + 1) % 4]]), a[b[(i + 1) % 4]].distance(a[b[(i + 2) % 4]])) != 0) { return false; } } return a[b[0]].vector(a[b[1]]).crossProduct(a[b[0]].vector(a[b[3]])) != 0; } boolean rect(int[] b) { for (int i = 0; i < 4; ++i) { if (a[b[i]].vector(a[b[(i - 1 + 4) % 4]]).dotProduct( a[b[i]].vector(a[b[(i + 1) % 4]])) != 0) { return false; } } return a[b[0]].vector(a[b[1]]).crossProduct(a[b[0]].vector(a[b[3]])) != 0; } boolean ok(int[] o) { boolean[] us = new boolean[8]; for (int i = 0; i < 4; ++i) { us[o[i]] = true; } int[] b = new int[4]; int t = 0; for (int i = 0; i < 8; ++i) { if (!us[i]) { b[t++] = i; } } for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { if (j != i) { for (int k = 0; k < 4; ++k) { if (k != i && k != j) { for (int l = 0; l < 4; ++l) { if (i != l && j != l && k != l) { int[] o1 = new int[4]; o1[0] = b[i]; o1[1] = b[j]; o1[2] = b[k]; o1[3] = b[l]; if (sq(o) && rect(o1)) { out.println("YES"); for (int u = 0; u < 4; ++u) { out.print((a[o[u]].id + 1) + " "); } out.println(); for (int u = 0; u < 4; ++u) { out.print((a[o1[u]].id + 1) + " "); } return true; } } } } } } } } return false; } Point[] a; void solve() { a = new Point[8]; int min = 0; for (int i = 0; i < 8; ++i) { a[i] = new Point(nextInt(), nextInt(), i); if (a[i].y < min) { min = a[i].y; } } for (int i = 0; i < 8; ++i) { a[i].y += -min; } for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (j != i) { for (int k = 0; k < 8; ++k) { if (k != i && k != j) { for (int l = 0; l < 8; ++l) { if (i != l && j != l && k != l) { int[] o = new int[4]; o[0] = i; o[1] = j; o[2] = k; o[3] = l; if (ok(o)) { return; } } } } } } } } out.print("NO"); } BufferedReader br; StringTokenizer st; PrintWriter out; void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); //br = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); solve(); br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new Main().run(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
2ba8626130025c682164bdc03bc83049
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class D97 { static boolean test = false; Point[] pts = null; boolean solved = false; private void solve() throws Throwable { pts = new Point[8]; for (int i = 0; i < 8; i++) { pts[i] = new Point(iread(), iread()); } go(new int[8], 0); if(!solved){ System.out.println("NO"); } } private void go(int[] is, int pos) { if(solved){ return; } if(pos == 8){ //test the solution List<Point> squareList = new ArrayList<Point>(); List<Point> rectList = new ArrayList<Point>(); for (int i = 0; i < is.length; i++) { if(is[i] == 1){ squareList.add(pts[i]); } else { rectList.add(pts[i]); } } if(squareList.size() != 4){ return; } if(isSquare(squareList) && isRect(rectList)){ solved = true; //print String s1 = ""; String s2 = ""; for (int i = 0; i < is.length; i++) { if(is[i] == 1){ s1 += (i+1) + ""; if(i < is.length-1){ s1 += " "; } } if(is[i] == 0){ s2 += (i+1) + ""; if(i < is.length-1){ s2 += " "; } } } System.out.println("YES"); System.out.println(s1); System.out.println(s2); return; } } else { is[pos] = 0; go(is, pos+1); is[pos] = 1; go(is, pos+1); is[pos] = 0; } } private boolean isRect(List<Point> rectList) { int zeros = 0; for (int i = 0; i < rectList.size(); i++) { for (int j = i+1; j < rectList.size(); j++) { Point point = rectList.get(i); Point point2 = rectList.get(j); for (int k = 0; k < rectList.size(); k++) { if(k == j || k == i){ continue; } Point base = rectList.get(k); double x1 = point.getX() - base.getX(); double x2 = point2.getX() - base.getX(); double y1 = point.getY() - base.getY(); double y2 = point2.getY() - base.getY(); if(Math.abs(x1*x2 + y1*y2) < 0.0000001){ zeros ++; } } } } return zeros == 4; } private boolean isSquare(List<Point> squareList) { List<Double> d = new ArrayList<Double>(); for (int i = 0; i < squareList.size(); i++) { for (int j = i+1; j < squareList.size(); j++) { d.add(dist(squareList.get(i), squareList.get(j))); } } Collections.sort(d); if(same(d.get(0), d.get(1)) && same(d.get(0), d.get(2))&& same(d.get(0), d.get(3))&& same(d.get(4), d.get(5))){ return true; } return false; } private boolean same(Double double1, Double double2) { if(Math.abs(double1 - double2) <= 0.0000001){ return true; } return false; } private Double dist(Point point, Point point2) { return (point.getX() - point2.getX())*(point.getX() - point2.getX()) + (point.getY() - point2.getY())*(point.getY() - point2.getY()); } public int iread() throws Exception { return Integer.parseInt(wread()); } public double dread() throws Exception { return Double.parseDouble(wread()); } public long lread() throws Exception { return Long.parseLong(wread()); } public String wread() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) throws Throwable { new D97().solve(); out.close(); } public D97() throws Throwable { if (test) { in = new BufferedReader(new FileReader(new File(testDataFile))); } else { new BufferedReader(inp); } } static InputStreamReader inp = new InputStreamReader(System.in); static BufferedReader in = new BufferedReader(inp); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static String testDataFile = "testdata.txt"; BufferedReader reader = null; }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
2fb10f531a6fe55b50ae93dd7cd4fb1d
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class D { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new D().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = 8; int[][] a = new int[n][2]; for(int i = 0; i < n; i++){ a[i][0] = readInt(); a[i][1] = readInt(); } for(int i = 0; i < (1 << n); i++){ ArrayList<Integer> sq = new ArrayList<Integer>(); ArrayList<Integer> rec = new ArrayList<Integer>(); for(int j = 0; j < n; j++){ if((i & (1 << j)) == 0)rec.add(j); else sq.add(j); } double eps = pow(0.1, 9); if(sq.size() != rec.size()) continue; double[][] m = new double[4][4]; for(int j = 0; j < 4; j++) for(int k = j+1; k < 4; k++){ long x1 = a[sq.get(j)][0]; long y1 = a[sq.get(j)][1]; long x2 = a[sq.get(k)][0]; long y2 = a[sq.get(k)][1]; m[j][k] = m[k][j] = distance(x1, y1, x2, y2); } boolean checkSq = true; if(abs(m[0][1] - m[2][3]) < eps && abs(m[0][2] - m[1][3]) < eps && abs(m[0][3] - m[1][2]) < eps){ double min = m[0][1]; for(int j = 2; j < 4; j++){ if(m[0][j] < min) min = m[0][j]; } for(int j = 2; j < 4; j++){ if(abs(m[0][j] - min) < eps) continue; if(abs(m[0][j] - min * sqrt(2)) < eps) continue; checkSq = false; } } else{ checkSq = false; } if(!checkSq) continue; if(i == 15){ int crw = 0; } boolean checkRec = true; for(int j = 0; j < 4; j++){ boolean check1 = false; for(int k = 0; k < 4; k++){ for(int l = 0; l < 4; l++){ if(j == k || j == l || k == l) continue; int x1 = a[rec.get(j)][0]; int x2 = a[rec.get(k)][0]; int x3 = a[rec.get(l)][0]; int y1 = a[rec.get(j)][1]; int y2 = a[rec.get(k)][1]; int y3 = a[rec.get(l)][1]; if(scalar(x1,y1,x2,y2,x1,y1,x3,y3) < eps) check1 = true; } } if(!check1) checkRec = false; } if(checkRec){ out.println("YES"); for(int j = 0; j < 4; j++){ out.print((sq.get(j)+1)+ " "); } out.println(); for(int j = 0; j < 4; j++){ out.print((rec.get(j)+1)+ " "); } return; } } out.println("NO"); } double scalar(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){ return (x1-x2)*(x3-x4) + (y1-y2)*(y3-y4); } int[] zFunction(char[] s){ int[] z = new int[s.length]; z[0] = 0; for (int i=1, l=0, r=0; i<s.length; ++i) { if (i <= r) z[i] = min (r-i+1, z[i-l]); while (i+z[i] < s.length && s[z[i]] == s[i+z[i]]) ++z[i]; if (i+z[i]-1 > r){ l = i; r = i+z[i]-1; } } return z; } int[] prefixFunction(char[] s){ int[] pr = new int[s.length]; for (int i = 1; i< s.length; ++i) { int j = pr[i-1]; while (j > 0 && s[i] != s[j]) j = pr[j-1]; if (s[i] == s[j]) ++j; pr[i] = j; } return pr; } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4a8f984faead2cc59ea8f737657489cf
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; public class D implements Runnable{ public static void main(String[] args) { // TODO Auto-generated method stub new D().run(); } Scanner Reader; PrintWriter Writer; Point[] p = new Point[8]; public class Point{ int x,y; Point(int x, int y){ this.x=x; this.y=y; } } private int getBit(int i, int x){ return (x>>i)&1; } private boolean checkSquare(Point[] p){ if ((p[0].x-p[1].x)*(p[2].x-p[3].x) + (p[0].y-p[1].y)*(p[2].y-p[3].y) == 0){ if (checkRec(p)) return true; } Point tg = p[0]; p[0]=p[2]; p[2]=tg; if ((p[0].x-p[1].x)*(p[2].x-p[3].x) + (p[0].y-p[1].y)*(p[2].y-p[3].y) == 0){ if (checkRec(p)) return true; } tg = p[1]; p[1]=p[2]; p[2]=tg; if ((p[0].x-p[1].x)*(p[2].x-p[3].x) + (p[0].y-p[1].y)*(p[2].y-p[3].y) == 0){ if (checkRec(p)) return true; } return false; } private boolean checkRec(Point[] p){ if ((p[0].x-p[2].x)*(p[1].x-p[2].x) + (p[0].y-p[2].y)*(p[1].y-p[2].y) == 0 && (p[0].x-p[3].x)*(p[1].x-p[3].x) + (p[0].y-p[3].y)*(p[1].y-p[3].y) == 0){ if (p[0].x+p[1].x==p[2].x+p[3].x && p[0].y+p[1].y==p[2].y+p[3].y) return true; } Point tg = p[0]; p[0]=p[2]; p[2]=tg; if ((p[0].x-p[2].x)*(p[1].x-p[2].x) + (p[0].y-p[2].y)*(p[1].y-p[2].y) == 0 && (p[0].x-p[3].x)*(p[1].x-p[3].x) + (p[0].y-p[3].y)*(p[1].y-p[3].y) == 0){ if (p[0].x+p[1].x==p[2].x+p[3].x && p[0].y+p[1].y==p[2].y+p[3].y) return true; } tg = p[1]; p[1]=p[2]; p[2]=tg; if ((p[0].x-p[2].x)*(p[1].x-p[2].x) + (p[0].y-p[2].y)*(p[1].y-p[2].y) == 0 && (p[0].x-p[3].x)*(p[1].x-p[3].x) + (p[0].y-p[3].y)*(p[1].y-p[3].y) == 0){ if (p[0].x+p[1].x==p[2].x+p[3].x && p[0].y+p[1].y==p[2].y+p[3].y) return true; } return false; } public void display(Point[] k){ for (int i=0; i<k.length; i++) Writer.println(k[i].x+" "+k[i].y); } public void solve() throws IOException{ for(int i=0; i<8; i++){ int x=Reader.nextInt(); int y=Reader.nextInt(); p[i] = new Point(x,y); //Writer.println(x+" "+y); } boolean ok=false; for(int i=0; i<(1<<8); i++){ int sum=0; for(int j=0; j<8; j++) sum+= getBit(j,i); if (sum!=4) continue; Point[] Square = new Point[4]; int Sn=-1; for(int j=0; j<8; j++) if (getBit(j,i)==0){ Sn++; Square[Sn]=p[j]; } if (!checkSquare(Square)) continue; Point[] Rec = new Point[4]; int Rn=-1; for(int j=0; j<8; j++) if (getBit(j,i)==1){ Rn++; Rec[Rn]=p[j]; } if (!checkRec(Rec)) continue; Writer.println("YES"); for(int j=0; j<8; j++) if (getBit(j,i)==0){ if (j<7) Writer.print((j+1)+" "); else Writer.println((j+1)); } for(int j=0; j<8; j++) if (getBit(j,i)==1){ if (j<7) Writer.print((j+1)+" "); else Writer.println((j+1)); } ok=true; break; } if (!ok) Writer.println("NO"); } public void run(){ try{ Reader = new Scanner(new InputStreamReader(System.in)); Writer = new PrintWriter(System.out); solve(); Reader.close(); Writer.close(); } catch (Exception e){ System.out.println(e.getMessage()); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
7f879be14a400e424584d247a2dd87b2
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { new Main(); } Scanner sc; PrintWriter pw; public Main() { sc = new Scanner(System.in); pw = new PrintWriter(System.out); solve(); sc.close(); pw.close(); } static class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } Point(Point p, Point q) { this.x = q.x - p.x; this.y = q.y - p.y; } int length() { return (x * x + y * y); } static int dot(Point p, Point q) { return p.x * q.x + p.y * q.y; } @Override public String toString() { // TODO Auto-generated method stub return "(" + x + "; " + y + ")"; } static boolean isRect(Point a, Point b, Point c, Point d) { return dot(a, b) == 0 && dot(b, c) == 0 && dot(c, d) == 0; } static boolean isSquare(Point a, Point b, Point c, Point d) { return isRect(a, b, c, d) && (a.length() == b.length()) && (b.length() == c.length()) && (c.length() == d.length()); } } boolean bruteRect(Point[] p) { boolean result = false; for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (a == b) continue; for (int c = 0; c < 4; c++) { if (b == c) continue; for (int d = 0; d < 4; d++) { if (c == d) continue; result |= Point.isRect(new Point(p[a], p[b]), new Point(p[b], p[c]), new Point(p[c], p[d]), new Point(p[d], p[a])); if (result) return result; } } } } return result; } boolean bruteSquare(Point[] p) { boolean result = false; for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (a == b) continue; for (int c = 0; c < 4; c++) { if (b == c) continue; for (int d = 0; d < 4; d++) { if (c == d) continue; result |= Point.isSquare(new Point(p[a], p[b]), new Point(p[b], p[c]), new Point(p[c], p[d]), new Point(p[d], p[a])); if (result) return result; } } } } return result; } boolean[] subset = new boolean[8]; Point[] rectPoints = new Point[4]; Point[] squarePoints = new Point[4]; final int N = 8; Point[] p = new Point[N]; void rec(int i, int size) { if (size == 4 && i == 8) { int rectCount = 0; int squareCount = 0; for (int j = 0; j < 8; j++) { if (subset[j]) { squarePoints[squareCount++] = p[j]; } else { rectPoints[rectCount++] = p[j]; } } if (bruteRect(rectPoints) && bruteSquare(squarePoints)) { pw.println("YES"); for (int j = 0; j < 8; j++) { if (subset[j]) { pw.print((j + 1) + " "); } } pw.println(); for (int j = 0; j < 8; j++) { if (!subset[j]) { pw.print((j + 1) + " "); } } pw.println(); pw.flush(); pw.close(); System.exit(0); } } if (size > 4 || i == 8) return; subset[i] = false; rec(i + 1, size); subset[i] = true; rec(i + 1, size + 1); } void solve() { for (int i = 0; i < N; i++) { int x = sc.nextInt(); int y = sc.nextInt(); p[i] = new Point(x, y); } rec(0, 0); pw.println("NO"); pw.flush(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
85f6a8bcb784dd741aca1ea34ced953d
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Scanner; public class D136 { public static final int N = 8; public static final double eps = 1e-9; static int[] perm; static boolean[] used; static Point[] points; static class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } public double dist(Point p) { return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); points = new Point[N]; for (int i = 0; i < N; i++) { points[i] = new Point(in.nextInt(), in.nextInt()); } used = new boolean[N]; perm = new int[N]; put(0); System.out.println("NO"); } public static void put(int already) { if (already == N) { if (isSolution()) { System.out.println("YES"); for (int i = 0; i < 4; i++) { System.out.print((perm[i] + 1) + " "); } System.out.println(""); for (int i = 0; i < 4; i++) { System.out.print((perm[i + 4] + 1) + " "); } System.exit(0); } } else { for (int i = 0; i < N; i++) { if (!used[i]) { perm[already] = i; used[i] = true; put(already + 1); used[i] = false; } } } } public static boolean isSolution() { double d1 = points[perm[0]].dist(points[perm[1]]); double d2 = points[perm[1]].dist(points[perm[2]]); double d3 = points[perm[2]].dist(points[perm[3]]); double d4 = points[perm[3]].dist(points[perm[0]]); boolean isSquare = (Math.abs(d1 - d2) < eps && Math.abs(d2 - d3) < eps && Math.abs(d3 - d4) < eps && d1 > 0); boolean ang1 = isRightAngle(getVector(points[perm[0]], points[perm[1]]), getVector(points[perm[0]], points[perm[3]])); boolean ang2 = isRightAngle(getVector(points[perm[1]], points[perm[0]]), getVector(points[perm[1]], points[perm[2]])); boolean ang3 = isRightAngle(getVector(points[perm[2]], points[perm[1]]), getVector(points[perm[2]], points[perm[3]])); boolean ang4 = isRightAngle(getVector(points[perm[3]], points[perm[2]]), getVector(points[perm[3]], points[perm[0]])); isSquare = isSquare && ang1 && ang2 && ang3 && ang4; d1 = points[perm[4]].dist(points[perm[5]]); d2 = points[perm[5]].dist(points[perm[6]]); d3 = points[perm[6]].dist(points[perm[7]]); d4 = points[perm[7]].dist(points[perm[4]]); boolean isRectangle = (Math.abs(d1 - d3) < eps && Math.abs(d2 - d4) < eps && d1 > 0 && d2 > 0); ang1 = isRightAngle(getVector(points[perm[4]], points[perm[5]]), getVector(points[perm[4]], points[perm[7]])); ang2 = isRightAngle(getVector(points[perm[5]], points[perm[4]]), getVector(points[perm[5]], points[perm[6]])); ang3 = isRightAngle(getVector(points[perm[6]], points[perm[5]]), getVector(points[perm[6]], points[perm[7]])); ang4 = isRightAngle(getVector(points[perm[7]], points[perm[6]]), getVector(points[perm[7]], points[perm[4]])); isRectangle = isRectangle && ang1 && ang2 && ang3 && ang4; return isSquare && isRectangle; } public static Point getVector(Point a, Point b) { Point c = new Point(b.x - a.x, b.y - a.y); return c; } public static boolean isRightAngle(Point a, Point b) { Point zero = new Point(0, 0); double p = a.x * b.x + a.y * b.y; double q = zero.dist(a) * zero.dist(b); double angle = Math.acos(p / q); return (Math.abs(angle - Math.PI / 2) < eps); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
9f74094c13784c67c16947e4c9de56d4
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/29/11 * Time: 7:56 PM * To ch ange this template use File | Settings | File Templates. */ public class TaskD { int[] x; int[] y; boolean isValid(int mask) { int[] squarex = new int[4]; int[] squarey = new int[4]; int[] recx = new int[4]; int[] recy = new int[4]; int ia = 0, ib = 0; for (int i = 0; i < 8; i++) { if ((mask & (1 << i)) > 0) { squarex[ia] = x[i]; squarey[ia++] = y[i]; } else { recx[ib] = x[i]; recy[ib++] = y[i]; } } boolean isSquare = true, isRec = true; int[][] xdiff = new int[4][4]; int[][] ydiff = new int[4][4]; int[][] dist = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { xdiff[i][j] = squarex[i] - squarex[j]; ydiff[i][j] = squarey[i] - squarey[j]; dist[i][j] = xdiff[i][j] * xdiff[i][j] + ydiff[i][j] * ydiff[i][j]; } } for (int i = 0; i < 4 && isSquare; i++) { int minDistance = Integer.MAX_VALUE; for (int j = 0; j < 4; j++) { if (j == i) continue; minDistance = Math.min(minDistance, dist[i][j]); } ArrayList<Integer> ix = new ArrayList<Integer>(); for (int j = 0; j < 4; j++) { if (j == i) continue; if (dist[i][j] == minDistance) ix.add(j); } if (ix.size() == 2) { if (ydiff[i][ix.get(0)] * ydiff[i][ix.get(1)] + xdiff[i][ix.get(0)] * xdiff[i][ix.get(1)] == 0) { } else { isSquare = false; } } else { isSquare = false; } } xdiff = new int[4][4]; ydiff = new int[4][4]; dist = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { xdiff[i][j] = recx[i] - recx[j]; ydiff[i][j] = recy[i] - recy[j]; dist[i][j] = xdiff[i][j] * xdiff[i][j] + ydiff[i][j] * ydiff[i][j]; } } for (int i = 0; i < 4 && isRec; i++) { int maxDistance = Integer.MIN_VALUE; for (int j = 0; j < 4; j++) { if (j == i) continue; maxDistance = Math.max(maxDistance, dist[i][j]); } ArrayList<Integer> ix = new ArrayList<Integer>(); for (int j = 0; j < 4; j++) { if (j == i) continue; if (dist[i][j] != maxDistance) ix.add(j); } if (ix.size() == 2) { if (ydiff[i][ix.get(0)] * ydiff[i][ix.get(1)] + xdiff[i][ix.get(0)] * xdiff[i][ix.get(1)] == 0) { } else { isRec = false; } } else { isRec = false; } } return isSquare && isRec; } void run() { x = new int[8]; y = new int[8]; for (int i = 0; i < 8; i++) { x[i] = nextInt(); y[i] = nextInt(); } int mask = -1; for (int i = 0; i < (1 << 8) && mask == -1; i++) { if (Integer.bitCount(i) == 4) { if (isValid(i)) mask = i; } } if (mask > 0) { System.out.println("YES"); List<Integer> squarePoints = new ArrayList<Integer>(); List<Integer> rectanglePoints = new ArrayList<Integer>(); for (int i = 0; i < 8; i++) { if ((mask & (1 << i)) > 0) squarePoints.add(i); else rectanglePoints.add(i); } for (int a : squarePoints) System.out.print(a + 1 + " "); System.out.println(); for (int a : rectanglePoints) System.out.print(a + 1 + " "); System.out.println(); } else { System.out.println("NO"); } } int nextInt() { try { int c = System.in.read(); if (c == -1) return c; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return c; } if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } long nextLong() { try { int c = System.in.read(); if (c == -1) return -1; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return -1; } if (c == '-') return -nextLong(); long res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } String nextLine() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (c == '\r' || c == '\n') c = System.in.read(); do { res.append((char) c); c = System.in.read(); } while (c != '\r' && c != '\n'); return res.toString(); } catch (Exception e) { return null; } } public static void main(String[] args) { new TaskD().run(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
a357d348278a394e1142ef3475ecb4e8
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.io.PrintWriter; import static java.lang.Math.*; import static java.util.Arrays.*; public class D97 { static Scanner in = new Scanner(System.in); static PrintWriter w = new PrintWriter(System.out, true); static int ni() { return in.nextInt(); } static String nl() { return in.nextLine(); } static void pl(int v) { w.println(v); } static void pl(long v) { w.println(v); } static void pl(Object v) { w.println(v); } static int[][] p; public static void main(String[] args) { p = new int[8][]; for(int i = 0; i < 8; i++) p[i] = new int[] {ni(), ni()}; int set = (1 << 4) - 1; int limit = (1 << 8); while (set < limit) { int t1, t2; if (abs(t1=det(set))==1 && abs(t2=det(~set)) == 1 && !(t1==-1 && t2==-1)) { pl("YES"); int ts = (t1 == 1) ? set : ~set; Integer[] s = new Integer[4]; int sc = 0; for (int j = 0; j < 8; j++) { if (((ts>>j)&1)==1) { s[sc] = j; sc++; } } for (Integer i : s) w.print(i+1+" "); w.println(); ts = ~ts; sc = 0; for (int j = 0; j < 8; j++) { if (((ts>>j)&1)==1) { s[sc] = j; sc++; } } for (Integer i : s) w.print(i+1+" "); w.println(); return; } // Gosper's hack: int c = set & -set; int r = set + c; set = (((r^set) >>> 2) / c) | r; } pl("NO"); } static int det(int set) { int[][] ps = new int[4][]; Integer[] s = new Integer[4]; int sc = 0; for (int j = 0; j < 8; j++) { if (((set>>j)&1)==1) { s[sc] = j; ps[sc] = p[j]; sc++; } } sort(s, new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { return p[i][0]-p[j][0]; } }); if (p[s[1]][0]!=p[s[0]][0]) { int d1 = p[s[1]][0] - p[s[0]][0]; int d2 = p[s[1]][1] - p[s[0]][1]; int d3 = p[s[3]][0] - p[s[2]][0]; int d4 = p[s[3]][1] - p[s[2]][1]; int d5 = p[s[3]][0] - p[s[1]][0]; int d6 = p[s[3]][1] - p[s[1]][1]; int d7 = p[s[2]][0] - p[s[0]][0]; int d8 = p[s[2]][1] - p[s[0]][1]; if (d1*d8-d2*d7==0) return 0; if (d1 == d3 && d2 == d4 && d5 == d7 && d6 == d8) { if ((d2==d5&& d1 ==-d6) || (d2==-d5&& d1 ==d6)) return 1; if (d2*d6 == -d1*d5) return -1; } return 0; } else{ if (p[s[0]][1]>p[s[1]][1]) { int t = s[0]; s[0] = s[1]; s[1] = t; } if (p[s[2]][1]>p[s[3]][1]) { int t = s[2]; s[2] = s[3]; s[3] = t; } int d1 = p[s[1]][0] - p[s[0]][0]; int d2 = p[s[1]][1] - p[s[0]][1]; int d3 = p[s[3]][0] - p[s[2]][0]; int d4 = p[s[3]][1] - p[s[2]][1]; int d5 = p[s[3]][0] - p[s[1]][0]; int d6 = p[s[3]][1] - p[s[1]][1]; int d7 = p[s[2]][0] - p[s[0]][0]; int d8 = p[s[2]][1] - p[s[0]][1]; if (d1*d8-d2*d7==0) return 0; if (d1 == d3 && d2 == d4 && d5 == d7 && d6 == d8) { if ((d2==d5&& d1 ==-d6) || (d2==-d5&& d1 ==d6)) return 1; if (d2*d6 == -d1*d5) return -1; } return 0; } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
7f8368c9cace9ec745c43357ba5ef8ad
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; 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); solve(in, out); out.close(); } private static void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int h = in.nextInt(), c = in.nextInt(), temp = in.nextInt(); if (temp <= (h + c) / 2) { out.println(2); continue; } long k = getK(h, c , temp); out.println(k); } } private static long getK(int h, int c, int t) { int a = h - t; int b = 2 * t - c - h; int k = 2 * (a / b) + 1; long val1 = Math.abs(k / 2 * 1l * c + (k + 1) / 2 * 1l * h - t * 1l * k); long val2 = Math.abs((k + 2) / 2 * 1l * c + (k + 3) / 2 * 1l * h - t * 1l * (k + 2)); return val1 * (k + 2) <= val2 * k ? k : k + 2; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
bd2705f467b2071f98da3fa42dbf0b31
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF1359C { public static void main(String[] args) { FastReader input = new FastReader(); int t = input.nextInt(); while (t > 0){ long hot = input.nextLong(); long cold = input.nextLong(); long desired = input.nextLong(); if(hot == desired){ System.out.println(1); } else if((hot + cold) >= 2 * desired){ System.out.println(2); } else{ long x = ((desired - cold) / ((2 * desired) - hot - cold)); long y = x + 1; double lower = ((x * hot) + (x - 1) * cold) / (1.0 * (2 * x - 1)); double upper = ((y * hot) + (y - 1) * cold) / (1.0 * (2 * y - 1)); double d1 = Math.abs(desired * 1L * (2 * x - 1) - (x * (cold + hot) - cold)) / (2 * x - 1.0); double d2 = Math.abs(desired * 1L * (2 * y - 1) - (y * (cold + hot) - cold)) / (2 * y - 1.0); if(d1 <= d2){ System.out.println(2 * x - 1); } else { System.out.println(2 * y - 1); } } t--; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
d0879150a6949770b448a1ce826d17db
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.util.*; import java.io.*; public class C1359 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static StringTokenizer st; public static void main(String[]args)throws IOException { int t = readInt(); loop: while(t--!=0) { int h = readInt(); int c = readInt(); int temp = readInt(); int sum = h+c; if(h==temp) { pr.println(1); continue; } if(sum==temp*2) { pr.println(2); continue; } if((double)sum/2>temp) { pr.println(2); continue; } double close = 0; long times = 0; if(h>temp & (double)sum/2<temp) { long low = 0; long high = (long)1e9; long mid = (low+high)/2; while(low<high-1) { double ans = (h+(double)sum*mid)/(2*mid+1); if(Math.abs(ans-temp)<=0.000000000000001) { pr.println(2*mid+1); continue loop; } if(ans-temp>0.000000000000001) { low = mid; } else { high = mid; } mid = (low+high)/2; } double s1 = (h+(double)sum*low)/((long)2*low+1); double s2 = (h+(double)sum*high)/((long)2*high+1); if(Math.abs(s1-temp)<=Math.abs(s2-temp)+0.000000000000001) { close = Math.abs(s1-temp); times = 2*low+1; } else { close = Math.abs(s2-temp); times = 2*high+1; } if(low>6) for(int i = -5; i<=5; i++) { double an = (h+(double)sum*(low+i))/(2*(low+i)+1); if(Math.abs(an-temp)<=close+0.000000000000001) { close = Math.abs(an-temp); times = 2*(low+i)+1; } } pr.println(times); /* if(Math.abs((double)sum/2-temp)<=close+0.00000000000001) { if(h-temp<=Math.abs((double)sum/2-temp)+0.00000000001) { pr.println(1); } else { pr.println(2); } continue; } else { pr.println(times); continue; } */ } } pr.close(); } static String next () throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } static long readLong () throws IOException { return Long.parseLong(next()); } static int readInt () throws IOException { return Integer.parseInt(next()); } static double readDouble () throws IOException { return Double.parseDouble(next()); } static char readCharacter () throws IOException { return next().charAt(0); } static String readLine () throws IOException { return br.readLine().trim(); } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
f63c0b403cb91cb09f3bd81b5b6b5f7a
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class test2{ public static void main (String [] args) throws IOException { try { Scanner sc=new Scanner(System.in); int test=sc.nextInt(); for(int i=0;i<test;i++) { double h=sc.nextDouble(); double c=sc.nextDouble(); double t=sc.nextDouble(); double ans=0; double temp=(double)((h+c)/2); if(t<=temp){ ans=2; } else { if(t>=h) ans=1; else{ //double j=(double)h; double diff1=0,diff2=0; double x=1; double min=1000000; //while(j>temp) //{ // j=temp+((h-c)/((4*x)-2)); // diff=Math.abs(t-j); // if(diff<min) // min=diff; // else // { // x--; // break; // } // // break; // x++; //} double val=(h-c)/(2*(t-temp)); double near=Math.floor(val); if(near%2==0) { ans=near+1; } else { //diff1=t-temp-((h-c)/(2*near)); //diff1=Math.abs(diff1); //min=diff1; //ans=near; //diff2=t-temp-((h-c)/((2*near)+2)); //diff2=Math.abs(diff2); //if(diff2<min) //{ // ans=near+2; //} //if(diff1==diff2) //ans=near; double middle=((near)*(near+2))/(near+1); if(val>middle) ans=near+2; else ans=near; } //System.out.println(near); //System.out.println(diff1); //System.out.println(diff2); //System.out.println(val); } } System.out.println((int)ans); } } catch (Exception e) { return; } } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
1582b719ee2a88af3d3c6e7dd6045fa8
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static class Pair implements Comparable<Pair>{ int a; int b; public Pair(int x,int y){a=x;b=y;} public Pair(){} public int compareTo(Pair p){ return p.a - a; } } static class cell implements Comparable<cell>{ int a,b; long dis; public cell(int x,int y,long z) {a=x;b=y;dis=z;} public int compareTo(cell c) { return Long.compare(dis,c.dis); } } static class TrieNode{ TrieNode[]child; int w; boolean term; TrieNode(){ child = new TrieNode[26]; } } public static long gcd(long a,long b) { if(a<b) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } static long lcm(long a,long b) { return a*b / gcd(a,b); } //static long ans = 0; static long mod = (long)(1e9+7);///998244353; public static void main(String[] args) throws Exception { new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static long pow(long x,long y){ if(y == 0)return 1; if(y==1)return x; long a = pow(x,y/2); a = (a*a)%mod; if(y%2==0){ return a; } return (a*x)%mod; } static long mxx; static int mxN = (int)(3e5+5); static long[]fact,inv_fact; static long my_inv(long a) { return pow(a,mod-2); } static long bin(int a,int b) { if(a < b || a<0 || b<0)return 0; return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod; } //static ArrayList<ArrayList<Integer>>adj; //static boolean[]vis; //static long[]dis; //static long val; //static void dfs(int sv,int cur) { // if(vis[sv]) { // // dis[sv] = cur; // val = cur-dis[sv]; // return; // } // vis[sv] = true; // dis[sv]=cur; // for(int x:adj.get(sv)) { // // dfs(x,cur+1); // // } //} static int n,m; static long[][]c; static int[]x= {0,0,-1,1}; static int[]y= {-1,1,0,0}; public static void solve() throws Exception { // solve the problem here MyScanner s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); int tc = s.nextInt(); mxx = (long)(1e18+5); // fact=new long[mxN]; // inv_fact = new long[mxN]; // fact[0]=inv_fact[0]=1L; // for(int i=1;i<mxN;i++) { // fact[i] = (i*fact[i-1])%mod; // inv_fact[i] = my_inv(fact[i]); // } while(tc-->0){ double h = s.nextDouble(); double c = s.nextDouble(); double t = s.nextDouble(); if(t <= (h+c)/2) { out.println("2"); continue; } double k = (h-t)/(2*t-h-c); double o1 = Math.floor(k); //out.println(o1); if( (2*o1+3)*Math.abs((o1*(h+c)+h)-t*(2*o1+1)) <= (2*o1+1)*Math.abs(((o1+1)*(h+c)+h)-t*(2*o1+3))) { out.println((int)(2*o1+1)); } else out.println((int)(2*o1+3)); } out.flush(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
34b56660b7ec0b01170dc8d17d4411d6
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class C { // change to name String nameIn = getClass().getSimpleName() + ".in"; String nameOut = null; public static void main(String[] args) throws IOException { new C().run(); // change to name } //don't touch this private void run() throws IOException { File input = null; if(nameIn != null && (input = new File(nameIn)).exists()) { try( FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); ) { load_inputs(br); } } else { try( InputStreamReader fr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(fr); ) { load_inputs(br); } } } //don't touch this PrintWriter select_output() throws FileNotFoundException { if(nameOut != null) { return new PrintWriter(nameOut); } return new PrintWriter(System.out); } private void load_inputs(BufferedReader br) throws IOException { try( PrintWriter pw = select_output(); ) { int T = Integer.valueOf(br.readLine().trim()); while(T-- > 0) { double[] hct = Arrays.stream(br.readLine().trim().split("\\s+")).mapToDouble(v -> Double.valueOf(v)).toArray(); solve(hct[0], hct[1], hct[2], pw); } } } private void solve(final double h, final double c, final double t, final PrintWriter pw) { long res = 0; if(t <= (h + c) / 2) { res = 2; } else { long i0 = (long)Math.ceil((h - c) / (2 * t - h - c)); i0 += (1 - i0 % 2); long dt0 = (long)Math.abs(((i0 + 1) / 2 * h + (i0 - 1) / 2 * c) - i0 * t); long dt1 = (long)Math.abs(((i0 - 1) / 2 * h + (i0 - 3) / 2 * c) - (i0 - 2) * t); if(dt0 * (i0 - 2) < dt1 * i0) { res = i0; } else { res = i0 - 2; } } pw.println(res); pw.flush(); } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
d7ffc555be9eb57dd508c96ee93fdb16
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
// Spaghetti code import java.io.*; import java.math.*; import java.util.*; public class Main { static int mod=(int)(1e9+7); static int mod2=998244353; static PrintWriter pw; static class FastReader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){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 double d() throws IOException {return Double.parseDouble(next()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li)arr[li]=i();} public void scanIntIndexArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i()-1;}} public void printIntArr(int [] arr){ for(int li=0;li<arr.length;++li)pw.print(arr[li]+" ");pw.println();} public void printLongArr(long [] arr){ for(int li=0;li<arr.length;++li)pw.print(arr[li]+" ");pw.println();} public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}} public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; }} public int swapIntegers(int a,int b){return a;} //Call it like this: a=swapIntegers(b,b=a) public int findMax(int [] arr){int res=Integer.MIN_VALUE;for(int num:arr)res=Math.max(res,num);return res;} } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); pw = new PrintWriter(System.out); /* inputCopy 3 30 10 20 41 15 30 18 13 18 outputCopy 2 7 1 */ //Press Ctrl+Win+Alt+L for reformatting indentation int t = fr.i(); for (int ti = 0; ti < t; ++ti) { long h = fr.i(), c = fr.i(), tb = fr.i(); double average=(h+c)/2.0; if(tb<=average){ pw.println(2); continue; } long k = (h - tb) / (2 * tb - h - c); long foo = (2L * k + 3) * Math.abs((2L * k + 1) * tb - k * (h + c) - h); long bar = (2L * k + 1) * Math.abs((2L * k + 3) * tb - (k + 1) * (h + c) - h); pw.println(foo <= bar ? 2 * k + 1 : 2 * k + 3); } pw.flush(); pw.close(); } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
b1043428a24caa3d9abe86cb6bda2b8f
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { long h,c,t; h=input.nextInt(); c=input.nextInt(); t=input.nextInt(); long m=(h+c)/2; if(t<=m) { out.println(2); } else { long x=(t-c)/(2*t-h-c); long y=x+1; if(Math.abs(((h*x)+c*(x-1)-t*(2*x-1))*(2*y-1))<=Math.abs(((h*y)+c*(y-1)-t*(2*y-1))*(2*x-1))) { out.println(2*x-1); } else { out.println(2*y-1); } } } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
18b60c4cff3559a091f337f90052a72d
train_000.jsonl
1590676500
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c &lt; h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.function.Function; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author out_of_the_box */ 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); CMixingWater solver = new CMixingWater(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CMixingWater { public void solve(int testNumber, InputReader in, OutputWriter out) { long h = in.nextLong(); h <<= 1L; long c = in.nextLong(); c <<= 1L; long t = in.nextLong(); t <<= 1L; long a = (h + c) / 2L; if (t <= a) { out.println(2); } else { h >>= 1L; c >>= 1L; t >>= 1L; long finalH = h; long finalC = c; long finalT = t; Fraction ft = new Fraction(finalT, 1L); Function<Long, Boolean> func = some -> ((getTemp(some, finalH, finalC).compareTo(ft)) < 0); long mx = getMax(1, func); long intx = BinarySearch.searchLastZero(0L, mx, func); long othx = BinarySearch.searchFirstOne(0L, mx, func); Fraction val = getTemp(intx, h, c); Fraction vall = getTemp(othx, h, c); if (val.sub(ft).abs().compareTo(vall.sub(ft).abs()) <= 0) { // if (Double.compare(Math.abs(val.sub(ft)), Math.abs(vall.sub(ft))) <= 0) { out.println(2L * intx + 1L); } else { out.println(2L * othx + 1L); } // long num = h-t; // long denom = 2L*t-h-c; // if (num%denom == 0L) { // long x = num/denom; // double temp = getTemp(x, h, c); // MiscUtility.assertion(Double.compare(temp, t) == 0, // String.format("Temp [%f] and t[%d] are not eq.", temp, t)); // out.println(2L*x+1L); // } else { // long x = num/denom; // double val = getTemp(x,h,c); // double vall = getTemp(x+1L,h,c); // double dif = Math.abs(val-t); // double diff = Math.abs(vall-t); // if (dif <= diff) { // out.println(2L*x+1L); // } else { // out.println(2L*x+3L); // } // } } } private Fraction getTemp(long x, long h, long c) { return new Fraction(x * h + h + x * c, 2 * x + 1); } private long getMax(long start, Function<Long, Boolean> func) { long mx = (Long.MAX_VALUE >> 1L); while (!func.apply(start) && start <= mx) { start <<= 1L; } return start; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Fraction implements Comparable<Fraction> { public long num; public long denom; public Fraction(long num, long denom) { if (denom == 0) { throw new RuntimeException("Denominator cannot be 0"); } this.num = num; this.denom = denom; } public Fraction add(Fraction other) { long lcm = MathUtility.lcm(denom, other.denom); long mul = lcm / denom; long omul = lcm / other.denom; long nu = num * mul + other.num * omul; return new Fraction(nu, lcm); } public Fraction sub(Fraction other) { return add(new Fraction(-other.num, other.denom)); } public Fraction abs() { return new Fraction(Math.abs(num), Math.abs(denom)); } public int compareTo(Fraction o) { return Long.compare(this.num * o.denom, this.denom * o.num); } } static class MathUtility { public static long hcf(long a, long b) { if (a == 0L) { return b; } return hcf(b % a, a); } public static long lcm(long a, long b) { if (a > b) return lcm(b, a); long hcf = hcf(a, b); return (b / hcf) * a; } } static class BinarySearch { public static long searchLastZero(long start, long end, Function<Long, Boolean> valueFunc) { long low = start; long high = end - 1L; while (low < high) { long mid = low + (high - low) / 2L; if (valueFunc.apply(mid + 1L)) { high = mid; } else { low = mid + 1L; } } if (!valueFunc.apply(low)) { return low; } else { return start - 1L; } } public static long searchFirstOne(long start, long end, Function<Long, Boolean> valueFunc) { long low = start; long high = end - 1L; while (low < high) { long mid = low + (high - low) / 2L; if (valueFunc.apply(mid)) { high = mid; } else { low = mid + 1L; } } if (valueFunc.apply(low)) { return low; } else { return end; } } } }
Java
["3\n30 10 20\n41 15 30\n18 13 18"]
2 seconds
["2\n7\n1"]
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
Java 8
standard input
[ "binary search", "math" ]
ca157773d06c7d192589218e2aad6431
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c &lt; h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
1,700
For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
standard output
PASSED
6d00ff871ce871e1e01c3a690ac5c6e7
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { public void solve() throws IOException { char[] c = nextToken().toCharArray(); int N = c.length; boolean[] mixed = new boolean[N+1]; for(int i = 2; i <= N; i++){ boolean prime = true; for(int j = 2; j * j <= i; j++) if(i % j == 0) prime = false; if(prime && i * 2 <= N){ for(int j = i; j <= N; j += i) mixed[j] = true; } } int countMixed = 0; for(int i = 0; i < mixed.length; i++) if(mixed[i]) countMixed++; int[] count = new int[26]; for(char cc : c) count[cc - 'a']++; char[] answer = new char[N]; for(int i = 0; i < 26; i++){ if(count[i] >= countMixed){ for(int j = 0; j < N; j++) if(mixed[j + 1]){ answer[j] = (char)('a' + i); count[i]--; } for(int j = 0; j < N; j++) if(!mixed[j+1]){ for(int k = 0; k < 26; k++){ if(count[k] > 0){ answer[j] = (char)('a' + k); count[k]--; break; } } } out.println("YES"); out.println(new String(answer)); return; } } out.println("NO"); } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
e784760b5c13cde307f001a7dc26860f
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.util.*; public class Main { static char ans[]; static boolean used[]; static ArrayList<Integer>primes; public static void fill(char a,int len){ for(int i=2;i<=len;i++){ if(check(i,len))continue; ans[i]=a; used[i]=true; } } static boolean check(int a,int len){ for(int c:primes){ if(c > len/2 && c == a) return true; } return false; } public static void main(String [] args){ Scanner in=new Scanner(System.in); String s=in.next(); int array[]=new int[26]; for(int i=0;i<s.length();i++) array[s.charAt(i)-'a']++; boolean isPrime[]=new boolean[1001]; Arrays.fill(isPrime,true); primes=new ArrayList<Integer>(); for(int i=2;i<=1000;i++){ if(!isPrime[i])continue; primes.add(i); for(int j=i+i;j<=1000;j+=i){ isPrime[j]=false; } } int len=s.length(); ans=new char[len+1]; used=new boolean[len+1]; int t=0; for(int a:primes){ if(a > len)break; if(a > len/2)t++; } t++; for(int i=0;i<26;i++){ if(array[i] >= len-t){ fill((char)(i+97),len); array[i]-=(len-t); break; } if(i==25){ System.out.print("NO"); return; } } int ptr=1; //for(int i=1;i<=len;i++)System.out.println(i+" "+ans[i]); for(int j=0;j<26;j++){ if(array[j]==0)continue; int cnt=array[j]; //System.out.println(cnt+" "+(char)(j+97)); for(int i=1;i<=cnt;i++){ while(ptr <=len && used[ptr])ptr++; used[ptr]=true; ans[ptr]=(char)(j+97); } } StringBuilder sb=new StringBuilder("YES"); sb.append('\n'); for(int i=1;i<=len;i++) sb.append(ans[i]); System.out.print(sb); } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
7930847e26c337438a5d922ef4e89884
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main3 { public static class Node implements Comparable<Node> { char a; int count; public Node(char a, int count) { this.count = count; this.a = a; } @Override public int compareTo(Node o) { // TODO Auto-generated method stub return new Integer(count).compareTo(o.count); } @Override public String toString() { return a+" "+count; } } public static void main(String[] args) throws IOException { File file = new File("in"); BufferedReader in; if (file.exists()) { in = new BufferedReader(new FileReader(file)); } else { in = new BufferedReader(new InputStreamReader(System.in)); } String line, lines[]; char arr[] = in.readLine().toCharArray(); ArrayList<Integer> primes = numerosPrimos(arr.length+1); int p; int l = arr.length; int sum = 1; int r; int ps[] = new int[1001]; ps[1] = 1; for( int i = 0; i < primes.size(); i++ ) { p = primes.get(i); //System.out.println(p+" "+ l/p); if ( l/p == 1) { sum++; ps[sum] = p; } } r = l - sum; //System.out.println(r); //System.out.println(primes.size()); int count[] = new int[30]; for ( int i = 0; i < arr.length; i++ ) { count[arr[i]-'a']++; } Node arrN[] = new Node[26]; int m = 26; for( int i = 'a'; i <= 'z'; i++ ) { arrN[i-'a'] = new Node((char)i, count[i-'a']); } Arrays.sort(arrN); if( arrN[arrN.length-1].count < r) { System.out.println("NO"); } else { int intV; char charV; Queue<Character> list = new LinkedList<Character>(); for( int i = 0; i< arrN.length; i++ ) { intV = arrN[i].count; charV = arrN[i].a; for( int j = 0; j < intV; j++ ) list.add(charV); } int index = 0; char result[] = new char[arr.length]; Arrays.fill(result, 'A'); for( int i = 1; i <= sum; i++ ) { result[ps[i]-1] = list.poll(); } for( int i = 0; i < result.length; i++ ) { if ( result[i] == 'A' ) { result[i] = arrN[arrN.length-1].a; } } System.out.println("YES"); System.out.println(result); } } public static ArrayList<Integer> numerosPrimos(int n) { if (n < 2) return new ArrayList<Integer>(); char[] is_composite = new char[(n - 2 >> 5) + 1]; final int limit_i = n - 2 >> 1, limit_j = 2 * limit_i + 3; ArrayList<Integer> results = new ArrayList<>((int) Math.ceil(1.25506 * n / Math.log(n))); results.add(2); for (int i = 0; i < limit_i; ++i) if ((is_composite[i >> 4] & 1 << (i & 0xF)) == 0) { results.add(2 * i + 3); for (long j = 4L * i * i + 12L * i + 9; j < limit_j; j += 4 * i + 6) is_composite[(int) (j - 3L >> 5)] |= 1 << (j - 3L >> 1 & 0xF); } return results; } public static int[] readInts(String line) { String lines[] = line.split("\\s+"); int[] result = new int[line.length()]; for (int i = 0; i < lines.length; i++) result[i] = Integer.parseInt(lines[i]); return result; } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
69b8ae912db52f00266c47746ee096fb
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.io.*; import java.util.*; public class Pr123A { public static void main(String[] args) throws IOException { new Pr123A().run(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out, true); solve(); out.flush(); } void solve() throws IOException { char[] s = nextToken().toCharArray(); int[] col = new int[s.length + 1]; boolean[] isPrime = new boolean[s.length + 1]; boolean[] vis = new boolean[s.length + 1]; Arrays.fill(isPrime, true); int cnt = 0; for (int i = 1; i < s.length; i++) { int p = i + 1; if (isPrime[p]) { vis[p] = true; for (int j = 2; j <= s.length / p; j++) { isPrime[j * p] = false; if (!vis[p * j]) { cnt++; vis[p * j] = true; } col[p]++; } if (col[p] > 0) { cnt++; } } } Arrays.sort(s); int[] howOft = new int[26]; char[] ans = new char[s.length]; char isn = ans[0]; int isc = 0; boolean flag = false; for (int i = 0; i < s.length; i++) { howOft[(int) (s[i] - 'a')]++; if (howOft[(int) (s[i] - 'a')] >= cnt) { isc = i; flag = true; } } if (!flag) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < s.length; i++) { if (isPrime[i + 1] && col[i + 1] > 0) { ans[i] = s[isc]; howOft[(int) (s[isc] - 'a')]--; } else if (!isPrime[i + 1]) { ans[i] = s[isc]; howOft[(int) (s[isc] - 'a')]--; } } int sch = 0; for (int i = 0; i < 26; i++) { while (howOft[i] > 0) { while (ans[sch] != isn) { sch++; } ans[sch] = (char) (i + 'a'); howOft[i]--; } } for (int i = 0; i < s.length; i++) { out.print(ans[i]); } } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
c36efc55364c95a411f28c8e561c9829
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.io.*; import java.util.*; public class PrimePermutation { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String str = f.readLine(); int n = str.length(); char[] a = new char[n]; for (int i = 0; i < n; i++) a[i] = str.charAt(i); Arrays.sort(a); int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37}; boolean[] b = new boolean[n]; int count = 0; for (int i = 2; i <= n; i++) { int j = 0; while (i%primes[j] != 0 && primes[j]*primes[j] <= i) j++; int p = primes[j]; if (i % p != 0) p = i; if (p <= n/2) { b[i-1] = true; count++; } } int index = 0; int max = 0; int len = 1; for (int i = 1; i < n; i++) if (a[i] == a[i-1]) len++; else { if (len > max) { index = i-1; max = len; } len = 1; } if (len > max) { index = n-1; max = len; } if (max < count) { System.out.println("NO"); return; } System.out.println("YES"); char c = a[index]; for (int i = 0; i < n; i++) if (b[i]) System.out.print(c); else System.out.print(a[(++index)%n]); } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
b99bab001f4c8eb2b83e83307b8896af
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; /** * * * @author pttrung */ public class A { public static int Mod; public static int[] dp; public static int min; public static void main(String[] args) throws FileNotFoundException, IOException { Scanner in = new Scanner(); // PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); PrintWriter out = new PrintWriter(System.out); String line = in.next(); int n = line.length(); HashMap<Character, Integer> m = new HashMap(); for (int i = 0; i < n; i++) { char c = line.charAt(i); if (!m.containsKey(c)) { m.put(c, 0); } m.put(c, m.get(c) + 1); } boolean[] p = new boolean[n + 1]; ArrayList<Integer> list = new ArrayList(); for (int i = 2; i < p.length; i++) { if (!p[i]) { list.add(i); for (int j = i + i; j < p.length; j += i) { p[j] = true; } } } boolean[][] map = new boolean[n][n]; for (int i : list) { for (int j = 1; j <= n / i; j++) { if (j * i <= n) { map[i - 1][j * i - 1] = true; map[j * i - 1][i - 1] = true; } } } int[] check = new int[n]; Arrays.fill(check, -1); ArrayList<Integer> num = new ArrayList(); int comp = 0; for (int i = 0; i < n; i++) { if (check[i] == -1) { int val = dfs(i, comp, map, check); num.add(val); comp++; } } // System.out.println(num); int[] match = new int[comp]; ArrayList<Entry> q1 = new ArrayList(); PriorityQueue<Entry> q2 = new PriorityQueue(); for (char c : m.keySet()) { q1.add(new Entry(c - 'a', m.get(c))); } int index = 0; for (int val : num) { q2.add(new Entry(index++, val)); } boolean found = true; while (!q2.isEmpty() && found) { Entry a = q2.poll(); Entry b = q2.peek(); // System.out.println(a.c + " " + a.num); found = false; for(Entry e : q1){ if(e.num >= a.num){ if(e.num == a.num){ q1.remove(e); found = true; match[a.c] = e.c; break; }else if(b != null && b.num + a.num <= e.num){ found = true; e.num -= a.num; match[a.c] = e.c; break; } } } Collections.sort(q1); } if(!found){ out.println("NO"); }else{ out.println("YES"); for(int i = 0; i < n; i++){ out.print((char)(match[check[i]] + 'a')); } } out.close(); } public static class Entry implements Comparable<Entry> { int c; int num; public Entry(int c, int num) { this.c = c; this.num = num; } @Override public int compareTo(Entry o) { if (num != o.num) { return num - o.num; } return c - o.c; } } public static int dfs(int index, int comp, boolean[][] map, int[] check) { int result = 1; check[index] = comp; for (int i = 0; i < map.length; i++) { if (check[i] == -1 && map[index][i]) { result += dfs(i, comp, map, check); } } return result; } public static int[][] powSquareMatrix(int[][] A, long p) { int[][] unit = new int[A.length][A.length]; for (int i = 0; i < unit.length; i++) { unit[i][i] = 1; } if (p == 0) { return unit; } int[][] val = powSquareMatrix(A, p / 2); if (p % 2 == 0) { return mulMatrix(val, val); } else { return mulMatrix(A, mulMatrix(val, val)); } } public static int[][] mulMatrix(int[][] A, int[][] B) { int[][] result = new int[A.length][B[0].length]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { long temp = 0; for (int k = 0; k < A[0].length; k++) { temp += ((long) A[i][k] * B[k][j] % Mod); temp %= Mod; } temp %= Mod; result[i][j] = (int) temp; } } return result; } static double dist(Point a, Point b) { long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return Math.sqrt(total); } static class Point implements Comparable<Point> { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { if (x != o.x) { return x - o.x; } return y - o.y; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int pow(int a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } int val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } // static Point minus(Point a, Point b) { // return new Point(a.x - b.x, a.y - b.y); // } // // static Point add(Point a, Point b) { // return new Point(a.x + b.x, a.y + b.y); // } // // static double cross(Point a, Point b) { // return a.x * b.y - a.y * b.x; // // // } // // static class Point { // // int x, y; // // Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public String toString() { // return "Point: " + x + " " + y; // } // } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader(new File("A-large-practice.in"))); } 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
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
a23d4726dcfb6fe6f543f0ceffa79a23
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { public static void main(String[] args) throws IOException { Reader.init(System.in); String s = Reader.next(); char ans[] = new char[s.length() + 1], ch = 'a'; int freq[] = new int[26]; int max = 0; boolean isP[] = new boolean[s.length() + 1]; for(int i = 0; i < s.length(); i++){ int x = s.charAt(i) - 97; freq[x]++; if(freq[x] > freq[max]){ max = x; ch = s.charAt(i); } } for(int i = 2; i < s.length(); i++){ if(!isP[i]){ if(i * 2 > s.length()) break; for(int j = i ; j <= s.length(); j += i){ isP[j] = true; } } } for(int i = 2; i <= s.length(); i++) if(isP[i]){ if(freq[max] == 0){ System.out.println("NO"); return; } ans[i] = ch; freq[max]--; } int j = 0; for(int i = 1; i <= s.length(); i++){ if(isP[i]) continue; while(j < 26 && freq[j] == 0) j++; ans[i] = (char)(j+97); freq[j]--; } System.out.println("YES"); for(int i = 1; i < ans.length; i++) System.out.print(ans[i]); } } class Edge implements Comparable<Edge>{ int to; int cost; Edge(int a, int b){ to = a; cost = b; } @Override public int compareTo(Edge t) { return cost - t.cost; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; public static int pars(String x) { int num = 0; int i = 0; if (x.charAt(0) == '-') { i = 1; } for (; i < x.length(); i++) { num = num * 10 + (x.charAt(i) - '0'); } if (x.charAt(0) == '-') { return -num; } return num; } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static void init(FileReader input) { reader = new BufferedReader(input); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return pars(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
c6d7a591c537e14111959ffae2d5bb18
train_000.jsonl
1320333000
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class Main { private static final int MAXN = 1111; private static int[] fa = new int[ MAXN ]; private static int[] cnt = new int[ MAXN ]; private static int[] acnt = new int[ 88 ]; private static int n ; private static String s; private static void init() { for(int i=0;i<n;++i) { fa[i] = i; cnt[i]=1; } Arrays.fill(acnt, 0, 88, 0); } private static int find(int x) { if( fa[x] == x ) return x; return fa[x] = find( fa[x] ); } private static boolean isp(int n) { if(n==1)return false; for(int i=2;i*i<=n;++i) if(n%i == 0) return false; return true; } public static void main(String args[]) { Scanner cin = new Scanner(System.in); s = cin.next(); n = s.length(); init(); for(int i=0;i<n;++i) { char c = s.charAt( i ); ++ acnt[ c-'a' ]; if( isp(i+1)) { for(int j=i+1+i+1; j <= n; j += i + 1) { int f_a = find(i), f_b = find(j-1); if( f_a != f_b) { cnt[f_a] += cnt[f_b]; fa[f_b] = f_a; } } } } char[] cc = s.toCharArray(); boolean ok=true; while( true ) { int j=0; for(int i=0;i<n;++i) { int _ct = cnt[find(i)]; if(_ct > cnt[find(j)]) j = i; } int k=0; for(int i=0;i<26;++i){ if(acnt[i]>acnt[k]) k=i; } if(acnt[k] == 0) break; //System.out.printf("%d %d\n", acnt[k], cnt[find(j)]); if( acnt[k] < cnt[find(j)]) { ok = false; break; } acnt[k] -= cnt[find(j)]; cnt[find(j)] = 0; for(int i=0;i<n;++i) if(find(i) == find(j)) cc[i] = (char)('a'+k); } if(!ok) System.out.println("NO"); else { System.out.println("YES"); for(int i=0;i<n;++i) System.out.print(cc[i]); System.out.println(); } } }
Java
["abc", "abcd", "xxxyxxx"]
1 second
["YES\nabc", "NO", "YES\nxxxxxxy"]
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Java 7
standard input
[ "implementation", "number theory", "strings" ]
64700ca85ef3b7408d7d7ad1132f8f81
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
1,300
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
standard output
PASSED
a6a362eb085926683ccca27ebe1c1ffb
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class apples{ public static void main(String[] args) { Scanner zizo=new Scanner(System.in); int n=zizo.nextInt(); String l="I love that"; String h="I hate that"; String r=""; int i=1; while(i<n) { if(i%2==1) { r+=" "+h; }else r+=" "+l; i+=1; } if(n%2==0) r+=" "+"I love it"; else r+=" "+"I hate it"; System.out.println(r); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
122abddd05e93ab0c6bc235bf6beb5ed
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class imagine { private static Scanner butts; public static void main(String[] args) { butts = new Scanner(System.in); int n = butts.nextInt(); int shiva = 0; for(int i = 1; i < n; i++) { shiva=i; if(i%2==0) { System.out.print(" I love that "); } else { System.out.print("I hate that"); } } shiva++; if(shiva==n) { if(n%2==1) { System.out.print("I hate it"); } if(n%2==0) { System.out.print(" I love it"); } } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
3b5103b2beb9896517421be47e878515
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); Zidan(Integer.parseInt(sc.nextLine())); } public static void Zidan(int x){ String y=""; for (int i=1 ; i <= x-1 ; i++ ){ if (i%2==0){ y=y+"I love that "; } else { y=y+"I hate that "; } } if(x%2==0){ y+="I love it"; } else{ y+="I hate it"; } System.out.print(y); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
3ecea9ef4a539c129c8fd5e91530163d
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class apples { public static void main (String args[]) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); for (int i=1;i<=a;i++) { if (i%2!=0) { if(i==a) System.out.print("I hate it"); else System.out.print("I hate that"); } else { if(i==a) System.out.print("I love it"); else System.out.print("I love that"); } System.out.print(" "); } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
e1c08282e26a2b6e2e4e7d9de7e335db
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class Hulk { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String res = ""; for (int i = 1; i <= n; i++) { if ((i & 1) == 0) res += "I love"; else res += "I hate"; if (i != n) res += " that "; else res += " it"; } System.out.println(res); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
32a8d116652ab5763671c46af51cbb07
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class Hulk { /** * */ public static int feelingNum = 0 ; public static String printMessage = ""; public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int num = myScanner.nextInt(); for (int i = 0 ; i < num ; i++){ if(feelingNum == 0){ printMessage=printMessage+"I hate "; feelingNum = 1; } else { printMessage=printMessage+"I love "; feelingNum = 0; } if (i+1 >= num) printMessage=printMessage+"it"; else printMessage=printMessage+"that "; } System.out.println(printMessage); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
7ae873662aaa6dc24f425f408063fc85
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; /** * * @author abosala7 */ public class Hulk { /** * */ public static int feelingNum = 0 ; public static String printMessage = ""; public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int num = myScanner.nextInt(); for (int i = 0 ; i < num ; i++){ if(feelingNum == 0){ printMessage=printMessage+"I hate "; feelingNum = 1; } else { printMessage=printMessage+"I love "; feelingNum = 0; } if (i+1 >= num) printMessage=printMessage+"it"; else printMessage=printMessage+"that "; } System.out.println(printMessage); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
edb066a29b8dfdd2ba0a4ef1221bc653
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; /** * * @author abosala7 */ public class Hulk { public static void main(String[] args) { int feelingNum = 0 ; String printMessage = ""; Scanner myScanner = new Scanner(System.in); int num = myScanner.nextInt(); for (int i = 0 ; i < num ; i++){ if(feelingNum == 0){ printMessage+="I hate"; feelingNum = 1; } else { printMessage+="I love"; feelingNum = 0; } if (i+1 >= num)printMessage+=" it"; else printMessage+=" that "; } System.out.println(printMessage); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
e6d16d46056898a7701d50b11f015598
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class hulk { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); boolean flag=true; String s=""; for(int i=0;i<n;i++){ if(flag==true){ s="hate"; flag=false; } else{ s="love"; flag=true; } System.out.print("I"+" "+s); if((i+1)<n) System.out.print(" that "); } System.out.print(" it"); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
e886af42ccf8a4173f8d2313d0463c89
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class hulk { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); boolean flag=true; String s=""; if(n==1) System.out.println("I hate it"); else{ for(int i=0;i<n;i++){ if(flag==true){ s="hate"; flag=false; } else{ s="love"; flag=true; } System.out.print("I"+" "+s); if((i+1)<n) System.out.print(" that "); } System.out.print(" it"); } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
22b44ee56f24f737c07d47054ef6801b
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class DrHulk { private static String Lt = "I love that"; private static String Ht = "I hate that"; private static String Li = "I love it"; private static String Hi = "I hate it" ; public static void main(String[] args) { Scanner rd = new Scanner(System.in); String firstLine = rd.nextLine(); int layers = Integer.parseInt(firstLine); String a[] = new String[layers]; int n = a.length; for (int i = 0; i < n; i++) { if(n==1) { a[0]=Hi; }else { if(i<n-1) { if(i%2!=0) { a[i]=Lt; }else { a[i]=Ht; } }else { if((n-1)%2==0){ a[i]=Hi; }else { a[i]=Li; } } } }rd.close(); show(a); } private static void show(String[] a) { String r = ""; for (int i = 0; i < a.length; i++) { r+= a[i]+" "; } System.out.println(r); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
7d2edf0ac453245ccaf17ae0a61aa0bc
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Hulk { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String x = br.readLine(); int y = Integer.parseInt(x); for (int i = 1 ; i<y ; i++ ) { if(i%2 == 1) System.out.print("I hate that "); if ( i%2 == 0) System.out.print("I love that "); } if(y!= 0 ) { if ( y%2 ==1) System.out.println("I hate it "); else System.out.println("I love it "); } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
a253da4c600180f394077ddd7e3d02ce
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Hulk { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String x = br.readLine(); int y = Integer.parseInt(x); for (int i = 1 ; i<y ; i++ ) { if(i%2 == 1) System.out.print("I hate that "); if ( i%2 == 0) System.out.print("I love that "); } if(y!= 0 ) { if ( y%2 ==1) System.out.println("I hate it "); else System.out.println("I love it "); } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
0ecd1aba17d008ddeff9c0c084dbe432
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.Scanner; public class main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); // your code goes here int num=sc.nextInt(); System.out.print("I hate "); for(int i=1;i<num;i++) { System.out.print("that "); if(i%2==1) System.out.print("I love "); else System.out.print("I hate "); } System.out.println("it"); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
05f686773a7230bf7948eba8c3761290
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Hulk{ public static void main(String[] Args){ Scanner sc= new Scanner(System.in); int n= sc.nextInt(); if(n==1) System.out.print("I hate it"); if(n==2) System.out.print("I hate that I love it"); else{ for(int i=1;i<n;i++){ if(i%2==0){ System.out.print("I love that ");} else{ System.out.print("I hate that "); } } if(n%2==0){ System.out.print("I love it");} else{ if(n%2!=0 && n!=1) System.out.print("I hate it");} } } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
cb7bc54deff6e1232406a3f03c1954e5
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Main6{ public static void main (String[]args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(0<=n&&n<=100){ for(int i = 1; i<n+1 ;i++){ if(i%2==1) System.out.print("I hate"); else System.out.print("I love"); if(i==n) System.out.print(" it "); else System.out.print(" that "); }} } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
6671620c928006001aad3a9865d113fc
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Main{ public static void main (String[]args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(0<=n&&n<=100){ for(int i = 1; i<n+1 ;i++){ if(i%2==1) System.out.print("I hate"); else System.out.print("I love"); if(i==n) System.out.print(" it "); else System.out.print(" that "); }} } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
f2da271320415b7611a330cded54bffe
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Main8{ public static void main (String[]args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(0<=n&&n<=100){ for(int i = 1; i<n+1 ;i++){ if(i%2==1) System.out.print("I hate"); else System.out.print("I love"); if(i==n) System.out.print(" it "); else System.out.print(" that "); }} } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
6c42bd14352d4ebad77bec524066cd04
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Hulk { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Scanner kbd = new Scanner(System.in); double num = kbd.nextInt(); double counter = 0; double x; if(num == 1) System.out.print("I hate it"); else { if(num % 2 == 0) { x = num/2; do { counter ++; System.out.print(" I hate that " + bet(counter*2,num)); } while(counter != x); } else { x = (num/2)-0.5; do { counter ++; System.out.print(" I hate that " + bet((counter*2)+1,num)); } while(counter != x); } } } public static String bet(double i, double j) { String value = ""; if(i != j) value = "I love that"; else if(i == j && j % 2 ==0) value = "I love it "; else if(i == j && j % 2 != 0) value = "I love that I hate it"; return value; } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
4d1bcce744603a994a8b5376cd3fef53
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Hulk { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Scanner kbd = new Scanner(System.in); double num = kbd.nextInt(); double counter = 0; double x; if(num == 1) System.out.print("I hate it"); else { if(num % 2 == 0) { x = num/2; do { counter ++; System.out.print(" I hate that " + bet(counter*2,num)); } while(counter != x); } else { x = (num/2)-0.5; do { counter ++; System.out.print(" I hate that " + bet((counter*2)+1,num)); } while(counter != x); } } } public static String bet(double i, double j) { String value = ""; if(i != j) value = "I love that"; else if(i == j && j % 2 ==0) value = "I love it "; else if(i == j && j % 2 != 0) value = "I love that I hate it"; return value; } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
5c69d60fc9bdcbf478b6297e500e983a
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
//705A import java.util.*; public class Hulk { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Scanner kbd = new Scanner(System.in); double num = kbd.nextInt(); double counter = 0; double x; if(num == 1) System.out.print("I hate it"); else { if(num % 2 == 0) { x = num/2; do { counter ++; System.out.print(" I hate that " + bet(counter*2,num)); } while(counter != x); } else { x = (num/2)-0.5; do { counter ++; System.out.print(" I hate that " + bet((counter*2)+1,num)); } while(counter != x); } } } public static String bet(double i, double j) { String value = ""; if(i != j) value = "I love that"; else if(i == j && j % 2 ==0) value = "I love it "; else if(i == j && j % 2 != 0) value = "I love that I hate it"; return value; } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
4b2741af834edc7aa65feb1470da6c83
train_000.jsonl
1470578700
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.
256 megabytes
import java.util.*; public class Hulk { public static void main(String[] args) { String s = ""; Scanner kbd = new Scanner(System.in); int n = kbd.nextInt(); String str1 = "I hate "; String str2 = "I love "; if(n==1) { s+=str1; System.out.print(s); } else { int t = n-1; for(int i=0;i<n;i++) { if(i%2==0) { s+=str1; } else { s+=str2; } if(t>=1) { s+="that "; t--; } } System.out.print(s+" "); } System.out.print("it"); } }
Java
["1", "2", "3"]
1 second
["I hate it", "I hate that I love it", "I hate that I love that I hate it"]
null
Java 8
standard input
[ "implementation" ]
7f2441cfb32d105607e63020bed0e145
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
800
Print Dr.Banner's feeling in one line.
standard output
PASSED
3abd71a3ba5f376a62ada54ca9392f82
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; public class CountTheRectangles { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); List<Segment> horizontal = new ArrayList<>(); List<Segment> vertical = new ArrayList<>(); for (int i = 0; i < n; i++) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); if (x1 == x2) { vertical.add(new Segment(x1, y1, y2)); } else { horizontal.add(new Segment(y1, x1, x2)); } } if (horizontal.size() > vertical.size()) { List<Segment> temp = horizontal; horizontal = vertical; vertical = temp; } vertical.sort((s1, s2) -> { if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else if (s1.v1 != s2.v1) { return s1.v1 - s2.v1; } else { return s1.u - s2.u; } }); horizontal.sort((s1, s2) -> { if (s1.u != s2.u) { return s1.u - s2.u; } else if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else { return s1.v1 - s2.v1; } }); long answer = 0; Queue<Segment> queue = new LinkedList<>(); SegmentTree segmentTree = new SegmentTree(-5000, 5000); for (int i = 0; i < horizontal.size(); i++) { Segment h = horizontal.get(i); //System.out.println("*****h = " + h + "*****"); for (Segment v : vertical) { if (v.v1 <= h.u && h.u <= v.v2 && h.v1 <= v.u && v.u <= h.v2) { queue.add(v); segmentTree.update(v.u, 1); //System.out.println("adding " + v); } } for (int j = i + 1; j < horizontal.size(); j++) { Segment ho = horizontal.get(j); while (!queue.isEmpty() && queue.peek().v2 < ho.u) { //System.out.println("removing " + queue.peek()); segmentTree.update(queue.remove().u, -1); } long amt = segmentTree.query(ho.v1, ho.v2); //System.out.println("h = " + h + ", ho = " + ho + ", amt = " + amt); answer += (amt * (amt - 1)) >> 1L; } while (!queue.isEmpty()) { //System.out.println("removing " + queue.peek()); segmentTree.update(queue.remove().u, -1); } } System.out.println(answer); } static class Segment { final int u; final int v1; final int v2; Segment(int u, int v1, int v2) { this.u = u; this.v1 = Math.min(v1, v2); this.v2 = Math.max(v1, v2); } @Override public String toString() { return "Segment{" + "u=" + u + ", v1=" + v1 + ", v2=" + v2 + '}'; } } static class SegmentTree { final long[] val; final int treeFrom; final int length; public static final long IDENTITY = 0; long combine(long a, long b) { return a + b; } SegmentTree(int treeFrom, int treeTo) { this.treeFrom = treeFrom; int length = treeTo - treeFrom + 1; int l; for (l = 0; (1 << l) < length; l++); val = new long[1 << (l + 1)]; this.length = 1 << l; } void update(int index, long delta) { int node = index - treeFrom + length; val[node] += delta; for (node >>= 1; node > 0; node >>= 1) { val[node] = val[node << 1] + val[(node << 1) + 1]; } } long query(int from, int to) { if (to < from) { return 0; } return query(1, 0, length - 1, from - treeFrom, to - treeFrom); } long query(int node, int segFrom, int segTo, int from, int to) { if(segTo < from || segFrom > to) return IDENTITY; if(segFrom >= from && segTo <= to) { return val[node]; } int mid = (segFrom + segTo) >> 1; return combine( query(node << 1, segFrom, mid, from, to), query((node << 1) + 1, mid + 1, segTo, from, to) ); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
83d082952a5c317e538f2297a6621681
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; public class CountTheRectangles2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); List<Segment> horizontal = new ArrayList<>(); List<Segment> vertical = new ArrayList<>(); for (int i = 0; i < n; i++) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); if (x1 == x2) { vertical.add(new Segment(x1, y1, y2)); } else { horizontal.add(new Segment(y1, x1, x2)); } } if (horizontal.size() > vertical.size()) { List<Segment> temp = horizontal; horizontal = vertical; vertical = temp; } vertical.sort((s1, s2) -> { if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else if (s1.v1 != s2.v1) { return s1.v1 - s2.v1; } else { return s1.u - s2.u; } }); horizontal.sort((s1, s2) -> { if (s1.u != s2.u) { return s1.u - s2.u; } else if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else { return s1.v1 - s2.v1; } }); long answer = 0; Queue<Segment> queue = new LinkedList<>(); SegmentTree segmentTree = new SegmentTree(-5000, 5000); for (int i = 0; i < horizontal.size(); i++) { Segment h = horizontal.get(i); //System.out.println("*****h = " + h + "*****"); for (Segment v : vertical) { if (v.v1 <= h.u && h.u <= v.v2 && h.v1 <= v.u && v.u <= h.v2) { queue.add(v); segmentTree.update(v.u, 1); //System.out.println("adding " + v); } } for (int j = i + 1; j < horizontal.size(); j++) { Segment ho = horizontal.get(j); while (!queue.isEmpty() && queue.peek().v2 < ho.u) { //System.out.println("removing " + queue.peek()); segmentTree.update(queue.remove().u, -1); } long amt = segmentTree.query(ho.v1, ho.v2); //System.out.println("h = " + h + ", ho = " + ho + ", amt = " + amt); answer += (amt * (amt - 1)) >> 1L; } while (!queue.isEmpty()) { //System.out.println("removing " + queue.peek()); segmentTree.update(queue.remove().u, -1); } } System.out.println(answer); } static class Segment { final int u; final int v1; final int v2; Segment(int u, int v1, int v2) { this.u = u; this.v1 = Math.min(v1, v2); this.v2 = Math.max(v1, v2); } @Override public String toString() { return "Segment{" + "u=" + u + ", v1=" + v1 + ", v2=" + v2 + '}'; } } static class SegmentTree { final long[] val; final int treeFrom; final int length; SegmentTree(int treeFrom, int treeTo) { this.treeFrom = treeFrom; int length = treeTo - treeFrom + 1; int l; for (l = 0; (1 << l) < length; l++); val = new long[1 << (l + 1)]; this.length = 1 << l; } void update(int index, long delta) { int node = index - treeFrom + length; val[node] += delta; for (node >>= 1; node > 0; node >>= 1) { val[node] = val[node << 1] + val[(node << 1) + 1]; } } long query(int from, int to) { if (to < from) { return 0; } from += length - treeFrom; to += length - treeFrom + 1; long res = 0; for (; from + (from & -from) <= to; from += from & -from) { res += val[from / (from & -from)]; } for (; to - (to & -to) >= from; to -= to & -to) { res += val[(to - (to & -to)) / (to & -to)]; } return res; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
0bd999c017d6b301b7fb4413fdda048c
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; public class CountTheRectangles3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); List<Segment> horizontal = new ArrayList<>(); List<Segment> vertical = new ArrayList<>(); for (int i = 0; i < n; i++) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); if (x1 == x2) { vertical.add(new Segment(x1, y1, y2)); } else { horizontal.add(new Segment(y1, x1, x2)); } } if (horizontal.size() > vertical.size()) { List<Segment> temp = horizontal; horizontal = vertical; vertical = temp; } vertical.sort((s1, s2) -> { if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else if (s1.v1 != s2.v1) { return s1.v1 - s2.v1; } else { return s1.u - s2.u; } }); horizontal.sort((s1, s2) -> { if (s1.u != s2.u) { return s1.u - s2.u; } else if (s1.v2 != s2.v2) { return s1.v2 - s2.v2; } else { return s1.v1 - s2.v1; } }); long answer = 0; Queue<Segment> queue = new LinkedList<>(); BinaryIndexTree bixTree = new BinaryIndexTree(-5000, 5000); for (int i = 0; i < horizontal.size(); i++) { Segment h = horizontal.get(i); //System.out.println("*****h = " + h + "*****"); for (Segment v : vertical) { if (v.v1 <= h.u && h.u <= v.v2 && h.v1 <= v.u && v.u <= h.v2) { queue.add(v); bixTree.update(v.u, 1); //System.out.println("adding " + v); } } for (int j = i + 1; j < horizontal.size(); j++) { Segment ho = horizontal.get(j); while (!queue.isEmpty() && queue.peek().v2 < ho.u) { //System.out.println("removing " + queue.peek()); bixTree.update(queue.remove().u, -1); } long amt = bixTree.query(ho.v1, ho.v2); //System.out.println("h = " + h + ", ho = " + ho + ", amt = " + amt); answer += (amt * (amt - 1)) >> 1L; } while (!queue.isEmpty()) { //System.out.println("removing " + queue.peek()); bixTree.update(queue.remove().u, -1); } } System.out.println(answer); } static class Segment { final int u; final int v1; final int v2; Segment(int u, int v1, int v2) { this.u = u; this.v1 = Math.min(v1, v2); this.v2 = Math.max(v1, v2); } @Override public String toString() { return "Segment{" + "u=" + u + ", v1=" + v1 + ", v2=" + v2 + '}'; } } static class BinaryIndexTree { final long[] val; final int treeFrom; BinaryIndexTree(int treeFrom, int treeTo) { val = new long[treeTo - treeFrom + 2]; this.treeFrom = treeFrom; } void update(int index, long delta) { for (int i = index + 1 - treeFrom; i < val.length; i += i & -i) { val[i] += delta; } } long query(int to) { long res = 0; for (int i = to + 1 - treeFrom; i > 0; i -= i & -i) { res += val[i]; } return res; } long query(int from, int to) { if (to < from) { return 0; } return query(to) - query(from - 1); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
345ee89010fc23e7d51807a8e564d9bc
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int maxn = 5001; static class Node { int x1, x2, y1, y2; public Node(int x1, int x2, int y1, int y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } } static class BIT { int[] c; int size; public BIT(int size) { c = new int[size + 1]; this.size = size + 1; } public int get(int x) { int sum = 0; for (; x > 0; x -= x & (-x)) { sum += c[x]; } return sum; } public void update(int x, int val) { for (; x < size; x += x & (-x)) { c[x] += val; } } } public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); ArrayList<Node> hlist = new ArrayList<>(); ArrayList<Node> vlist = new ArrayList<>(); int x1, x2, y1, y2; for (int i = 0; i < n; i++) { x1 = input.nextInt() + maxn; y1 = input.nextInt() + maxn; x2 = input.nextInt() + maxn; y2 = input.nextInt() + maxn; if (x1 > x2) { int tmp = x1; x1 = x2; x2 = tmp; } if (y1 > y2) { int tmp = y1; y1 = y2; y2 = tmp; } if (x1 == x2) vlist.add(new Node(x1, x2, y1, y2)); else hlist.add(new Node(x1, x2, y1, y2)); } Collections.sort(hlist, (a, b) -> a.y1 - b.y1); Collections.sort(vlist, (a, b) -> b.y2 - a.y2); long ans = 0; for (int i = 0; i < hlist.size(); i++) { Node x = hlist.get(i); BIT bit = new BIT(2 * maxn); Stack<Node> stk = new Stack<>(); for (int j = 0; j < vlist.size(); j++) { Node y = vlist.get(j); if (y.y1 <= x.y1 && x.x1 <= y.x1 && y.x1 <= x.x2) { bit.update(y.x1, 1); stk.push(y); } } for (int j = i + 1; j < hlist.size(); j++) { Node y = hlist.get(j); while (!stk.empty()) { Node cur = stk.peek(); if (cur.y2 < y.y2) { bit.update(cur.x1, -1); stk.pop(); } else break; } int l = Math.max(x.x1, y.x1); int r = Math.min(x.x2, y.x2); if (l > r) continue; long cnt = bit.get(r) - bit.get(l - 1); ans += cnt * (cnt - 1) / 2; } } System.out.println(ans); } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
28227e6bab08e826b7eb9bd89b964b62
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static int mod = 998244353; static long inf = (long) 1e16; static int[] l, r; static int n, m, id; static long all, ans; static ArrayList<Integer>[] ad; static long[][][] memo; static long[] a; static ArrayList<Integer> h; static boolean vis[]; public static class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n + 1]; } int rsq(int b) // O(log n) { int sum = 0; while (b > 0) { sum += ft[b]; b -= b & -b; } // min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a - 1); } void point_update(int k, int val) // O(log n), update = increment { while (k <= n) { ft[k] += val; k += k & -k; } // min? } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int offset = 5001; n = sc.nextInt(); int v = 0; int h = 0; int[] xs = new int[n]; int[] ys = new int[n]; int[] xe = new int[n]; int[] ye = new int[n]; for (int i = 0; i < n; i++) { xs[i] = sc.nextInt() + offset; ys[i] = sc.nextInt() + offset; xe[i] = sc.nextInt() + offset; ye[i] = sc.nextInt() + offset; if (xs[i] == xe[i]) { int min = Math.min(ys[i], ye[i]); int max = Math.max(ys[i], ye[i]); ys[i] = min; ye[i] = max; v++; } else { int min = Math.min(xs[i], xe[i]); int max = Math.max(xs[i], xe[i]); xs[i] = min; xe[i] = max; h++; } } long ans = 0; tri[] V = new tri[v]; tri[] H = new tri[h]; int iv = 0; int ih = 0; for (int i = 0; i < n; i++) { if (xs[i] == xe[i]) { V[iv++] = new tri(xs[i], ys[i], ye[i]); } else { H[ih++] = new tri(ys[i], xs[i], xe[i]); } } Arrays.sort(V); FenwickTree ft = new FenwickTree(10001); for (int i = 0; i < v; i++) { int interlinked = 0; for (int inter = 0; inter < h; inter++) { if (H[inter].d >= V[i].st && H[inter].d <= V[i].ed && V[i].d >= H[inter].st && V[i].d <= H[inter].ed) { interlinked++; } } tri[] ar = new tri[interlinked]; int id = 0; for (int inter = 0; inter < h; inter++) { if (H[inter].d >= V[i].st && H[inter].d <= V[i].ed && V[i].d >= H[inter].st && V[i].d <= H[inter].ed) { ar[id++] = new tri(H[inter].ed - V[i].d, H[inter].d, 0); ft.point_update(H[inter].d, 1); } } Arrays.sort(ar); id = 0; for (int j = i + 1; j < v; j++) { if (V[i].d == V[j].d) continue; while (id < interlinked && ar[id].d < V[j].d - V[i].d) { ft.point_update(ar[id].st, -1); id++; } long x = ft.rsq(V[j].st, V[j].ed); ans += x * (x - 1) / 2; } while (id < interlinked) { ft.point_update(ar[id].st, -1); id++; } } System.out.println(ans); out.flush(); } static class tri implements Comparable<tri> { int d, st, ed; tri(int d, int s, int e) { this.d = d; st = s; ed = e; } public String toString() { return d + " " + st + " " + ed; } @Override public int compareTo(tri o) { return d - o.d; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
6a791e1030f565aceebec49081c53e85
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); ECountTheRectangles solver = new ECountTheRectangles(); solver.solve(1, in, out); out.close(); } static class ECountTheRectangles { private static final int MAX = 5000; private static final int SIZE = MAX * 2 + 1; ECountTheRectangles.Item[] items; int itemCount = 0; IntSegmentTree tree; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); items = new ECountTheRectangles.Item[2 * n]; itemCount = 0; for (int i = 0; i < n; i++) { int x1 = MAX + in.nextInt(); int y1 = MAX + in.nextInt(); int x2 = MAX + in.nextInt(); int y2 = MAX + in.nextInt(); if (x1 == x2) { int yl = Math.min(y1, y2); int yh = Math.max(y1, y2); items[itemCount++] = new ECountTheRectangles.Item(x1, yl, yh); } else { int xl = Math.min(x1, x2); int xh = Math.max(x1, x2); items[itemCount++] = new ECountTheRectangles.Item(xl, y1, true); items[itemCount++] = new ECountTheRectangles.Item(xh, y1, false); } } Arrays.sort(items, 0, itemCount, Comparator.comparingInt((ECountTheRectangles.Item i) -> i.x).thenComparingInt(i -> { if (!i.isPoint) return 0; return i.start ? -1 : 1; })); long answer = 0; tree = new IntSegmentTree(SIZE, Integer::sum, 0); for (int i = 0; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (!item.isPoint) { answer += count(i); } } out.println(answer); } private long count(int start) { ECountTheRectangles.Item left = items[start]; long result = 0; for (int i = 0; i < start; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (item.y >= left.y && item.y <= left.y2) { if (item.start) tree.update_LAZY(item.y, 1); else tree.update_LAZY(item.y, 0); } } } tree.rebuild(); for (int i = start + 1; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (!item.start && item.y >= left.y && item.y <= left.y2) { if (tree.get(item.y) == 1) tree.update(item.y, 0); } } else { int yl = Math.max(left.y, item.y); int yh = Math.min(left.y2, item.y2); result += nc2(tree.query(yl, yh + 1)); } } return result; } private static long nc2(long n) { return n * (n - 1) / 2; } private static class Item { int x; int y; int y2; boolean isPoint; boolean start; Item(int x, int y1, int y2) { this.x = x; this.y = y1; this.y2 = y2; isPoint = false; } Item(int x, int y, boolean start) { this.x = x; this.y = y; isPoint = true; this.start = start; } public String toString() { return String.format("(%d, %d, %d, %s, %s)", x - MAX, y - MAX, y2 - MAX, isPoint ? "P" : "L", start ? "S" : "E"); } } } static class IntSegmentTree { public int size; public int[] value; protected final IntSegmentTree.Combiner combiner; protected final int identityElement; public IntSegmentTree(int size, IntSegmentTree.Combiner combiner, int identityElement) { this.size = size; value = new int[2 * size]; Arrays.fill(value, identityElement); this.combiner = combiner; this.identityElement = identityElement; } protected int combine(int a, int b) { return combiner.combine(a, b); } public void rebuild() { for (int i = size - 1; i > 0; i--) { value[i] = combine(value[2 * i], value[2 * i + 1]); } } public int get(int i) { return value[size + i]; } public void update(int i, int v) { i += size; value[i] = v; while (i > 1) { i /= 2; value[i] = combine(value[2 * i], value[2 * i + 1]); } } public void update_LAZY(int i, int v) { i += size; value[i] = v; } public int query(int i, int j) { int res_left = identityElement, res_right = identityElement; for (i += size, j += size; i < j; i /= 2, j /= 2) { if ((i & 1) == 1) res_left = combine(res_left, value[i++]); if ((j & 1) == 1) res_right = combine(value[--j], res_right); } return combine(res_left, res_right); } public interface Combiner { int combine(int a, int b); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
04e9a25468d5e67f92e936b31591d7f9
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); ECountTheRectangles solver = new ECountTheRectangles(); solver.solve(1, in, out); out.close(); } static class ECountTheRectangles { private static final int MAX = 5000; private static final int SIZE = MAX * 2 + 1; ECountTheRectangles.Item[] items; int itemCount = 0; IntSumSegmentTree tree; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); items = new ECountTheRectangles.Item[2 * n]; itemCount = 0; for (int i = 0; i < n; i++) { int x1 = MAX + in.nextInt(); int y1 = MAX + in.nextInt(); int x2 = MAX + in.nextInt(); int y2 = MAX + in.nextInt(); if (x1 == x2) { int yl = Math.min(y1, y2); int yh = Math.max(y1, y2); items[itemCount++] = new ECountTheRectangles.Item(x1, yl, yh); } else { int xl = Math.min(x1, x2); int xh = Math.max(x1, x2); items[itemCount++] = new ECountTheRectangles.Item(xl, y1, true); items[itemCount++] = new ECountTheRectangles.Item(xh, y1, false); } } Arrays.sort(items, 0, itemCount, Comparator.comparingInt((ECountTheRectangles.Item i) -> i.x).thenComparingInt(i -> { if (!i.isPoint) return 0; return i.start ? -1 : 1; })); long answer = 0; tree = new IntSumSegmentTree(SIZE); for (int i = 0; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (!item.isPoint) { answer += count(i); } } out.println(answer); } private long count(int start) { ECountTheRectangles.Item left = items[start]; long result = 0; for (int i = 0; i < start; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (item.y >= left.y && item.y <= left.y2) { if (item.start) tree.update_LAZY(item.y, 1); else tree.update_LAZY(item.y, 0); } } } tree.rebuild(); for (int i = start + 1; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (!item.start && item.y >= left.y && item.y <= left.y2) { if (tree.get(item.y) == 1) tree.update(item.y, 0); } } else { int yl = Math.max(left.y, item.y); int yh = Math.min(left.y2, item.y2); result += nc2(tree.query(yl, yh + 1)); } } return result; } private static long nc2(long n) { return n * (n - 1) / 2; } private static class Item { int x; int y; int y2; boolean isPoint; boolean start; Item(int x, int y1, int y2) { this.x = x; this.y = y1; this.y2 = y2; isPoint = false; } Item(int x, int y, boolean start) { this.x = x; this.y = y; isPoint = true; this.start = start; } public String toString() { return String.format("(%d, %d, %d, %s, %s)", x - MAX, y - MAX, y2 - MAX, isPoint ? "P" : "L", start ? "S" : "E"); } } } 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 IntSumSegmentTree { public int size; public int[] value; public IntSumSegmentTree(int size) { this.size = size; value = new int[2 * size]; } public void rebuild() { for (int i = size - 1; i > 0; i--) { value[i] = value[2 * i] + value[2 * i + 1]; } } public int get(int i) { return value[size + i]; } public void update(int i, int v) { i += size; value[i] = v; while (i > 1) { i /= 2; value[i] = value[2 * i] + value[2 * i + 1]; } } public void update_LAZY(int i, int v) { i += size; value[i] = v; } public int query(int i, int j) { int res_left = 0, res_right = 0; for (i += size, j += size; i < j; i /= 2, j /= 2) { if ((i & 1) == 1) { int b = value[i++]; res_left = res_left + b; } if ((j & 1) == 1) { int a = value[--j]; res_right = a + res_right; } } return res_left + res_right; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
a140f93aa6db9a770c86bd1b3d75d8d0
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); ECountTheRectangles solver = new ECountTheRectangles(); solver.solve(1, in, out); out.close(); } static class ECountTheRectangles { private static final int MAX = 5000; private static final int SIZE = MAX * 2 + 1; ECountTheRectangles.Item[] items; int itemCount = 0; IntSegmentTree tree; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); items = new ECountTheRectangles.Item[2 * n]; itemCount = 0; for (int i = 0; i < n; i++) { int x1 = MAX + in.nextInt(); int y1 = MAX + in.nextInt(); int x2 = MAX + in.nextInt(); int y2 = MAX + in.nextInt(); if (x1 == x2) { int yl = Math.min(y1, y2); int yh = Math.max(y1, y2); items[itemCount++] = new ECountTheRectangles.Item(x1, yl, yh); } else { int xl = Math.min(x1, x2); int xh = Math.max(x1, x2); items[itemCount++] = new ECountTheRectangles.Item(xl, y1, true); items[itemCount++] = new ECountTheRectangles.Item(xh, y1, false); } } Arrays.sort(items, 0, itemCount, Comparator.comparingInt((ECountTheRectangles.Item i) -> i.x).thenComparingInt(i -> { if (!i.isPoint) return 0; return i.start ? -1 : 1; })); long answer = 0; tree = new IntSegmentTree(SIZE, Integer::sum, 0); for (int i = 0; i < itemCount; i++) { if (!items[i].isPoint) { answer += count(i); } } out.println(answer); } private long count(int start) { ECountTheRectangles.Item left = items[start]; long result = 0; for (int i = 0; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (!item.start || i < start) if (item.y >= left.y && item.y <= left.y2) { if (item.start) tree.update(item.y, 1); else if (tree.get(item.y) == 1) tree.update(item.y, 0); } } else { if (i > start) { int yl = Math.max(left.y, item.y); int yh = Math.min(left.y2, item.y2); int tot = tree.query(yl, yh + 1); result += nc2(tot); } } } return result; } private static long nc2(long n) { return n * (n - 1) / 2; } private static class Item { int x; int y; int y2; boolean isPoint; boolean start; Item(int x, int y1, int y2) { this.x = x; this.y = y1; this.y2 = y2; isPoint = false; } Item(int x, int y, boolean start) { this.x = x; this.y = y; isPoint = true; this.start = start; } public String toString() { return String.format("(%d, %d, %d, %s, %s)", x - MAX, y - MAX, y2 - MAX, isPoint ? "P" : "L", start ? "S" : "E"); } } } static class IntSegmentTree { public int size; public int[] value; protected final IntSegmentTree.Combiner combiner; protected final int identityElement; public IntSegmentTree(int size, IntSegmentTree.Combiner combiner, int identityElement) { this.size = size; value = new int[2 * size]; Arrays.fill(value, identityElement); this.combiner = combiner; this.identityElement = identityElement; } protected int combine(int a, int b) { return combiner.combine(a, b); } public int get(int i) { return value[size + i]; } public void update(int i, int v) { i += size; value[i] = v; while (i > 1) { i /= 2; value[i] = combine(value[2 * i], value[2 * i + 1]); } } public int query(int i, int j) { int res_left = identityElement, res_right = identityElement; for (i += size, j += size; i < j; i /= 2, j /= 2) { if ((i & 1) == 1) res_left = combine(res_left, value[i++]); if ((j & 1) == 1) res_right = combine(value[--j], res_right); } return combine(res_left, res_right); } public interface Combiner { int combine(int a, int b); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
58501095cdc14bf342ddafda6b868f79
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); ECountTheRectangles solver = new ECountTheRectangles(); solver.solve(1, in, out); out.close(); } static class ECountTheRectangles { private static final int MAX = 5000; private static final int SIZE = MAX * 2 + 1; ECountTheRectangles.Item[] items; int itemCount = 0; IntSumSegmentTree tree; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); items = new ECountTheRectangles.Item[2 * n]; itemCount = 0; for (int i = 0; i < n; i++) { int x1 = MAX + in.nextInt(); int y1 = MAX + in.nextInt(); int x2 = MAX + in.nextInt(); int y2 = MAX + in.nextInt(); if (x1 == x2) { int yl = Math.min(y1, y2); int yh = Math.max(y1, y2); items[itemCount++] = new ECountTheRectangles.Item(x1, yl, yh); } else { int xl = Math.min(x1, x2); int xh = Math.max(x1, x2); items[itemCount++] = new ECountTheRectangles.Item(xl, y1, true); items[itemCount++] = new ECountTheRectangles.Item(xh, y1, false); } } Arrays.sort(items, 0, itemCount, Comparator.comparingInt((ECountTheRectangles.Item i) -> i.x).thenComparingInt(i -> { if (!i.isPoint) return 0; return i.start ? -1 : 1; })); long answer = 0; tree = new IntSumSegmentTree(SIZE); for (int i = 0; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (!item.isPoint) { answer += count(i); } } out.println(answer); } private long count(int start) { ECountTheRectangles.Item left = items[start]; long result = 0; for (int i = 0; i < start; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (item.y >= left.y && item.y <= left.y2) { if (item.start) tree.update_LAZY(item.y, 1); else tree.update_LAZY(item.y, 0); } } } tree.rebuild(); for (int i = start + 1; i < itemCount; i++) { ECountTheRectangles.Item item = items[i]; if (item.isPoint) { if (!item.start && item.y >= left.y && item.y <= left.y2) { if (tree.get(item.y) == 1) tree.update(item.y, 0); } } else { int yl = Math.max(left.y, item.y); int yh = Math.min(left.y2, item.y2); result += nc2(tree.query(yl, yh + 1)); } } return result; } private static long nc2(long n) { return n * (n - 1) / 2; } private static class Item { int x; int y; int y2; boolean isPoint; boolean start; Item(int x, int y1, int y2) { this.x = x; this.y = y1; this.y2 = y2; isPoint = false; } Item(int x, int y, boolean start) { this.x = x; this.y = y; isPoint = true; this.start = start; } public String toString() { return String.format("(%d, %d, %d, %s, %s)", x - MAX, y - MAX, y2 - MAX, isPoint ? "P" : "L", start ? "S" : "E"); } } } 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 IntSumSegmentTree { public int size; public int[] value; protected final int identityElement = 0; public IntSumSegmentTree(int size) { this.size = size; value = new int[2 * size]; } private int combine(int a, int b) { return a + b; } public void rebuild() { for (int i = size - 1; i > 0; i--) { value[i] = combine(value[2 * i], value[2 * i + 1]); } } public int get(int i) { return value[size + i]; } public void update(int i, int v) { i += size; value[i] = v; while (i > 1) { i /= 2; value[i] = combine(value[2 * i], value[2 * i + 1]); } } public void update_LAZY(int i, int v) { i += size; value[i] = v; } public int query(int i, int j) { int res_left = identityElement, res_right = identityElement; for (i += size, j += size; i < j; i /= 2, j /= 2) { if ((i & 1) == 1) res_left = combine(res_left, value[i++]); if ((j & 1) == 1) res_right = combine(value[--j], res_right); } return combine(res_left, res_right); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
1b32f5575716db12dbc35da2449d8059
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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 class TaskE { final int shift = 5001; final int max = shift * 2; int[] tree; void update(int id, int value) { while (id < max) { tree[id] += value; id += (id & (-id)); } } int read(int id) { int res = 0; while (id > 0) { res += tree[id]; id -= (id & (-id)); } return res; } int range(int a, int b) { return read(b) - read(a - 1); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<Horizontal>[] horizonal = new ArrayList[max]; ArrayList<Vertical>[] vertical = new ArrayList[max]; for (int i = 0; i < max; i++) { horizonal[i] = new ArrayList<>(); vertical[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { int x1 = in.nextInt() + shift; int y1 = in.nextInt() + shift; int x2 = in.nextInt() + shift; int y2 = in.nextInt() + shift; if (x1 == x2) { vertical[x1].add(new Vertical(Math.min(y1, y2), Math.max(y1, y2))); } else { horizonal[y1].add(new Horizontal(Math.min(x1, x2), Math.max(x1, x2))); } } long ans = 0; ArrayList<Integer>[] delete = new ArrayList[max]; for (int i = 0; i < max; i++) { delete[i] = new ArrayList<>(); } for (int y = 0; y < max; y++) { for (Horizontal h : horizonal[y]) { tree = new int[max]; int xLeft = h.x1; int xRight = h.x2; for (int x = xLeft; x <= xRight; x++) { for (Vertical v : vertical[x]) { if (v.y1 <= y && y < v.y2) { update(x, +1); delete[v.y2].add(x); } } } for (int y2 = y + 1; y2 < max; y2++) { for (Horizontal h2 : horizonal[y2]) { long cnt = range(h2.x1, h2.x2); ans += ((cnt * (cnt - 1)) >> 1); } for (int x : delete[y2]) update(x, -1); delete[y2].clear(); } } } out.println(ans); return; } class Horizontal { int x1; int x2; Horizontal(int x1, int x2) { this.x1 = x1; this.x2 = x2; } } class Vertical { int y1; int y2; Vertical(int y1, int y2) { this.y1 = y1; this.y2 = y2; } } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
629fd0438abd3908ba4f9c2366541689
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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 class TaskE { final int shift = 5001; final int max = shift * 2; int[] tree; void update(int id, int value) { while (id < max) { tree[id] += value; id += (id & (-id)); } } int read(int id) { int res = 0; while (id > 0) { res += tree[id]; id -= (id & (-id)); } return res; } int range(int a, int b) { return read(b) - read(a - 1); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<Horizontal>[] horizonal = new ArrayList[max]; ArrayList<Vertical>[] vertical = new ArrayList[max]; for (int i = 0; i < max; i++) { horizonal[i] = new ArrayList<>(); vertical[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { int x1 = in.nextInt() + shift; int y1 = in.nextInt() + shift; int x2 = in.nextInt() + shift; int y2 = in.nextInt() + shift; if (x1 == x2) { vertical[x1].add(new Vertical(Math.min(y1, y2), Math.max(y1, y2))); } else { horizonal[y1].add(new Horizontal(Math.min(x1, x2), Math.max(x1, x2))); } } long ans = 0; ArrayList<Integer>[] delete = new ArrayList[max]; for (int i = 0; i < max; i++) { delete[i] = new ArrayList<>(); } tree = new int[max]; for (int y = 0; y < max; y++) { for (Horizontal h : horizonal[y]) { int xLeft = h.x1; int xRight = h.x2; for (int x = xLeft; x <= xRight; x++) { for (Vertical v : vertical[x]) { if (v.y1 <= y && y < v.y2) { update(x, +1); delete[v.y2].add(x); } } } for (int y2 = y + 1; y2 < max; y2++) { for (Horizontal h2 : horizonal[y2]) { long cnt = range(h2.x1, h2.x2); ans += ((cnt * (cnt - 1)) >> 1); } for (int x : delete[y2]) update(x, -1); delete[y2].clear(); } } } out.println(ans); return; } class Horizontal { int x1; int x2; Horizontal(int x1, int x2) { this.x1 = x1; this.x2 = x2; } } class Vertical { int y1; int y2; Vertical(int y1, int y2) { this.y1 = y1; this.y2 = y2; } } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
4bfbf0654f5052476b1db868096bea5d
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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 class TaskE { final int shift = 5001; final int max = shift * 2; int[] tree; void update(int id, int value) { while (id < max) { tree[id] += value; id += (id & (-id)); } } int read(int id) { int res = 0; while (id > 0) { res += tree[id]; id -= (id & (-id)); } return res; } int range(int a, int b) { return read(b) - read(a - 1); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<Horizontal>[] horizonal = new ArrayList[max]; ArrayList<Vertical>[] vertical = new ArrayList[max]; for (int i = 0; i < max; i++) { horizonal[i] = new ArrayList<>(); vertical[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { int x1 = in.nextInt() + shift; int y1 = in.nextInt() + shift; int x2 = in.nextInt() + shift; int y2 = in.nextInt() + shift; if (x1 == x2) { vertical[x1].add(new Vertical(Math.min(y1, y2), Math.max(y1, y2))); } else { horizonal[y1].add(new Horizontal(Math.min(x1, x2), Math.max(x1, x2))); } } long ans = 0; for (int y = 0; y < max; y++) { for (Horizontal h : horizonal[y]) { ArrayList<Integer>[] delete = new ArrayList[max]; for (int i = 0; i < max; i++) { delete[i] = new ArrayList<>(); } tree = new int[max]; int xLeft = h.x1; int xRight = h.x2; for (int x = xLeft; x <= xRight; x++) { for (Vertical v : vertical[x]) { if (v.y1 <= y && y < v.y2) { update(x, +1); delete[v.y2].add(x); } } } for (int y2 = y + 1; y2 < max; y2++) { for (Horizontal h2 : horizonal[y2]) { long cnt = range(h2.x1, h2.x2); ans += ((cnt * (cnt - 1)) >> 1); } for (int x : delete[y2]) update(x, -1); } } } out.println(ans); return; } class Horizontal { int x1; int x2; Horizontal(int x1, int x2) { this.x1 = x1; this.x2 = x2; } } class Vertical { int y1; int y2; Vertical(int y1, int y2) { this.y1 = y1; this.y2 = y2; } } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
556ea3abed58f84c040d6751da0ae41f
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
//package educational.round68; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class E2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[][] hs = new int[n][]; int[][] vs = new int[n][]; int hp = 0, vp = 0; for(int i = 0;i < n;i++){ int x1 = ni(), y1 = ni(), x2 = ni(), y2 = ni(); if(y1 > y2){ int d = y1; y1 = y2; y2 = d; } if(x1 > x2){ int d = x1; x1 = x2; x2 = d; } if(x1 == x2){ vs[vp++] = new int[]{x1, y1, y2, -1}; }else{ hs[hp++] = new int[]{y1, x1, x2}; } } vs = Arrays.copyOf(vs, vp); hs = Arrays.copyOf(hs, hp); Arrays.sort(hs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); Arrays.sort(vs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); for(int i = 0;i < vp;i++)vs[i][3] = i; int[][] vsu = Arrays.copyOf(vs, vs.length); Arrays.sort(vsu, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[2] - b[2]; } }); long ans = 0; for(int i = 0;i < hp;i++){ int[] ft = new int[n+3]; int p = vp-1; for(int j = hp-1;j >= i+1;j--){ while(p >= 0 && vsu[p][2] >= hs[j][0]){ if(vsu[p][1] <= hs[i][0]){ addFenwick(ft, vsu[p][3], 1); } p--; } int L = lowerBound(vs, 0, Math.max(hs[i][1], hs[j][1]))-1; int R = lowerBound(vs, 0, Math.min(hs[i][2], hs[j][2])+1)-1; if(L < R){ int u = sumFenwick(ft, R) - sumFenwick(ft, L); ans += (long)u * (u-1) / 2; } } } out.println(ans); } public static int lowerBound(int[][] a, int ind, int v) { int low = -1, high = a.length; while(high-low > 1){ int h = high+low>>>1; if(a[h][ind] >= v){ high = h; }else{ low = h; } } return high; } public static int sumFenwick(int[] ft, int i) { int sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(int[] ft, int i, int v) { if(v == 0 || i < 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } 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 E2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
ceaaeadbc873e87ae494be6fcf0990a3
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); ArrayList<Line> h = new ArrayList<>(); ArrayList<Line> v = new ArrayList<>(); int n = fs.nextInt(); for(int i = 0; i < n; i++) { int x = fs.nextInt(), y = fs.nextInt(); int x1 = fs.nextInt(), y1 = fs.nextInt(); boolean hori = y == y1; Line add = new Line(hori); if(hori) { add.y = y1; add.x = x; add.x1 = x1; } else { add.x = x; add.y = y; add.y1 = y1; } add.set(); if(hori) h.add(add); else v.add(add); } myBitSet[] a = new myBitSet[h.size()]; for(int i = 0; i < a.length; i++) { a[i] = new myBitSet(v.size()); } for(int i = 0; i < h.size(); i++) { Line me = h.get(i); for(int j = 0; j < v.size(); j++) { Line you = v.get(j); boolean hits = you.y <= me.y && me.y <= you.y1; hits &= me.x <= you.x && you.x <= me.x1; if(hits) { a[i].set(j); } } } long res = 0; for(int i = 0; i < a.length; i++) { for(int j = i+1; j < a.length; j++) { int sz = a[i].andC(a[j]); res += sz * (sz-1)/2; } } out.println(res); out.close(); } class myBitSet { long[] bits; int n, m; myBitSet(int nn) { n = nn; m = nn/60 + (nn % 60 > 0 ? 1 : 0); bits = new long[m]; } void set(int i) { int idx = i/60; int bit = i-idx*60; bits[idx] |= 1L << bit; } int andC(myBitSet b) { int res = 0; for(int i = 0; i < bits.length; i++) { long temp = bits[i] & b.bits[i]; res += Long.bitCount(temp); } return res; } } class Line { boolean hori; int x, x1, y, y1; Line(boolean h) { hori = h; } void set() { if(hori) { int mn = Math.min(x, x1); int mx = Math.max(x, x1); x = mn; x1 = mx; } else { int mn = Math.min(y, y1); int mx = Math.max(y, y1); y = mn; y1 = mx; } } } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
e141c38af309cad7c39331115932435c
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; import java.io.*; public class RectCount { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); BIT b; boolean[] intersects; ArrayList<CLine> vert = new ArrayList<CLine>(5000); ArrayList<CLine> hori = new ArrayList<CLine>(5000); for (int i = 0; i < n; i++) { int x, y, x1, y1; x = nextInt(); y = nextInt(); x1 = nextInt(); y1 = nextInt(); if (y > y1) { int t = y1; y1 = y; y = t; } if (x > x1) { int t = x1; x1 = x; x = t; } if (x == x1) vert.add(new CLine(x, x1, y, y1)); else hori.add(new CLine(x, x1, y, y1)); } hori.sort(null); vert.sort(null); long sum = 0; for (int i = 0; i < hori.size(); i++) { b = new BIT(10001); intersects = new boolean[vert.size()]; for (int j = 0; j < vert.size(); j++) if (checkIntersect(vert.get(j), hori.get(i))) { b.add(vert.get(j).x + 5000, 1); intersects[j] = true; } int k = 0; for (int j = i + 1; j < hori.size(); j++) { while (k < vert.size() && vert.get(k).y1 < hori.get(j).y1) { if(intersects[k]) b.add(vert.get(k).x + 5000, -1); k++; } if (hori.get(j).x < hori.get(i).x1 && hori.get(i).x < hori.get(j).x1) { int t = b.get(Math.max(hori.get(j).x, hori.get(i).x) + 5000, Math.min(hori.get(j).x1, hori.get(i).x1) + 5001); // System.out.println("t " + t); t--; sum += (long) t * (t + 1) / 2; } } // System.out.println(sum); } System.out.println(sum); } public static boolean checkIntersect(CLine v, CLine h) { if (h.x <= v.x && v.x <= h.x1 && v.y <= h.y && h.y <= v.y1) return true; return false; } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class CLine implements Comparable<CLine> { int x, x1, y, y1; public CLine(int x, int x1, int y, int y1) { super(); this.x = x; this.x1 = x1; this.y = y; this.y1 = y1; } @Override public int compareTo(CLine o) { if (y1 != o.y1) return y1 - o.y1; return x - o.x; } } class BIT { int[] BIT; int n; public BIT(int n) { super(); this.n = n + 1; BIT = new int[n + 1]; } public BIT(int[] BIT) { this.BIT = BIT; n = BIT.length; } // [idx] void add(int idx, int val) { idx++; for (; idx < n; idx += (idx & (-idx))) BIT[idx] += val; } // [0,l] int get(int idx) { idx++; int ret = 0; for (; idx > 0; idx -= (idx & (-idx))) ret += BIT[idx]; return ret; } // [l,r) int get(int l, int r) { return (get(r - 1) - get(l - 1)); } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
ece34c2a8362446edb29232c8ca2b1a6
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* */ import java.util.*; import java.io.*; public class x1194E2 { public static void main(String args[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); ArrayList<Segment> hor = new ArrayList<Segment>(); ArrayList<Segment> ver = new ArrayList<Segment>(); for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int ab = Integer.parseInt(st.nextToken()); int ac = Integer.parseInt(st.nextToken()); int ad = Integer.parseInt(st.nextToken()); Segment b = new Segment(a,ab,ac,ad); if(a == ac) ver.add(b); else hor.add(b); } if(ver.size() <= hor.size()) System.out.println(bash(ver, hor)); else System.out.println(bash(hor, ver)); } public static long bash(ArrayList<Segment> ls, ArrayList<Segment> ls2) { int N = ls.size(); int M = ls2.size(); BitSet[] bsets = new BitSet[N]; for(int i=0; i < N; i++) { bsets[i] = new BitSet(M); for(int a=0; a < M; a++) if(cross(ls.get(i), ls2.get(a))) bsets[i].add(a); } long res = 0L; for(int i=0; i < N; i++) for(int a=i+1; a < N; a++) { int bitcnt = bsets[i].and(bsets[a]); res += (long)bitcnt*(bitcnt-1); } return res/2; } public static boolean cross(Segment s1, Segment s2) { if(s1.y1 == s1.y2) return (s2.x1 >= s1.x1) && (s2.x1 <= s1.x2) && (s1.y1 >= s2.y1) && (s1.y2 <= s2.y2); else return (s1.x1 >= s2.x1) && (s1.x1 <= s2.x2) && (s2.y1 >= s1.y1) && (s2.y2 <= s1.y2); } } class Segment { public int x1; public int y1; public int x2; public int y2; public Segment(int a, int b, int c, int d) { x1 = Math.min(a, c); y1 = Math.min(b, d); x2 = Math.max(a, c); y2 = Math.max(b, d); } } class BitSet { public long[] sets; public int size; public BitSet(int N) { size = N; if(N%64 == 0) sets = new long[N/64]; else sets = new long[N/64+1]; } public void add(int i) { int dex = i/64; int thing = i%64; sets[dex] |= (1L << thing); } public int and(BitSet oth) { int boof = Math.min(sets.length, oth.sets.length); int res = 0; for(int i=0; i < boof; i++) res += Long.bitCount(sets[i] & oth.sets[i]); return res; } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
270dfa88e99d57c5d53b0386e196d3f0
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ 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); EPoschitaiteChetirehugolniki solver = new EPoschitaiteChetirehugolniki(); solver.solve(1, in, out); out.close(); } static class EPoschitaiteChetirehugolniki { public void solve(int testNumber, InputReader in, OutputWriter out) { int offset = 5000; int n = in.readInt(); List<Segment> vertical = new ArrayList<>(); List<Segment> horizontal = new ArrayList<>(); for (int i = 0; i < n; i++) { int x0 = in.readInt() + offset; int y0 = in.readInt() + offset; int x1 = in.readInt() + offset; int y1 = in.readInt() + offset; Segment segment = createSegment(x0, x1, y0, y1); if (segment.isVertical()) { vertical.add(segment); } else { horizontal.add(segment); } } horizontal.sort(Comparator.comparingInt(s -> s.minY)); vertical.sort(Comparator.comparingInt(s -> s.maxY)); Fenwick tree = new Fenwick(offset * 2 + 1); long answer = 0; for (int i = 0; i < horizontal.size(); i++, tree.clear()) { Segment h0 = horizontal.get(i); List<Segment> added = new ArrayList<>(); for (Segment s : vertical) { if (s.minY <= h0.minY) { tree.add(s.minX, 1); added.add(s); } } int atAdded = 0; for (int j = i + 1; j < horizontal.size(); j++) { Segment h1 = horizontal.get(j); IntIntPair inter = intersect(h0.minX, h0.maxX, h1.minX, h1.maxX); if (h1.minY == h0.minY || inter.first >= inter.second) { continue; } while (atAdded < added.size() && added.get(atAdded).maxY < h1.minY) { Segment rem = added.get(atAdded++); tree.add(rem.minX, -1); } answer += pairs(tree.get(inter.first, inter.second)); } } out.print(answer); } long pairs(long n) { return n * (n - 1) / 2; } IntIntPair intersect(int a1, int b1, int a2, int b2) { return IntIntPair.makePair(Math.max(a1, a2), Math.min(b1, b2)); } Segment createSegment(int x0, int x1, int y0, int y1) { if (x0 > x1) { return createSegment(x1, x0, y0, y1); } if (y0 > y1) { return createSegment(x0, x1, y1, y0); } return new Segment(x0, y0, x1, y1); } class Segment { int minX; int minY; int maxX; int maxY; Segment(int minX, int minY, int maxX, int maxY) { this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; } boolean isVertical() { return minX == maxX; } } class Fenwick { int[] tree; Fenwick(int n) { tree = new int[n + 1]; } int get(int at) { int s = 0; for (at++; at > 0; at -= at & -at) { s += tree[at]; } return s; } int get(int l, int r) { return get(r) - get(l - 1); } void add(int at, int x) { for (at++; at < tree.length; at += at & -at) { tree[at] += x; } } void clear() { Arrays.fill(tree, 0); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static 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 print(long i) { writer.print(i); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(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; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
7b6d25c848257be2f14c6acd88dea6d7
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int maxn = 5001; static class Node { int x1, x2, y1, y2; public Node(int x1, int x2, int y1, int y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } } static class BIT { int[] c; int size; public BIT(int size) { c = new int[size + 1]; this.size = size + 1; } public int get(int x) { int sum = 0; for (; x > 0; x -= x & (-x)) { sum += c[x]; } return sum; } public void update(int x, int val) { for (; x < size; x += x & (-x)) { c[x] += val; } } } public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); ArrayList<Node> hlist = new ArrayList<>(); ArrayList<Node> vlist = new ArrayList<>(); int x1, x2, y1, y2; for (int i = 0; i < n; i++) { x1 = input.nextInt() + maxn; y1 = input.nextInt() + maxn; x2 = input.nextInt() + maxn; y2 = input.nextInt() + maxn; if (x1 > x2) { int tmp = x1; x1 = x2; x2 = tmp; } if (y1 > y2) { int tmp = y1; y1 = y2; y2 = tmp; } if (x1 == x2) vlist.add(new Node(x1, x2, y1, y2)); else hlist.add(new Node(x1, x2, y1, y2)); } Collections.sort(hlist, (a, b) -> a.y1 - b.y1); Collections.sort(vlist, (a, b) -> b.y2 - a.y2); long ans = 0; for (int i = 0; i < hlist.size(); i++) { Node x = hlist.get(i); BIT bit = new BIT(2 * maxn); Stack<Node> stk = new Stack<>(); for (int j = 0; j < vlist.size(); j++) { Node y = vlist.get(j); if (y.y1 <= x.y1 && x.x1 <= y.x1 && y.x1 <= x.x2) { bit.update(y.x1, 1); stk.push(y); } } for (int j = i + 1; j < hlist.size(); j++) { Node y = hlist.get(j); while (!stk.empty()) { Node cur = stk.peek(); if (cur.y2 < y.y2) { bit.update(cur.x1, -1); stk.pop(); } else break; } int l = Math.max(x.x1, y.x1); int r = Math.min(x.x2, y.x2); if (l > r) continue; long cnt = bit.get(r) - bit.get(l - 1); ans += cnt * (cnt - 1) / 2; } } System.out.println(ans); } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
7e72afb791d3ee81548b13beb69fd9e5
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.util.*; public class Solution { int N = 10002; int maxn = 5001; int [] f; private int sum(int index){ int sum = 0; while(index > 0){ sum += f[index]; index -= (index & (-index)); } return sum; } public void fupdate(int index, int val){ while(index < N){ f[index]+=val; index += (index & (-index)); } } public void solve(){ Scanner input = new Scanner(System.in); int n = input.nextInt(); List<int[]> hlist = new ArrayList<>(); List<int[]> vlist = new ArrayList<>(); int x1, x2, y1, y2; for (int i = 0; i < n; i++) { x1 = input.nextInt() + maxn; y1 = input.nextInt() + maxn; x2 = input.nextInt() + maxn; y2 = input.nextInt() + maxn; if (x1 > x2) { int tmp = x1; x1 = x2; x2 = tmp; } if (y1 > y2) { int tmp = y1; y1 = y2; y2 = tmp; } if (x1 == x2) { vlist.add(new int[]{x1, x2, y1, y2}); }else{ hlist.add(new int[]{x1, x2, y1, y2}); } } Collections.sort(hlist, (a, b) -> a[2] - b[2]); Collections.sort(vlist, (a, b) -> b[3] - a[3]); long ans = 0; for (int i = 0; i < hlist.size(); i++) { int [] x = hlist.get(i); f = new int[N]; Stack<int[]> stk = new Stack<>(); for (int j = 0; j < vlist.size(); j++) { int [] y = vlist.get(j); if (y[2] <= x[2] && x[0] <= y[0] && y[0] <= x[1]) { fupdate(y[0], 1); stk.push(y); } } for (int j = i + 1; j < hlist.size(); j++) { int [] y = hlist.get(j); while (!stk.empty()) { int [] cur = stk.peek(); if (cur[3] < y[3]) { fupdate(cur[0], -1); stk.pop(); }else{ break; } } int l = Math.max(x[0], y[0]); int r = Math.min(x[1], y[1]); if (l > r) continue; long cnt = sum(r) - sum(l - 1); ans += cnt * (cnt - 1) / 2; } } System.out.println(ans); } public static void main(String[] args) { new Solution().solve(); } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
e473a922ce05b8a138c104f6d33e6052
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } int[] A; int maxn=5001; void work() { int n=ni(); ArrayList<int[]> l1=new ArrayList<>(); ArrayList<int[]> l2=new ArrayList<>(); for(int i=0;i<n;i++) { int[] A=nia(4); if(A[0]==A[2]) { l2.add(new int[] {A[0],Math.min(A[1], A[3]),A[2],Math.max(A[1], A[3])}); }else { l1.add(new int[] {Math.min(A[0], A[2]),A[1],Math.max(A[0], A[2]),A[3]}); } } Collections.sort(l1,new Comparator<int[]>() { public int compare(int[] A1,int[] A2) { return A1[1]-A2[1]; } }); Collections.sort(l2,new Comparator<int[]>() { public int compare(int[] A1,int[] A2) { return A2[3]-A1[3];//上端点 } }); long ret=0; for(int i=0;i<l1.size();i++) { A=new int[10003]; for(int j=l1.size()-1,k=0;j>i;j--) { int s=Math.max(l1.get(i)[0], l1.get(j)[0]); int e=Math.min(l1.get(i)[2], l1.get(j)[2]); if(s>=e)continue; while(k<l2.size()&&l2.get(k)[3]>=l1.get(j)[1]) { if(l2.get(k)[1]<=l1.get(i)[1]) { update(l2.get(k)[0],1); } k++; } long v=query(s,e); ret+=v*(v-1)/2; } } out.println(ret); } private long query(int s, int e) { return query(e)-query(s-1); } long query(int x) { long ret=0; for(;x>0;x-=lowbit(x)) { ret+=A[x]; } return ret; } int lowbit(int x){ return x&-x; } private void update(int x, int v) { for(;x<10003;x+=lowbit(x)) { A[x]+=v; } } //input private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt()+maxn; } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } 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
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
11c0e8426676bf20455798c8d06089c4
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(); ArrayList<Q> al = new ArrayList<>(); for(int i = 0; i < n; i++) { int x1 = f.nextInt()+5000; int y1 = f.nextInt()+5000; int x2 = f.nextInt()+5000; int y2 = f.nextInt()+5000; if(y1 == y2) al.add(new Q(x1, x2, y1, i)); else { al.add(new Q(x1, y1, y1 < y2, i)); al.add(new Q(x1, y2, y2 < y1, i)); } } Collections.sort(al); long ans = 0; for(int i = 0; i < al.size(); i++) { if(!al.get(i).q) continue; int l = al.get(i).x1; int r = al.get(i).x2; BIT b = new BIT(10000); HashSet<Integer> hs = new HashSet<>(); for(int j = 0; j < al.size(); j++) { Q q = al.get(j); if(q.q) { if(j <= i) continue; long v = b.get(q.x2) - b.get(q.x1-1); ans += v * (v-1)/2; } else { if(q.x1 < l || q.x1 > r) continue; if(q.add && j < i) { b.add(q.x1, 1); hs.add(q.i); } else if(hs.remove(q.i)) b.add(q.x1, -1); } } } out.println(ans); /// out.flush(); } class BIT { int[] arr; public BIT(int sz) { arr = new int[sz+5]; } public int get(int i) { i++; int res = 0; while(i > 0) { res += arr[i]; i -= i & -i; } return res; } public void add(int i, int v) { i++; while(i < arr.length) { arr[i]+=v; i += i & -i; } } } class Q implements Comparable<Q> { int x1, x2, y, i; boolean q; boolean add; public Q(int x1, int x2, int y, int i) { this.i = i; if(x2 < x1) { x1 ^= x2; x2 ^= x1; x1 ^= x2; } this.x1 = x1; this.x2 = x2; this.y = y; q = true; } public Q(int x, int y, boolean add, int i) { this.i = i; this.x1 = x; this.y = y; this.add = add; } public int compareTo(Q q) { if(y != q.y) return Integer.compare(y, q.y); int a = 1; if(!this.q) { a = 2; if(add) a = 0; } int b = 1; if(!q.q) { b = 2; if(q.add) b = 0; } return Integer.compare(a, b); } } /// static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
97c3b88e7c7094c632eceb3b8b15ea60
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Comparator; import java.util.NoSuchElementException; public class P1194E { private static final int MAX = 10000; public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); ArrayList<int[]> horizontals = new ArrayList<>(n / 2); ArrayList<int[]> verticals = new ArrayList<>(n / 2); for (int i = 0; i < n; ++i) { int x1 = scanner.nextInt() + MAX / 2; int y1 = scanner.nextInt() + MAX / 2; int x2 = scanner.nextInt() + MAX / 2; int y2 = scanner.nextInt() + MAX / 2; if (y1 == y2) horizontals.add(new int[]{y1, Math.min(x1, x2), Math.max(x1, x2)}); else verticals.add(new int[]{x1, Math.min(y1, y2), Math.max(y1, y2)}); } verticals.sort(Comparator.comparingInt(o -> o[0])); horizontals.sort(Comparator.comparingInt(o -> o[2])); long cnt = 0; for (int i = 0; i < verticals.size(); ++i) { int[] left = verticals.get(i); ArrayList<int[]> intersects = new ArrayList<>(horizontals.size()); int[] bit = new int[MAX + 1]; for (int[] horizontal : horizontals) { if (intersect(horizontal, left)) { intersects.add(horizontal); bitUpdate(bit, horizontal[0], 1); } } // intersects.sort(Comparator.comparingInt(o -> o[2])); for (int j = i + 1, k = 0; j < verticals.size(); ++j) { int[] right = verticals.get(j); while (k < intersects.size() && intersects.get(k)[2] < right[0]) { bitUpdate(bit, intersects.get(k)[0], -1); ++k; } if (k == intersects.size()) break; int t = bitQuery(bit, Math.max(left[1], right[1]), Math.min(left[2], right[2])); cnt += t * (t - 1) / 2; } } writer.println(cnt); writer.close(); } private static int bitQuery(int[] bit, int l, int r) { if (l >= r) return 0; return bitQuery(bit, r) - bitQuery(bit, l - 1); } private static int bitQuery(int[] bit, int x) { int cnt = 0; for (; x >= 0; x = (x & (x + 1)) - 1) cnt += bit[x]; return cnt; } private static void bitUpdate(int[] bit, int x, int val) { for (; x <= MAX; x = x | (x + 1)) bit[x] += val; } private static boolean intersect(int[] horizontal, int[] vertical) { return horizontal[0] >= vertical[1] && horizontal[0] <= vertical[2] && vertical[0] >= horizontal[1] && vertical[0] <= horizontal[2]; } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
ab769d4b7b1b70fa6923542bf4b9bed4
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Comparator; import java.util.NoSuchElementException; public class P1194E { private static final int MAX = 10000; public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); ArrayList<int[]> horizontals = new ArrayList<>(n / 2); ArrayList<int[]> verticals = new ArrayList<>(n / 2); for (int i = 0; i < n; ++i) { int x1 = scanner.nextInt() + MAX / 2; int y1 = scanner.nextInt() + MAX / 2; int x2 = scanner.nextInt() + MAX / 2; int y2 = scanner.nextInt() + MAX / 2; if (y1 == y2) horizontals.add(new int[]{y1, Math.min(x1, x2), Math.max(x1, x2)}); else verticals.add(new int[]{x1, Math.min(y1, y2), Math.max(y1, y2)}); } verticals.sort(Comparator.comparingInt(o -> o[0])); long cnt = 0; for (int i = 0; i < verticals.size(); ++i) { int[] left = verticals.get(i); ArrayList<int[]> intersects = new ArrayList<>(horizontals.size()); int[] bit = new int[MAX + 1]; for (int[] horizontal : horizontals) { if (intersect(horizontal, left)) { intersects.add(horizontal); bitUpdate(bit, horizontal[0], 1); } } intersects.sort(Comparator.comparingInt(o -> o[2])); for (int j = i + 1, k = 0; j < verticals.size(); ++j) { int[] right = verticals.get(j); while (k < intersects.size() && intersects.get(k)[2] < right[0]) { bitUpdate(bit, intersects.get(k)[0], -1); ++k; } if (k == intersects.size()) break; int t = bitQuery(bit, Math.max(left[1], right[1]), Math.min(left[2], right[2])); cnt += t * (t - 1) / 2; } } writer.println(cnt); writer.close(); } private static int bitQuery(int[] bit, int l, int r) { if (l >= r) return 0; return bitQuery(bit, r) - bitQuery(bit, l - 1); } private static int bitQuery(int[] bit, int x) { int cnt = 0; for (; x >= 0; x = (x & (x + 1)) - 1) cnt += bit[x]; return cnt; } private static void bitUpdate(int[] bit, int x, int val) { for (; x <= MAX; x = x | (x + 1)) bit[x] += val; } private static boolean intersect(int[] horizontal, int[] vertical) { return horizontal[0] >= vertical[1] && horizontal[0] <= vertical[2] && vertical[0] >= horizontal[1] && vertical[0] <= horizontal[2]; } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
ada439d951594f5df2aedd40e85e3636
train_000.jsonl
1563115500
There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 &lt; h_2$$$ and $$$v_1 &lt; v_2$$$ should hold.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); int[] X1 = new int[n], Y1 = new int[n], X2 = new int[n], Y2 = new int[n]; in.readIntArrays(X1, Y1, X2, Y2); normalize(X1, X2); normalize(Y1, Y2); int nx = ArrayUtils.compress(X1, X2).length; int ny = ArrayUtils.compress(Y1, Y2).length; int[] order = ArrayUtils.order(X1); ArrayUtils.orderBy(ArrayUtils.reversePermutation(order), X1, Y1, X2, Y2); long res = 0; FenwickTree ft = new FenwickTree(ny); IntList[] rem = new IntList[nx]; for (int i = 0; i < n; i++) { if (X1[i] == X2[i]) { Arrays.setAll(rem, j -> new IntArrayList()); for (int j = 0; j < n; j++) { if (Y1[j] == Y2[j] && X1[i] >= X1[j] && X1[i] <= X2[j] && Y1[j] >= Y1[i] && Y1[j] <= Y2[i]) { ft.add(Y1[j], 1); rem[X2[j]].add(Y1[j]); } } int pos = 0; for (int j = i + 1; j < n; j++) { if (X1[j] == X2[j]) { while (pos < X1[j]) { for (int k : rem[pos]) { ft.add(k, -1); } pos++; } long c = ft.get(Y1[j], Y2[j]); res += c * (c - 1) / 2; } } while (pos < nx) { for (int k : rem[pos]) { ft.add(k, -1); } pos++; } } } out.printLine(res); } catch (Exception e) { e.printStackTrace(); } } void normalize(int[] A, int[] B) { for (int i = 0; i < A.length; i++) { if (A[i] > B[i]) { int tmp = A[i]; A[i] = B[i]; B[i] = tmp; } } } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } public int[] toArray() { return Arrays.copyOf(data, size); } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static interface IntComparator { IntComparator DEFAULT = Integer::compare; int compare(int first, int second); } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class ArrayUtils { public static int[] range(int from, int to) { return Range.range(from, to).toArray(); } public static int[] createOrder(int size) { return range(0, size); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } public static int[] order(final int[] array) { return sort(createOrder(array.length), (first, second) -> Integer.compare(array[first], array[second])); } public static int[] unique(int[] array) { return new IntArray(array).unique().toArray(); } public static int[] reversePermutation(int[] permutation) { int[] result = new int[permutation.length]; for (int i = 0; i < permutation.length; i++) { result[permutation[i]] = i; } return result; } public static int[] compress(int[]... arrays) { int totalLength = 0; for (int[] array : arrays) { totalLength += array.length; } int[] all = new int[totalLength]; int delta = 0; for (int[] array : arrays) { System.arraycopy(array, 0, all, delta, array.length); delta += array.length; } sort(all, IntComparator.DEFAULT); all = unique(all); for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i] = Arrays.binarySearch(all, array[i]); } } return all; } public static void orderBy(int[] base, int[]... arrays) { int[] order = ArrayUtils.order(base); order(order, base); for (int[] array : arrays) { order(order, array); } } public static void order(int[] order, int[] array) { int[] tempInt = new int[order.length]; for (int i = 0; i < order.length; i++) { tempInt[i] = array[order[i]]; } System.arraycopy(tempInt, 0, array, 0, array.length); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static interface IntReversableCollection extends IntCollection { } static class FenwickTree { private final long[] value; public FenwickTree(int size) { value = new long[size]; } public FenwickTree(long[] value) { this.value = value.clone(); init(); } void init() { for (int i = 0; i < value.length; i++) { int j = i | (i + 1); if (j < value.length) { value[j] += value[i]; } } } public long get(int from, int to) { if (from > to) { return 0; } return get(to) - get(from - 1); } private long get(int to) { to = Math.min(to, value.length - 1); long result = 0; while (to >= 0) { result += value[to]; to = (to & (to + 1)) - 1; } return result; } public void add(int at, long value) { while (at < this.value.length) { this.value[at] += value; at = at | (at + 1); } } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } 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 { boolean isSpaceChar(int ch); } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default IntList unique() { int last = Integer.MIN_VALUE; IntList result = new IntArrayList(); int size = size(); for (int i = 0; i < size; i++) { int current = get(i); if (current != last) { result.add(current); last = current; } } return result; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } }
Java
["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"]
2 seconds
["7", "0"]
NoteThe following pictures represent sample cases:
Java 8
standard input
[ "geometry", "bitmasks", "sortings", "data structures", "brute force" ]
09890f75bdcfff81f67eb915379b325e
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
2,200
Print one integer — the number of ways to choose four segments so they form a rectangle.
standard output
PASSED
e7d679b214c26fec239f92625f825433
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.util.Scanner; public class D1_690 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int R = in.nextInt(); in.nextInt(); // C String row = null; for (int r=0; r<R; r++) { row = in.next(); } int answer = 0; boolean gap = true; for (char c : row.toCharArray()) { if (c == '.') { gap = true; } else if (gap) { gap = false; answer++; } } System.out.println(answer); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
6fb25eafcbd847a8795c923537462681
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.io.*; /** * * @author root */ public class D1 { static int map[][]; static boolean visited[][]; public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tokens[] = br.readLine().split(" "); int r = Integer.parseInt(tokens[0]); int c = Integer.parseInt(tokens[1]); map = new int[r][c]; visited = new boolean[r][c]; for (int i = 0; i < r; i++) { String line = br.readLine(); for (int j = 0; j < c; j++) { if (line.charAt(j) == 'B') { map[i][j] = 1; } } } int ans = 0; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (!visited[i][j] && map[i][j] == 1) { ans++; dfs(i, j); } } } System.out.println(ans); } public static void dfs(int i, int j) { visited[i][j] = true; if (j < map[i].length - 1 && map[i][j + 1] == 1 && !visited[i][j + 1]) { dfs(i, j + 1); } if (j > 0 && map[i][j - 1] == 1 && !visited[i][j - 1]) { dfs(i, j - 1); } if (i < map.length - 1 && map[i + 1][j] == 1 && !visited[i + 1][j]) { dfs(i + 1, j); } if (i > 0 && map[i - 1][j] == 1 && !visited[i - 1][j]) { dfs(i - 1, j); } } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
d2f9c7c83177169517ffaadd4c1da944
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int r = s.nextInt(), c = s.nextInt(); s.nextLine(); char[] lastRow = new char[c]; for(int i = 0; i < r; i++) { if(i == r-1) { lastRow = s.nextLine().toCharArray(); } else s.nextLine(); } int ans = 0; boolean brick = false; for(int i = 0; i < c; i++) { char cur = lastRow[i]; if(cur == 'B' && !brick) { brick = true; ans++; } if(cur == '.') { brick = false; } } System.out.println(ans); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
0316a650511025d9a0004c43c100cb4d
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([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); TaskD1 solver = new TaskD1(); solver.solve(1, in, out); out.close(); } static class TaskD1 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); boolean[] any = new boolean[m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { any[j] = in.readCharacter() == 'B' || any[j]; } } if (ArrayUtils.count(any, true) == 0) { out.print(0); return; } int i0 = 0; while (!any[i0]) { i0++; } int i1 = m - 1; while (!any[i1]) { i1--; } i1++; int cnt = 0; while (i0 < i1) { cnt++; while (i0 < m && any[i0]) { i0++; } while (i0 < m && !any[i0]) { i0++; } } out.print(cnt); } } static class ArrayUtils { public static int count(boolean[] array, boolean value) { int result = 0; for (boolean i : array) { if (i == value) { result++; } } return result; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public 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 char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
aae65774e2b16238228b8766b744470c
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.util.Scanner; public class King { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int c = sc.nextInt(); int k = 0; int l = 1; String s = ""; for (int i = 0; i < r; i++) { s = sc.next(); } if (s.charAt(0) == 'B') { k++; l = 0; } for (int j = 0; j < c; j++) { if (s.charAt(j) == '.') l++; if (s.charAt(j) == 'B' && l > 0) { k++; l = 0; } } System.out.print(k); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
d2393aae645ad62fb98e490dd2fe662c
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { private static Set<Integer> integers; private static int wall[][]; private static int R; private static int C; public static void main(String[] args) { integers = new HashSet<>(); Scanner scanner = new Scanner(System.in); R = scanner.nextInt(); C = scanner.nextInt(); wall = new int[R][C]; String line_i; for (int i = 0; i < R; i++) { line_i = scanner.next(); for (int j = 0; j < C; j++) wall[i][j] = line_i.charAt(j) == 'B' ? -1 : 0; } scanner.close(); for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) markAs(i * j + j, i, j); System.out.println(integers.size()); } private static void markAs(int mark, int i, int j) { if (wall[i][j] != -1) return; integers.add(mark); wall[i][j] = mark; if (i - 1 >= 0) markAs(mark, i - 1, j); if (j - 1 >= 0) markAs(mark, i, j - 1); if (i + 1 < R) markAs(mark, i + 1, j); if (j + 1 < C) markAs(mark, i, j + 1); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
1c75c436ec262e43d1e4448d0c0398dd
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStream; import java.io.InputStreamReader; /** * Built using CHelper plug-in * Actual solution is at the top * @author Igor Kraskevich */ 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); TaskD1 solver = new TaskD1(); solver.solve(1, in, out); out.close(); } } class TaskD1 { public void solve(int testNumber, FastScanner in, PrintWriter out) { int rows = in.nextInt(); int cols = in.nextInt(); for (int i = 0; i < rows - 1; i++) in.next(); String s = in.next(); boolean clear = true; int cnt = 0; for (int i = 0; i < cols; i++) if (s.charAt(i) == 'B') { if (clear) { clear = false; cnt++; } } else { clear = true; } out.println(cnt); } } class FastScanner { private StringTokenizer tokenizer; private BufferedReader reader; public FastScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = null; try { line = reader.readLine(); } catch (IOException e) { } if (line == null) return null; tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
091122f071b8be8c53351d8b9e035c42
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.util.*; import java.io.*; public class D1{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); String[] line = br.readLine().split(" "); int r = Integer.parseInt(line[0]); int c = Integer.parseInt(line[1]); while( r-- > 1 ){ br.readLine(); } String l = br.readLine(); int cnt = 0; int i = 0; while( i < l.length() ){ if( l.charAt(i) == 'B' ){ cnt++; while( i < l.length() && l.charAt(i) == 'B' ) i++; }else{ while( i < l.length() && l.charAt(i) == '.' ) i++; } } out.println(cnt); out.close(); } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
34a91600d14933ce8684878c86b3d65d
train_000.jsonl
1468137600
"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
256 megabytes
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main4easy { public static void runBFS(boolean[][] mat, int i, int j, int H, int W){ Queue<Par> q = new LinkedList<>(); q.add(new Par(i, j)); mat[i][j] = false; while(!q.isEmpty()){ Par cur = q.remove(); int ci = cur.i; int cj = cur.j; //gore if(ci > 0 && mat[ci-1][cj]){ mat[ci-1][cj] = false; q.add(new Par(ci-1, cj)); } //dole if(ci < (H-1) && mat[ci+1][cj]){ mat[ci+1][cj] = false; q.add(new Par(ci+1, cj)); } //levo if(cj > 0 && mat[ci][cj-1]){ mat[ci][cj-1] = false; q.add(new Par(ci, cj-1)); } //desno if(cj < (W-1) && mat[ci][cj+1]){ mat[ci][cj+1] = false; q.add(new Par(ci, cj+1)); } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int H = sc.nextInt(); int W = sc.nextInt(); boolean[][] mat = new boolean[H][W]; //false by default for(int i = 0; i<H; i++){ String line = sc.next(); for(int j = 0; j<W; j++){ if(line.charAt(j) == 'B'){ mat[i][j] = true; } } } int counter = 0; for(int i = 0; i<H; i++){ for(int j = 0; j<W; j++){ if(mat[i][j]){ counter++; runBFS(mat, i, j, H, W); } } } System.out.println(counter); } } class Par{ int i; int j; Par(int ii, int jj){ i = ii; j = jj; } }
Java
["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"]
0.5 seconds
["2", "2", "1", "1", "3", "2"]
NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Java 8
standard input
[]
c339795767a174a59225a79023b5d14f
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. B
1,200
The number of wall segments in the input configuration.
standard output
PASSED
03e0c60027fdd3c20b32896960fe5103
train_000.jsonl
1422376200
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { int visitors, durationOfCandle, minimumBurningCandlePerVisit; int candlesStillBurningForNextVisit, extraCandlesNeededForNextVisit; int periodToTheNextVisit; int totalCandlesNeeded; public void solve() { visitors = in.nextInt(); durationOfCandle = in.nextInt(); minimumBurningCandlePerVisit = in.nextInt(); if (durationOfCandle < minimumBurningCandlePerVisit) { out.println("-1"); return; } if (visitors == 1) { out.println(minimumBurningCandlePerVisit); return; } List<Candle> candles = new ArrayList<>(); initualizeSetOfBurningCandles(candles); int previousVisitTime = 0, nextVisitTime = 0; int extraCandlesNeeded = 0; for (int i = 0; i < visitors; i++) { nextVisitTime = in.nextInt(); if (!isTheFirstVisit(previousVisitTime)) { periodToTheNextVisit = nextVisitTime - previousVisitTime; int remainingTimeAdapter = 0; for (Candle candle : candles) { int remainingTimeAfterTheNextVisit = candle.getRemainingTime() - periodToTheNextVisit; if (remainingTimeAfterTheNextVisit <= 0) { candle.setRemainingTime(durationOfCandle - remainingTimeAdapter); extraCandlesNeeded++; remainingTimeAdapter++; } else { candle.setRemainingTime(remainingTimeAfterTheNextVisit); } } // for next round previousVisitTime = nextVisitTime; } else { totalCandlesNeeded += minimumBurningCandlePerVisit; previousVisitTime = nextVisitTime; } } totalCandlesNeeded += extraCandlesNeeded; out.println(totalCandlesNeeded); } private void initualizeSetOfBurningCandles(List<Candle> candles) { for (int i = 0; i < minimumBurningCandlePerVisit; i++) { Candle candle = new Candle(); candle.setRemainingTime(durationOfCandle - minimumBurningCandlePerVisit + 1 + i); candles.add(candle); } } private boolean isTheFirstVisit(int previousVisitTime) { return previousVisitTime == 0; } private class Candle { int remainingTime; public int getRemainingTime() { return remainingTime; } public void setRemainingTime(int remainingTime) { this.remainingTime = remainingTime; } } public void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } FastScanner in; PrintWriter out; class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new CodeForces().run(); } }
Java
["1 8 3\n10", "2 10 1\n5 8", "1 1 3\n10"]
2 seconds
["3", "1", "-1"]
NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is  - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
03772bac6ed5bfe75bc0ad4d2eab56fd
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
1,600
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print  - 1.
standard output
PASSED
ae98b86e592f15387201496e7b5300f8
train_000.jsonl
1422376200
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Prob7 { public static void trier(int a[],int r) { for(int i=0;i<r;i++) { for(int j=i+1;j<r;j++) { if(a[i]>a[j]) { int c=a[j]; a[j]=a[i]; a[i]=c; } } } } public static int generer(int visite,int duree,int r,int min,int max,ArrayList<Integer> s) { int first=min-r+duree; int res = r; if(visite==1 && duree-r>=0) return r; else if(visite==1 && duree-r<0 ) return -1; /*else if(visite==1 && duree==1 && r==1) return 1;*/ int taille; int a[]=new int[r]; for(int i=r;i>0;i--) a[r-i]=s.get(0)-i; for(int i=0;i<s.size()-1;i++) { int val=s.get(i); int nval=s.get(i+1); int reste=0; taille=s.get(i+1)-s.get(i); trier(a,r); for(int j=0;j<r;j++) { if(a[j]+duree<val) return -1; if(a[j]+duree<nval) { reste++; if(reste>taille+1) return -1; else { res++; a[j]=nval-j-1; } } } /* if(duree-r<taille) { System.out.println(i); res=-1; break; } */ } /* if(res!=-1) return (((max-min)-((max-min)%duree))/duree+1)*r; else return -1; /* * */ if(duree!=1) return res; else return -1; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int visite=sc.nextInt(); int duree=sc.nextInt(); int r=sc.nextInt(); ArrayList<Integer> l=new ArrayList<Integer>(); for(int i=0;i<visite;i++) l.add(sc.nextInt()); //System.out.println("hhhhhh"); System.out.println(generer(visite, duree, r,l.get(0),l.get(l.size()-1),l)); /* int a[]={4,8,9,3,2,7}; trier(a,6); for(int i=0;i<6;i++) System.out.println(a[i]);*/ } }
Java
["1 8 3\n10", "2 10 1\n5 8", "1 1 3\n10"]
2 seconds
["3", "1", "-1"]
NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is  - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
03772bac6ed5bfe75bc0ad4d2eab56fd
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
1,600
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print  - 1.
standard output
PASSED
e83b8841acaeb6ec59cab70160e8aa05
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
import static java.lang.Math.* ; import static java.util.Arrays.* ; import java.math.BigInteger; import java.util.*; import java.io.*; public class Main { void main() throws Exception { Scanner sc = new Scanner(System.in) ; PrintWriter out = new PrintWriter(System.out) ; int TC = sc.nextInt() ; while(TC-->0) { char[] s = sc.next().toCharArray(); SuffixAutomaton sa = new SuffixAutomaton(s); long ans = 0 ; for(int v = 1 ; v <= sa.idx ; v++) ans += (1L * sa.cnt[v] * sa.cnt[v]) * (sa.len[v] - sa.len[sa.link[v]]) ; out.println(ans); } out.flush(); out.close(); } class SuffixAutomaton { int[] link, len , cnt; int [][] next ; boolean [] isClone ; int lst, idx; int [] endPos ; SuffixAutomaton(char[] s) { int n = s.length; link = new int[n<<1]; len = new int[n<<1]; next = new int [26][n << 1] ; cnt = new int [n << 1] ; endPos = new int [n << 1] ; isClone = new boolean[n << 1] ; int ix = 0 ; for(char c: s) addLetter(c - 'a' , ix ++); Integer [] id = new Integer[idx + 1] ; for(int i = 0 ; i <= idx ; i++) { id[i] = i; isClone[i] = cnt[i] == 0; } sort(id , (x , y)->len[y] - len[x]); for(int v : id) cnt[link[v]] += cnt[v] ; } void addLetter(int c , int ix) { int cur = ++idx, p = lst; endPos[cur] = ix ; while(next[c][p] == 0) { next[c][p] = cur; p = link[p]; } cnt[cur] = 1 ; int q = next[c][p]; if(q != cur) if(len[q] == len[p] + 1) link[cur] = q; else { int clone = ++idx; len[clone] = len[p] + 1; link[clone] = link[q]; endPos[clone] = endPos[q] ; for(int i = 0 ; i < 26 ; i++) next[i][clone] = next[i][q] ; link[cur] = link[q] = clone; while(next[c][p] == q) { next[c][p] = clone; p = link[p]; } } len[cur] = len[lst] + 1; lst = cur; } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String path) throws Exception { br = new BufferedReader(new FileReader(path)) ; } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next());} } public static void main (String [] args) throws Exception {(new Main()).main();} }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
4db4f21edcdbc6fc6eedf0737a055a2c
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Main { public static InputReader in = new InputReader(System.in); public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { int a; String s; SAM part=new SAM(); a=in.nextInt(); while (a--!=0) { s=in.next(); part.init(2*s.length()+2,26); for(int i=0;i<s.length();++i) part.insert(s.charAt(i)-'a'); long ans=0; part.topo(); SAM_node part2=part.root; for(int i=0;i<s.length();++i) { part2=part2.next[s.charAt(i)-'a']; part2.cnt=1; } for(int i=part.cur-1;i>0;--i) part.pool[i].pre.cnt+=part.pool[i].cnt; for(int i=part.cur-1;i>0;--i) ans+=(long)part.pool[i].cnt*(long)part.pool[i].cnt*((long)part.pool[i].step-(long)part.pool[i].pre.step); out.println(ans); } out.flush(); out.close(); } } class SAM_node { SAM_node pre,next[]; int step,cnt; SAM_node(int sigma) { next=new SAM_node[sigma]; Arrays.fill(next,null); step=0; cnt=0; pre=null; } } class SAM { SAM_node SAM_pool[],root,last; int d[]; SAM_node pool[]; int cur; int sigma; void topo() { int cnt = cur; int maxVal = 0; Arrays.fill(d, 0); for (int i = 1; i < cnt; i++) { maxVal = Math.max(maxVal, SAM_pool[i].step); d[SAM_pool[i].step]++; } for (int i = 1; i <= maxVal; i++) d[i] += d[i - 1]; for (int i = 1; i < cnt; i++) pool[d[SAM_pool[i].step]--] = SAM_pool[i]; pool[0] = root; } void init(int a,int b) { d=new int[a]; pool=new SAM_node[a]; SAM_pool=new SAM_node[a]; SAM_pool[0]=new SAM_node(b); sigma=b; root=last=SAM_pool[0]; cur=1; } void insert(int w) { SAM_node p=last; SAM_pool[cur]=new SAM_node(sigma); SAM_node np=SAM_pool[cur]; last=np; cur++; np.step=p.step+1; while (p!=null && p.next[w]==null) { p.next[w]=np; p = p.pre; } if(p==null) { np.pre=root; } else { SAM_node q=p.next[w]; if(p.step+1==q.step) np.pre=q; else { SAM_node nq = SAM_pool[cur++] = new SAM_node(sigma); nq.next = Arrays.copyOf(q.next, sigma); nq.cnt = q.cnt; nq.step = p.step + 1; nq.pre = q.pre; q.pre = nq; np.pre = nq; while (p != null && p.next[w]==(q)) { p.next[w] = nq; p = p.pre; } } } } } class InputReader{ private final static int BUF_SZ = 65536; BufferedReader in; StringTokenizer tokenizer; public InputReader(InputStream in) { super(); this.in = new BufferedReader(new InputStreamReader(in),BUF_SZ); tokenizer = new StringTokenizer(""); } public String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
6d5e77063b2b56eba66536b3ff5be29c
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; public class SumOfSquares { public static void main(String[] args) throws IOException { in.nextToken(); int tests = (int) in.nval; for (int T = 0; T < tests; T++) { LrsArray lrsArray = new LrsArray(); Map<Integer, List<Integer>> repeats = new HashMap<>(); in.nextToken(); for (char c : in.sval.toCharArray()) { LrsArray.Lmo repeat = lrsArray.append(c); if (repeat.length > 0) { addValue(repeats, repeat.rightEnd, lrsArray.text.size() - 1); } else { addValue(repeats, 0, lrsArray.text.size() - 1); } } TreeMap<LrsArray.Lmo, Long> counts = new TreeMap<>(); dfs(repeats, lrsArray.lrs, counts, 0); long sumOfSquares = 0; for (int i = 1; i < lrsArray.text.size(); i++) { LrsArray.Lmo lmo = lrsArray.lrs.get(i); sumOfSquares += i - lmo.length; } int lastEnd = 0; int lastLen = 0; for (Map.Entry<LrsArray.Lmo, Long> entry : counts.entrySet()) { LrsArray.Lmo lmo = entry.getKey(); if (lastEnd != lmo.rightEnd) { lastEnd = lmo.rightEnd; lastLen = lmo.lrs().length; } long length = lmo.length - lastLen; sumOfSquares += length * square(entry.getValue() + 1) - length; lastLen = lmo.length; } out.println(sumOfSquares); } out.flush(); } static long square(long x) { return x * x; } static long dfs(Map<Integer, List<Integer>> tree, List<LrsArray.Lmo> lrs, Map<LrsArray.Lmo, Long> counts, Integer node) { long result = 1; TreeMap<Integer, Long> sorted = new TreeMap<>(); Map<Integer, LrsArray.Lmo> lmos = new HashMap<>(); for (Integer child : tree.getOrDefault(node, Collections.emptyList())) { long value = dfs(tree, lrs, counts, child); sorted.merge(lrs.get(child).length, value, (x, y) -> x + y); lmos.put(lrs.get(child).length, lrs.get(child)); result += value; } long count = 0; for (Map.Entry<Integer, Long> entry : sorted.descendingMap().entrySet()) { count += entry.getValue(); counts.put(lmos.get(entry.getKey()), count); } return result; } static <K, V> void addValue(Map<K, List<V>> map, K key, V value) { if (!map.containsKey(key)) { map.put(key, new ArrayList<>()); } map.get(key).add(value); } static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in, StandardCharsets.ISO_8859_1 ))); static PrintWriter out = new PrintWriter(new OutputStreamWriter( System.out, StandardCharsets.ISO_8859_1 )); } class LrsArray { List<Character> text = arrayList(null); Map<Pair<Lmo, Character>, Integer> extensions = new HashMap<>(); List<Lmo> lrs = arrayList(new Lmo(-1, -1) { @Override boolean isNext(char c) { return true; } }); Lmo append(char c) { text.add(c); Lmo longest = lrs.get(lrs.size() - 1); while (!longest.hasExtension(c)) { extensions.put(Pair.of(longest, c), lrs.size()); longest = longest.lps(); } longest = longest.extend(c); lrs.add(longest); return longest; } class Lmo implements Comparable<Lmo> { final int rightEnd; final int length; Lmo(int rightEnd, int length) { this.rightEnd = rightEnd; this.length = length; } boolean isNext(char c) { return text.get(rightEnd + 1) == c; } boolean hasExtension(char c) { return isNext(c) || extensions.containsKey(Pair.of(this, c)); } Lmo extend(char c) { return new Lmo( isNext(c) ? rightEnd + 1 : extensions.get(Pair.of(this, c)), length + 1 ); } Lmo lrs() { return lrs.get(rightEnd); } Lmo lps() { return length - 1 == lrs().length ? lrs() : new Lmo(rightEnd, length - 1); } @Override public int compareTo(LrsArray.Lmo o) { if (rightEnd == o.rightEnd) { return Integer.compare(length, o.length); } else { return Integer.compare(rightEnd, o.rightEnd); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Lmo lmo = (Lmo) o; return rightEnd == lmo.rightEnd && length == lmo.length; } @Override public int hashCode() { return Objects.hash(rightEnd, length); } @Override public String toString() { return rightEnd + " " + length; } } static <T> List<T> arrayList(T single) { ArrayList<T> arrayList = new ArrayList<>(1); arrayList.add(single); return arrayList; } } class Pair<T1, T2> { final T1 p1; final T2 p2; Pair(T1 p1, T2 p2) { this.p1 = p1; this.p2 = p2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(p1, pair.p1) && Objects.equals(p2, pair.p2); } @Override public int hashCode() { return Objects.hash(p1, p2); } static <T1, T2> Pair<T1, T2> of(T1 p1, T2 p2) { return new Pair<>(p1, p2); } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
3912853d1e5d324a1dec527e00e1b8e7
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class CF802I { final int ALPHA = 26; final int OFFSET = 'a'; int next, MAX, last, len[], link[], trie[][]; long[] dp; boolean[] terminal; void suffixAutomaton(char[] s) { MAX = s.length << 1; next = 1; last = 0; len = new int[MAX]; link = new int[MAX]; trie = new int[ALPHA][MAX]; terminal = new boolean[MAX]; link[0] = -1; for(char cc : s) { int c = cc - OFFSET; int cur = next++; len[cur] = len[last] + 1; int p = last; while(p != -1 && trie[c][p] == 0) { trie[c][p] = cur; p = link[p]; } if(p == -1) { link[cur] = 0; } else { int q = trie[c][p]; if(len[p] + 1 == len[q]) { link[cur] = q; } else { int clone = next++; len[clone] = len[p] + 1; link[clone] = link[q]; for(int i = 0 ; i < ALPHA ; i++) trie[i][clone] = trie[i][q]; while(p != -1 && trie[c][p] == q) { trie[c][p] = clone; p = link[p]; } link[q] = link[cur] = clone; } } last = cur; } terminal = new boolean[MAX]; int p = last; while(p > 0) { terminal[p] = true; p = link[p]; } dp = new long[MAX]; dfs(0); } void dfs(int node) { if(dp[node] != 0) return; dp[node] = terminal[node] ? 1 : 0; for(int let = 0 ; let < ALPHA ; let++) { if(trie[let][node] != 0) { dfs(trie[let][node]); dp[node] += dp[trie[let][node]]; } } } public CF802I() { FS scan = new FS(); PrintWriter out = new PrintWriter(System.out); int t = scan.nextInt(); for(int tt = 0 ; tt < t ; tt++) { char[] s = scan.next().toCharArray(); suffixAutomaton(s); long res = 0; for(int node = 1 ; node < MAX ; node++) res += dp[node] * dp[node] * (len[node] - len[link[node]]); out.println(res); } out.close(); } 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 static void main(String[] args) { new CF802I(); } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
1ff08e71b628ae96fe5ef35a96fe1c46
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
//Created by Aminul on 9/3/2019. import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import static java.lang.Math.max; public class CF802I { public static void main(String[] args) throws Exception { //Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int test = Integer.parseInt(br.readLine()); for(int t = 1; t <= test; t++) { char[] s = br.readLine().toCharArray(); int n = s.length; int sa[] = suffixArray(s); final int lcp[] = lcp(sa, s); long ans = 0; SegTree segTree = new SegTree(n + 1); for (int i = n - 1; i >= 0; i--) { int len = n - sa[i]; ans += segTree.query(1, len) + len; segTree.clearRange(lcp[i] + 1, n); segTree.update(1, lcp[i], 1); } segTree = new SegTree(n + 1); for (int i = 0; i < n; i++) { int len = n - sa[i]; ans += segTree.query(1, len); if(i + 1 < n) segTree.clearRange(lcp[i + 1] + 1, n); if(i + 1 < n) segTree.update(1, lcp[i + 1], 1); } pw.println(ans); } pw.close(); } static int[] suffixArray(char[] S) { int n = S.length; Integer ord[] = new Integer[n]; for (int i = 0; i < n; i++) ord[i] = n - 1 - i; Arrays.sort(ord, (a, b) -> Character.compare(S[a], S[b])); int order[] = new int[n]; for (int i = 0; i < n; i++) order[i] = ord[i]; //Arrays.sort(order, new Comparator<Integer>() {public int compare(Integer o1, Integer o2) { return S[o1] - S[o2]; }}); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S[i]; } for (int len = 1; len < n; len <<= 1) { //int[] c = classes.clone(); int c[] = Arrays.copyOf(classes, n); for (int i = 0; i < n; i++) { classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + (len >> 1)] == c[sa[i] + (len >> 1)] ? classes[sa[i - 1]] : i; } int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } //int[] s = sa.clone(); int[] s = Arrays.copyOf(sa, n); for (int i = 0; i < n; i++) { int s1 = s[i] - len; if (s1 >= 0) { sa[cnt[classes[s1]]++] = s1; } } } return sa; } static int[] lcp(int[] sa, char[] 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]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; max(i, j) + h < s.length && s[i + h] == s[j + h]; ++h) ; lcp[rank[i] + 1] = h; if (h > 0) --h; } } return lcp; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class SegTree { Node root; int n; SegTree(int N) { n = N; root = new Node(); } void pushDown(Node node, int s, int m, int e) { if (node.lazy == 0) return; if (node.left != null) { node.left.value += (m - s + 1) * node.lazy; node.left.lazy += node.lazy; } if (node.right != null) { node.right.value += (e - m) * node.lazy; node.right.lazy += node.lazy; } node.lazy = 0; } void update(int l, int r, int v) { update(root, 1, n, l, r, v); } void update(Node node, int s, int e, int a, int b, int value) { if (s > e || s > b || e < a) return; if (s >= a && e <= b) { node.lazy += value; node.value += (e - s + 1) * value; return; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); update(node.left, s, m, a, b, value); update(node.right, m + 1, e, a, b, value); node.value = node.left.value + node.right.value; } void clearRange(int l, int r) { root = clearRange(root, 1, n, l, r); } Node clearRange(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return node; if (s >= a && e <= b) { return new Node(); } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); node.left = clearRange(node.left, s, m, a, b); node.right = clearRange(node.right, m + 1, e, a, b); node.value = node.left.value + node.right.value; return node; } long query(int l, int r) { return query(root, 1, n, l, r); } long query(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return 0; if (s >= a && e <= b) { return node.value; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); return query(node.left, s, m, a, b) + query(node.right, m + 1, e, a, b); } static class Node { Node left, right; long value, lazy; Node() { } Node(int v) { value = v; } @Override public String toString() { return "[" + value + ", " + lazy + "]"; } } } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
f955fc722a0b19a77c2baa614a2bb58a
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
//Created by Aminul on 9/3/2019. import java.io.*; import java.util.*; import static java.lang.Math.max; public class CF802I_fast { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); SuffixArray SA = new SuffixArray(); int test = in.nextInt(); for(int t = 1; t <= test; t++) { char[] s = in.next().toCharArray(); int n = s.length; int sa[] = SA.getSuffixArray(s); final int lcp[] = lcp(sa, s); long ans = 0; SegTree segTree = new SegTree(n + 1); for (int i = n - 1; i >= 0; i--) { int len = n - sa[i]; ans += segTree.query(1, len) + len; segTree.clearRange(lcp[i] + 1, n); segTree.update(1, lcp[i], 1); } segTree = new SegTree(n + 1); for (int i = 0; i < n; i++) { int len = n - sa[i]; ans += segTree.query(1, len); if(i + 1 < n) segTree.clearRange(lcp[i + 1] + 1, n); if(i + 1 < n) segTree.update(1, lcp[i + 1], 1); } pw.println(ans); } pw.close(); } static class SuffixArray { char str[]; int N, m; int [] SA; int [] x, y, w; int max_n; SuffixArray() { } int[] getSuffixArray(char[] s) { str = changeString(s); m = 256; N = str.length; max_n = max(m, N + 1); SA = new int[N]; x = new int[max_n]; y = new int[max_n]; w = new int[max_n]; DA(); SA = Arrays.copyOf(SA, N - 1); return SA; } boolean cmp(int a, int b, int l) { return (y[a] == y[b] && y[a + l] == y[b + l]); } void Sort() { for (int i = 0; i < m; ++i) w[i] = 0; for (int i = 0; i < N; ++i) ++w[x[y[i]]]; for (int i = 0; i < m - 1; ++i) w[i + 1] += w[i]; for (int i = N - 1; i >= 0; --i) SA[--w[x[y[i]]]] = y[i]; } void DA() { for (int i = 0; i < N; ++i) { x[i] = str[i]; y[i] = i; } Sort(); for (int i, j = 1, p = 1; p < N; j <<= 1, m = p) { for (p = 0, i = N - j; i < N; i++) y[p++] = i; for (int k = 0; k < N; ++k) if (SA[k] >= j) y[p++] = SA[k] - j; Sort(); for (swap(), p = 1, x[SA[0]] = 0, i = 1; i < N; ++i) x[SA[i]] = cmp(SA[i - 1], SA[i], j) ? p - 1 : p++; } } void swap() { int t[] = x; x = y; y = t; } static char[] changeString(char[] s){ char [] t = new char[s.length+1]; System.arraycopy(s, 0, t, 0, s.length); t[s.length] = '~'; return t; } } static int[] suffixArray(char[] S) { int n = S.length; Integer ord[] = new Integer[n]; for (int i = 0; i < n; i++) ord[i] = n - 1 - i; Arrays.sort(ord, (a, b) -> Character.compare(S[a], S[b])); int order[] = new int[n]; for (int i = 0; i < n; i++) order[i] = ord[i]; //Arrays.sort(order, new Comparator<Integer>() {public int compare(Integer o1, Integer o2) { return S[o1] - S[o2]; }}); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S[i]; } for (int len = 1; len < n; len <<= 1) { int[] c = classes.clone(); for (int i = 0; i < n; i++) { classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + (len >> 1)] == c[sa[i] + (len >> 1)] ? classes[sa[i - 1]] : i; } int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } int[] s = sa.clone(); for (int i = 0; i < n; i++) { int s1 = s[i] - len; if (s1 >= 0) { sa[cnt[classes[s1]]++] = s1; } } } return sa; } static int[] lcp(int[] sa, char[] 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]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; max(i, j) + h < s.length && s[i + h] == s[j + h]; ++h) ; lcp[rank[i] + 1] = h; if (h > 0) --h; } } return lcp; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class SegTree { Node root; int n; SegTree(int N) { n = N; root = new Node(); } void pushDown(Node node, int s, int m, int e) { if (node.lazy == 0) return; if (node.left != null) { node.left.value += (m - s + 1) * node.lazy; node.left.lazy += node.lazy; } if (node.right != null) { node.right.value += (e - m) * node.lazy; node.right.lazy += node.lazy; } node.lazy = 0; } void update(int l, int r, int v) { update(root, 1, n, l, r, v); } void update(Node node, int s, int e, int a, int b, int value) { if (s > e || s > b || e < a) return; if (s >= a && e <= b) { node.lazy += value; node.value += (e - s + 1) * value; return; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); update(node.left, s, m, a, b, value); update(node.right, m + 1, e, a, b, value); node.value = node.left.value + node.right.value; } void clearRange(int l, int r) { root = clearRange(root, 1, n, l, r); } Node clearRange(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return node; if (s >= a && e <= b) { return new Node(); } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); node.left = clearRange(node.left, s, m, a, b); node.right = clearRange(node.right, m + 1, e, a, b); node.value = node.left.value + node.right.value; return node; } long query(int l, int r) { return query(root, 1, n, l, r); } long query(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return 0; if (s >= a && e <= b) { return node.value; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); return query(node.left, s, m, a, b) + query(node.right, m + 1, e, a, b); } static class Node { Node left, right; long value, lazy; Node() { } Node(int v) { value = v; } @Override public String toString() { return "[" + value + ", " + lazy + "]"; } } } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public 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 boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public String nextLine() { int c = skip(); StringBuilder sb = new StringBuilder(); while (!isEndOfLine(c)){ sb.appendCodePoint(c); c = readByte(); } return sb.toString(); } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } public 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); } public char readChar() { return (char) skip(); } } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
b47120ad059a4178bb24428d451673e4
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
//Created by Aminul on 9/3/2019. import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import static java.lang.Math.max; public class CF802I { public static void main(String[] args) throws Exception { //Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int test = Integer.parseInt(br.readLine()); for(int t = 1; t <= test; t++) { char[] s = br.readLine().toCharArray(); int n = s.length; int sa[] = suffixArray(s); final int lcp[] = lcp(sa, s); long ans = 0; SegTree segTree = new SegTree(n + 1); for (int i = n - 1; i >= 0; i--) { int len = n - sa[i]; ans += segTree.query(1, len) + len; segTree.clearRange(lcp[i] + 1, n); segTree.update(1, lcp[i], 1); } segTree = new SegTree(n + 1); for (int i = 0; i < n; i++) { int len = n - sa[i]; ans += segTree.query(1, len); if(i + 1 < n) segTree.clearRange(lcp[i + 1] + 1, n); if(i + 1 < n) segTree.update(1, lcp[i + 1], 1); } pw.println(ans); } pw.close(); } static int[] suffixArray(char[] S) { int n = S.length; Integer ord[] = new Integer[n]; for (int i = 0; i < n; i++) ord[i] = n - 1 - i; Arrays.sort(ord, (a, b) -> Character.compare(S[a], S[b])); int order[] = new int[n]; for (int i = 0; i < n; i++) order[i] = ord[i]; //Arrays.sort(order, new Comparator<Integer>() {public int compare(Integer o1, Integer o2) { return S[o1] - S[o2]; }}); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S[i]; } for (int len = 1; len < n; len <<= 1) { int[] c = classes.clone(); for (int i = 0; i < n; i++) { classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + (len >> 1)] == c[sa[i] + (len >> 1)] ? classes[sa[i - 1]] : i; } int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } int[] s = sa.clone(); for (int i = 0; i < n; i++) { int s1 = s[i] - len; if (s1 >= 0) { sa[cnt[classes[s1]]++] = s1; } } } return sa; } static int[] lcp(int[] sa, char[] 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]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; max(i, j) + h < s.length && s[i + h] == s[j + h]; ++h) ; lcp[rank[i] + 1] = h; if (h > 0) --h; } } return lcp; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class SegTree { Node root; int n; SegTree(int N) { n = N; root = new Node(); } void pushDown(Node node, int s, int m, int e) { if (node.lazy == 0) return; if (node.left != null) { node.left.value += (m - s + 1) * node.lazy; node.left.lazy += node.lazy; } if (node.right != null) { node.right.value += (e - m) * node.lazy; node.right.lazy += node.lazy; } node.lazy = 0; } void update(int l, int r, int v) { update(root, 1, n, l, r, v); } void update(Node node, int s, int e, int a, int b, int value) { if (s > e || s > b || e < a) return; if (s >= a && e <= b) { node.lazy += value; node.value += (e - s + 1) * value; return; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); update(node.left, s, m, a, b, value); update(node.right, m + 1, e, a, b, value); node.value = node.left.value + node.right.value; } void clearRange(int l, int r) { root = clearRange(root, 1, n, l, r); } Node clearRange(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return node; if (s >= a && e <= b) { return new Node(); } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); node.left = clearRange(node.left, s, m, a, b); node.right = clearRange(node.right, m + 1, e, a, b); node.value = node.left.value + node.right.value; return node; } long query(int l, int r) { return query(root, 1, n, l, r); } long query(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return 0; if (s >= a && e <= b) { return node.value; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); return query(node.left, s, m, a, b) + query(node.right, m + 1, e, a, b); } static class Node { Node left, right; long value, lazy; Node() { } Node(int v) { value = v; } @Override public String toString() { return "[" + value + ", " + lazy + "]"; } } } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
4fca6144aee8b028af6179b76d984a94
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
//Created by Aminul on 9/3/2019. import java.io.*; import java.util.*; import static java.lang.Math.max; public class CF802I_fast { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int test = in.nextInt(); for(int t = 1; t <= test; t++) { char[] s = in.next().toCharArray(); int n = s.length; int sa[] = suffixArray(s); final int lcp[] = lcp(sa, s); long ans = 0; SegTree segTree = new SegTree(n + 1); for (int i = n - 1; i >= 0; i--) { int len = n - sa[i]; ans += segTree.query(1, len) + len; segTree.clearRange(lcp[i] + 1, n); segTree.update(1, lcp[i], 1); } segTree = new SegTree(n + 1); for (int i = 0; i < n; i++) { int len = n - sa[i]; ans += segTree.query(1, len); if(i + 1 < n) segTree.clearRange(lcp[i + 1] + 1, n); if(i + 1 < n) segTree.update(1, lcp[i + 1], 1); } pw.println(ans); } pw.close(); } static int[] suffixArray(char[] S) { int n = S.length; Integer ord[] = new Integer[n]; for (int i = 0; i < n; i++) ord[i] = n - 1 - i; Arrays.sort(ord, (a, b) -> Character.compare(S[a], S[b])); int order[] = new int[n]; for (int i = 0; i < n; i++) order[i] = ord[i]; //Arrays.sort(order, new Comparator<Integer>() {public int compare(Integer o1, Integer o2) { return S[o1] - S[o2]; }}); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S[i]; } for (int len = 1; len < n; len <<= 1) { int[] c = classes.clone(); for (int i = 0; i < n; i++) { classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + (len >> 1)] == c[sa[i] + (len >> 1)] ? classes[sa[i - 1]] : i; } int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } int[] s = sa.clone(); for (int i = 0; i < n; i++) { int s1 = s[i] - len; if (s1 >= 0) { sa[cnt[classes[s1]]++] = s1; } } } return sa; } static int[] lcp(int[] sa, char[] 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]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; max(i, j) + h < s.length && s[i + h] == s[j + h]; ++h) ; lcp[rank[i] + 1] = h; if (h > 0) --h; } } return lcp; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class SegTree { Node root; int n; SegTree(int N) { n = N; root = new Node(); } void pushDown(Node node, int s, int m, int e) { if (node.lazy == 0) return; if (node.left != null) { node.left.value += (m - s + 1) * node.lazy; node.left.lazy += node.lazy; } if (node.right != null) { node.right.value += (e - m) * node.lazy; node.right.lazy += node.lazy; } node.lazy = 0; } void update(int l, int r, int v) { update(root, 1, n, l, r, v); } void update(Node node, int s, int e, int a, int b, int value) { if (s > e || s > b || e < a) return; if (s >= a && e <= b) { node.lazy += value; node.value += (e - s + 1) * value; return; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); update(node.left, s, m, a, b, value); update(node.right, m + 1, e, a, b, value); node.value = node.left.value + node.right.value; } void clearRange(int l, int r) { root = clearRange(root, 1, n, l, r); } Node clearRange(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return node; if (s >= a && e <= b) { return new Node(); } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); node.left = clearRange(node.left, s, m, a, b); node.right = clearRange(node.right, m + 1, e, a, b); node.value = node.left.value + node.right.value; return node; } long query(int l, int r) { return query(root, 1, n, l, r); } long query(Node node, int s, int e, int a, int b) { if (s > e || s > b || e < a) return 0; if (s >= a && e <= b) { return node.value; } int m = (s + e) / 2; if (node.left == null) node.left = new Node(); if (node.right == null) node.right = new Node(); pushDown(node, s, m, e); return query(node.left, s, m, a, b) + query(node.right, m + 1, e, a, b); } static class Node { Node left, right; long value, lazy; Node() { } Node(int v) { value = v; } @Override public String toString() { return "[" + value + ", " + lazy + "]"; } } } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public 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 boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public String nextLine() { int c = skip(); StringBuilder sb = new StringBuilder(); while (!isEndOfLine(c)){ sb.appendCodePoint(c); c = readByte(); } return sb.toString(); } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } public 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); } public char readChar() { return (char) skip(); } } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
17f518e8a7d76fea68c0bf3449646161
train_000.jsonl
1495958700
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Main { public static InputReader in = new InputReader(System.in); public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { int a; String s; SAM part=new SAM(); a=in.nextInt(); while (a--!=0) { s=in.next(); part.init(2*s.length()+10,26); for(int i=0;i<s.length();++i) part.insert(s.charAt(i)-'a'); long ans=0; part.topo(); SAM_node part2=part.root; for(int i=0;i<s.length();++i) { part2=part2.next[s.charAt(i)-'a']; part2.cnt=1; } for(int i=part.cur-1;i>0;--i) part.pool[i].pre.cnt+=part.pool[i].cnt; for(int i=part.cur-1;i>0;--i) ans+=(long)part.pool[i].cnt*(long)part.pool[i].cnt*((long)part.pool[i].step-(long)part.pool[i].pre.step); out.println(ans); } out.flush(); out.close(); } } class SAM_node { SAM_node pre,next[]; int step,cnt; SAM_node(int sigma) { next=new SAM_node[sigma]; Arrays.fill(next,null); step=0; cnt=0; pre=null; } } class SAM { SAM_node SAM_pool[],root,last; int d[]; SAM_node pool[]; int cur; int sigma; void topo() { int cnt = cur; int maxVal = 0; Arrays.fill(d, 0); for (int i = 1; i < cnt; i++) { maxVal = Math.max(maxVal, SAM_pool[i].step); d[SAM_pool[i].step]++; } for (int i = 1; i <= maxVal; i++) d[i] += d[i - 1]; for (int i = 1; i < cnt; i++) pool[d[SAM_pool[i].step]--] = SAM_pool[i]; pool[0] = root; } void init(int a,int b) { d=new int[a]; pool=new SAM_node[a]; SAM_pool=new SAM_node[a]; SAM_pool[0]=new SAM_node(b); sigma=b; root=last=SAM_pool[0]; cur=1; } void insert(int w) { SAM_node p=last; SAM_pool[cur]=new SAM_node(sigma); SAM_node np=SAM_pool[cur]; last=np; cur++; np.step=p.step+1; while (p!=null && p.next[w]==null) { p.next[w]=np; p = p.pre; } if(p==null) { np.pre=root; } else { SAM_node q=p.next[w]; if(p.step+1==q.step) np.pre=q; else { SAM_node nq = SAM_pool[cur++] = new SAM_node(sigma); nq.next = Arrays.copyOf(q.next, sigma); nq.cnt = q.cnt; nq.step = p.step + 1; nq.pre = q.pre; q.pre = nq; np.pre = nq; while (p != null && p.next[w]==(q)) { p.next[w] = nq; p = p.pre; } } } } } class InputReader{ private final static int BUF_SZ = 65536; BufferedReader in; StringTokenizer tokenizer; public InputReader(InputStream in) { super(); this.in = new BufferedReader(new InputStreamReader(in),BUF_SZ); tokenizer = new StringTokenizer(""); } public String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4\naa\nabcd\nccc\nabcc"]
5 seconds
["5\n10\n14\n12"]
NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
Java 8
standard input
[ "string suffix structures" ]
a9c5516f0430f01d2d000241e5ac69ed
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
2,300
Output T lines, every line containing one number – the answer to the corresponding test case.
standard output
PASSED
d6fab0d787501d6d60973dcdf7496830
train_000.jsonl
1526395500
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
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); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { int n,max=Integer.MAX_VALUE; int a[][]; HashMap<Integer,Integer> hm[][]; int[] get(int no){ int x[]=new int[4]; int p=0; while(no!=0){ x[p++]=no%10;no/=10; }Arrays.sort(x); return x; } int get(int[] x){ int ans=0,m=1; for(int i=0;i<4;i++){ ans+=x[i]*m;m*=10; }return ans; } int[] m(int no,int v){ int a[]=get(no);boolean is=false; for(int i=0;i<4;i++){ if(a[i]==0){ is=true;a[i]=v;break; } } if(!is)return null; Arrays.sort(a); return a; } int rec(int id,int pe,int x[]){ if(x==null)return max/2; int no=get(x),min=max; if(hm[id][pe].containsKey(no))return hm[id][pe].get(no); if(pe==n){ int v1=0,pr=id; for(int i=0;i<4;i++){ if(x[i]==0)continue; v1+=Math.abs(x[i]-pr)+1;pr=x[i]; } int v2=0;pr=id; for(int i=3;i>=0;i--){ if(x[i]==0)continue; v2+=Math.abs(x[i]-pr)+1;pr=x[i]; } // System.out.println(v1+" "+v2); hm[id][pe].put(no,Math.min(v1,v2)); return hm[id][pe].get(no); } int v[]=new int[4],p; for(int i=0;i<(1<<4);i++){ v[0]=v[1]=v[2]=v[3]=0;p=0; int got=no,m=1; for(int j=0;j<4;j++){ if(((i>>j)&1)!=0){ v[p++]=x[j];got-=x[j]*m; }m*=10; } if(a[pe+1][0]>=id){ int pr=id,val=0; for(int z=0;z<p;z++){ if(v[z]==0)continue; val+=Math.abs(v[z]-pr)+1;pr=v[z]; } val+=Math.abs(a[pe+1][0]-pr)+1; // System.out.println(val+" "+got); min=Math.min(min,rec(a[pe+1][0],pe+1,m(got,a[pe+1][1]))+val); }else{ int pr=id,val=0; for(int z=p-1;z>=0;z--){ if(v[z]==0)continue; val+=Math.abs(v[z]-pr)+1;pr=v[z]; } val+=Math.abs(a[pe+1][0]-pr)+1; min=Math.min(min,rec(a[pe+1][0],pe+1,m(got,a[pe+1][1]))+val); } } hm[id][pe].put(no,min); return hm[id][pe].get(no); } public void solve(int testNumber, InputReader in, PrintWriter out) { n=in.nextInt(); a=new int[n+1][n+1]; for(int i=1;i<=n;i++){ a[i][0]=in.nextInt();a[i][1]=in.nextInt(); } hm=new HashMap[10][n+1]; for(int i=0;i<10;i++){ for(int j=0;j<=n;j++)hm[i][j]=new HashMap<>(); } out.print(rec(1,0,get(0))); } // int ja[][],from[],to[],c[]; // void make(int n,int m,InputReader in){ // ja=new int[n+1][];from=new int[m];to=new int[m];c=new int[n+1]; // for(int i=0;i<m;i++){ // from[i]=in.nextInt();to[i]=in.nextInt(); // c[from[i]]++;c[to[i]]++; // } // for(int i=1;i<=n;i++){ // ja[i]=new int[c[i]];c[i]=0; // } // for(int i=0;i<m;i++){ // ja[from[i]][c[from[i]]++]=to[i]; // ja[to[i]][c[to[i]]++]=from[i]; // } // } // int[] radixSort(int[] f){ return radixSort(f, f.length); } // int[] radixSort(int[] f, int n) // { // int[] to = new int[n]; // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++){ // to[b[f[i]&0xffff]++] = f[i]; // } // int[] d = f; f = to;to = d; // } // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; // int[] d = f; f = to;to = d; // } // return f; // } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n3 5\n5 3", "2\n5 3\n3 5"]
3 seconds
["10", "12"]
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
Java 8
standard input
[ "dp", "graphs", "shortest paths" ]
f6be5319ad3733d07a8ffd089fc44c71
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
2,400
Print a single integer — the minimal possible time in seconds.
standard output
PASSED
e5c61a33d879c9c1e98a0f979f36fcc9
train_000.jsonl
1526395500
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
256 megabytes
import java.util.*; import java.io.*; public class P983C { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int[][][] dp = new int[2][10000][10]; for (int[][] d : dp) for (int[] arr : d) Arrays.fill(arr, Integer.MAX_VALUE); dp[0][0][1] = 0; for (int i = 0; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); int[] digits = new int[4]; for (int w = 9000; w >= 0; w -= 1000) { digits[0] = w / 1000; int k1 = w / 10; for (int x = 900; x >= k1; x -= 100) { digits[1] = x / 100; int k2 = x / 10; for (int y = 90; y >= k2; y -= 10) { digits[2] = y / 10; for (int z = 9; z >= digits[2]; z--) { digits[3] = z; int dest = w + x + y + z; for (int f = 1; f <= 9; f++) { if (dp[0][dest][f] == Integer.MAX_VALUE) continue; // drop off int temp = dest; boolean[] been = new boolean[10]; while (temp > 0) { int r = temp % 10; temp /= 10; if (been[r]) continue; been[r] = true; int next = 0; for (int num : digits) { if (num != r) { next *= 10; next += num; } } dp[0][next][r] = Math.min(dp[0][next][r], dp[0][dest][f] + Math.abs(f - r)); } // pick up if (dest < 1000) { int next = 0; boolean added = false; for (int num : digits) { if (num != a) { if (num > b && !added) { next *= 10; next += b; added = true; } next *= 10; next += num; } } if (!added) { next *= 10; next += b; } dp[1][next][a] = Math.min(dp[1][next][a], dp[0][dest][f] + Math.abs(f - a)); } } } } } } dp[0] = dp[1]; dp[1] = new int[10000][10]; for (int[] arr : dp[1]) Arrays.fill(arr, Integer.MAX_VALUE); } int[] digits = new int[4]; for (int w = 9000; w >= 0; w -= 1000) { digits[0] = w / 1000; int k1 = w / 10; for (int x = 900; x >= k1; x -= 100) { digits[1] = x / 100; int k2 = x / 10; for (int y = 90; y >= k2; y -= 10) { digits[2] = y / 10; for (int z = 9; z >= digits[2]; z--) { digits[3] = z; int dest = w + x + y + z; for (int f = 1; f <= 9; f++) { if (dp[0][dest][f] == Integer.MAX_VALUE) continue; // drop off int temp = dest; boolean[] been = new boolean[10]; while (temp > 0) { int r = temp % 10; temp /= 10; if (been[r]) continue; been[r] = true; int next = 0; for (int num : digits) { if (num != r) { next *= 10; next += num; } } dp[0][next][r] = Math.min(dp[0][next][r], dp[0][dest][f] + Math.abs(f - r)); } } } } } } int min = Integer.MAX_VALUE; for (int f = 1; f <= 9; f++) min = Math.min(min, dp[0][0][f]); min += n * 2; System.out.println(min); } /** * Source: Matt Fontaine */ public static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["2\n3 5\n5 3", "2\n5 3\n3 5"]
3 seconds
["10", "12"]
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
Java 8
standard input
[ "dp", "graphs", "shortest paths" ]
f6be5319ad3733d07a8ffd089fc44c71
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
2,400
Print a single integer — the minimal possible time in seconds.
standard output