exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
4389a3e98842104d2eb189d42f0663df
train_001.jsonl
1586700300
You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.
256 megabytes
import java.util.*; import java.io.*; public class watermelon { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("input.txt")); int tests = Integer.parseInt(br.readLine()); for(int t = 0; t<tests; t++) { int n = Integer.parseInt(br.readLine()); int[]arr = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i<n; i++) { arr[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(arr); int[]sol = new int[n]; int forward = 1; int cur = 0; for(int i = 0; i<n; i++) { if(i==0) { cur = (n-1)/2; } sol[i]=arr[cur]; cur+=(i+1)*forward; forward*=-1; } for(int i=0; i<sol.length-1; i++) { System.out.print(sol[i]+" "); } System.out.println(sol[sol.length-1]); } } }
Java
["2\n6\n5 -2 4 8 6 5\n4\n8 1 4 2"]
1 second
["5 5 4 6 8 -2\n1 2 4 8"]
NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".
Java 11
standard input
[ "constructive algorithms", "sortings" ]
3c8bfd3199a9435cfbdee1daaacbd1b3
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).
1,200
For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.
standard output
PASSED
7f80d5595dd8dbb123c57f40986dd587
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Andy Phan */ public class b { public static void main(String[] args) { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); VecL[] a = new VecL[n]; for(int i = 0; i < n; i++) a[i] = new VecL(in.nextInt(), in.nextInt()); TreeMap<Long, SegL> upper = new TreeMap<>(); TreeMap<Long, SegL> lower = new TreeMap<>(); for(int i = 0; i < n; i++) { SegL seg = new SegL(a[i], a[(i+1)%n]); if(a[i].x < a[(i+1)%n].x || (a[i].x == a[(i+1)%n].x && a[i].y > a[(i+1)%n].y)) upper.put(a[i].x, seg); else lower.put(a[i].x, seg); } int m = in.nextInt(); for(int i = 0; i < m; i++) { VecL vec = new VecL(in.nextInt(), in.nextInt()); Map.Entry<Long, SegL> upperE = upper.floorEntry(vec.x); Map.Entry<Long, SegL> lowerE = lower.ceilingEntry(vec.x); if(upperE == null || upperE.getValue().side(vec) != -1) { System.out.println("NO"); return; } if(lowerE == null || lowerE.getValue().side(vec) != -1) { System.out.println("NO"); return; } } System.out.println("YES"); out.close(); } static class SegL { VecL from, to, dir; public SegL(VecL from, VecL to) { this.from = from; this.to = to; dir = to.sub(from); } //check if the segment contains the point public boolean contains(VecL p) { VecL d = p.sub(from); if (d.cross(dir) != 0) { return false; } long dot = d.dot(dir); return dot >= 0 && dot <= dir.mag2(); } //(assuming I go left to right) //returns: // 1 if point is above me // 0 if point is on me // -1 if point is below me public long side(VecL o) { long cross = dir.cross(o.sub(from)); return cross == 0 ? 0 : cross / Math.abs(cross); } //returns true if this segl intersects the other, including at endpoints //note: returns false if the two segments lie on the same line public boolean intersects(SegL o) { return side(o.from) != side(o.to) && o.side(from) != o.side(to); } public String toString() { return from + " -> " + to; } //# static long gcd(long a, long b) { a = Math.abs(a); b = Math.abs(b); return b == 0 ? a : gcd(b, a % b); } //$ //returns the lattice point of intersection or null if it is nonlattice or does not exist public VecL latticeIntersect(SegL o) { if (!intersects(o)) { return null; } long dirGCD = gcd(dir.x, dir.y), oDirGCD = gcd(o.dir.x, o.dir.y); VecL va= new VecL(dir.x / dirGCD, dir.y / dirGCD), vb = new VecL(o.dir.x / oDirGCD, o.dir.y / oDirGCD); if (va.x < 0 && va.y < 0) { va.x *= -1; va.y *= -1; } if (vb.x < 0 && vb.y < 0) { vb.x *= -1; vb.y *= -1; } if (va.equals(vb)) { return null; } long bottomScalar = va.x / gcd(va.x, va.y); long topScalar = va.y / gcd(va.x, va.y); long t2Scalar = -bottomScalar * vb.y + topScalar * vb.x; long t2Ans = bottomScalar * (o.from.y - from.y) - topScalar * (o.from.x - from.x); if (t2Ans % t2Scalar != 0) { return null; } long t2 = t2Ans / t2Scalar; return new VecL(t2 * vb.x + o.from.x, t2 * vb.y + o.from.y); } } static class VecL implements Comparable<VecL> { long x, y; public VecL(long x, long y) { this.x = x; this.y = y; } public VecL add(VecL o) { return new VecL(x + o.x, y + o.y); } public VecL sub(VecL o) { return new VecL(x - o.x, y - o.y); } public VecL scale(long s) { return new VecL(x * s, y * s); } public long dot(VecL o) { return x * o.x + y * o.y; } public long cross(VecL o) { return x * o.y - y * o.x; } public long mag2() { return dot(this); } public VecL rot90() { return new VecL(-y, x); } public VecL rot270() { return new VecL(y, -x); } public String toString() { return "(" + x + ", " + y + ")"; } public int hashCode() { return Long.hashCode(x << 13 ^ (y * 57)); } public boolean equals(Object oo) { VecL o = (VecL) oo; return x == o.x && y == o.y; } public int compareTo(VecL o) { if (x != o.x) { return Long.compare(x, o.x); } return Long.compare(y, o.y); } //origin->q1, axes-> quadrant in ccw direction public int quadrant() { if (x == 0 || y == 0) { if (y == 0) { if (x >= 0) { return 1; } else { return 3; } } else if (y >= 0) { return 2; } else { return 4; } } if (x > 0) { if (y > 0) { return 1; } else { return 4; } } else if (y > 0) { return 2; } else { return 3; } } public int radialCompare(VecL o) { if (quadrant() == o.quadrant()) { return -Long.signum(cross(o)); } return Integer.compare(quadrant(), o.quadrant()); } } static class FS { BufferedReader in; StringTokenizer token; public FS(InputStream str) { in = new BufferedReader(new InputStreamReader(str)); } public String next() { if (token == null || !token.hasMoreElements()) { try { token = new StringTokenizer(in.readLine()); } catch (IOException ex) { } return next(); } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
fb819efdcff70ddb33c51483d2b4802f
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.StringTokenizer; public class Polygons { static final double EPS = 1e-9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); HashSet<Point> big = new HashSet<>(); ArrayList<Point> all = new ArrayList<>(); for(int i=0;i<n;i++) { int x =sc.nextInt(); int y = sc.nextInt(); Point p = new Point(x, y); big.add(p); all.add(p); } int m =sc.nextInt(); for(int i=0;i<m;i++) { int x =sc.nextInt(); int y = sc.nextInt(); Point p = new Point(x, y); all.add(p); } Point [] g = convexHull(all); for(int i=0;i<g.length;i++) { if(!big.contains(g[i])) { System.out.println("NO"); return; } // System.out.println(g[i].x+" "+g[i].y); } System.out.println("YES"); } static double distToLine(Point p, Point a,Point b) { if(a.compareTo(b)==0) return p.dist(a); Vector ap = new Vector(a, p), ab = new Vector(a, b); double u =ap.dot(ab)/ab.norm2(); Point c = a.translate(ab.scale(u)); return p.dist(c); } public static class Vector { double x, y; Vector(Point a, Point b) { x = b.x - a.x; y = b.y - a.y; } Vector(double a, double b) { x = a; y = b; } // Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } } static double area ( Point[] x ) { double tot=0; for(int i=0;i+1<x.length;i++) { tot+=x[i].x*x[i+1].y-x[i+1].x*x[i].y; } return tot/2.0; } static Point [] convexHull (ArrayList<Point> points) { int n = points.size(); Collections.sort(points); Point [] ans = new Point [n<<1]; int size=0; int start=0; for(int i=0;i<n;i++) { Point p = points.get(i); while(size-start>=2&&!ccw(ans[size-2],ans[size-1],p)) size--; ans[size++]=p; } start = --size; for(int i=n-1;i>=0;i--) { Point p = points.get(i); while(size-start>=2&&!ccw(ans[size-2],ans[size-1],p)) size--; ans[size++]=p; } return Arrays.copyOf(ans,size); } static Point [] cutPolygon(Point [] pts , Point a, Point b) { Point[] ans = new Point[pts.length<<1]; Line l = new Line(a, b); Vector v = new Vector(a, b); int size=0; for(int i=0;i<pts.length;i++) { double left1 = v.cross(new Vector(a, pts[i])); double left2 =i ==pts.length-1?0:v.cross(new Vector(a, pts[i+1])); if(left1 + EPS>0) { ans[size++]=pts[i]; } if(left1*left2+EPS<0) ans[size++]=l.intersect(new Line(pts[i], pts[i+1])); } if(size!=0&& ans[0]!=ans[size-1]) ans[size++]=ans[0]; return Arrays.copyOf(ans, size); } static boolean ccw(Point a, Point b, Point c) { return new Vector(a, b).cross(new Vector(a, c)) > -EPS; } static class Point implements Comparable<Point> { double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point o) { if(o.x!=x) return (int)(x-o.x); return (int)(y-o.y); } public double dist(Point p) { return Math.sqrt((x - p.x)*(x - p.x) +(y - p.y)*(y - p.y)); } Point translate(Vector v) { return new Point(x + v.x , y + v.y); } } static class Line { double a, b, c; Line(Point p, Point q) { if(Math.abs(p.x - q.x) < EPS) { a = 1.0; b = 0.0; c = -p.x; } else { a = (q.y - p.y) / (p.x - q.x); b = 1.0; c = - a * p.x - p.y; } } boolean parallel(Line l) { return Math.abs(l.a - a) < EPS && Math.abs(l.b - b) < EPS; } Point intersect(Line l) { if(parallel(l)) return null; double x = (b * l.c - c * l.b) /(a * l.b - b * l.a); double y; if(Math.abs(b) > EPS) y = - a * x - c; else y = - l.a * x - l.c; return new Point(x, y); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
5a6a6f14bf572414ed5acb11d679c014
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF_166_B_POLYGONS { static final double EPS = 10e-10; static double angle(Point a, Point o, Point b) { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Point[] p = new Point[n ]; for (int i = 0; i < n; i++) p[i] = new Point(sc.nextDouble(), sc.nextDouble()); int m = sc.nextInt(); while (m-- > 0) if (!inPolygon(p, new Point(sc.nextDouble(), sc.nextDouble()))) { System.out.println("NO"); return; } System.out.println("YES"); } static boolean inPolygon(Point[] p, Point target) { int low = 1; int high = p.length - 1; boolean ccw = crossPrdouct(p[0], p[1], p[p.length - 1]) == 1; if(!ccw) { int temp = low ; low = high; high = temp; } if(!(crossPrdouct(p[0], p[low], target ) > 0 && crossPrdouct(p[0], p[high] ,target ) < 0)) return false; while (Math.abs(low - high) > 1) { int mid = (low + high) /2; if (crossPrdouct(p[0], p[mid], target) > 0) low = mid; else high = mid; } return crossPrdouct(target, p[low],p[high] ) > 0; } static double crossPrdouct(Point p, Point q, Point r) { Vector pq = new Vector(p, q); Vector pr = new Vector(p, r); double cross = pq.cross(pr); if(Math.abs(cross) > EPS) return cross > 0 ? 1 : -1; return 0; } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } // s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Point implements Comparable<Point> { static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if (Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } static double sq(double x) { return x * x; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
ea0a24a73d447b6370be2eb2e0bc9a17
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.net.Inet4Address; import java.util.*; public class B { private static final Comparator<int[]> cmp = new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { for(int i = 0 ; i < a.length ; i++) if(a[i] != b[i]) return Integer.compare(a[i], b[i]); return 0; } }; public static void main(String [] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int n = Integer.parseInt(reader.readLine()); int [][] A = new int[n][2]; for(int i = 0 ; i < n ; i++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int x = Integer.parseInt(tokenizer.nextToken()); int y = Integer.parseInt(tokenizer.nextToken()); A[i] = new int[] {x, y}; } int m = Integer.parseInt(reader.readLine()); int [][] B = new int[m][2]; for(int i = 0 ; i < m ; i++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int x = Integer.parseInt(tokenizer.nextToken()); int y = Integer.parseInt(tokenizer.nextToken()); B[i] = new int[] {x, y}; } int [][] all = new int[n+m][2]; for(int i = 0 ; i < n ; i++) { all[i][0] = A[i][0]; all[i][1] = A[i][1]; } for(int i = n ; i < n+m ; i++) { all[i][0] = B[i-n][0]; all[i][1] = B[i-n][1]; } int size = n+m; Arrays.sort(all, cmp); int [] up = new int[size]; int upLen = 0; up[upLen++] = 0; for(int i = 1 ; i < size ; i++) { while(upLen > 1 && ccw(all[up[upLen-2]], all[up[upLen-1]], all[i]) > 0) upLen--; up[upLen++] = i; } int [] down = new int[size]; int downLen = 0; down[downLen++] = 0; for(int i = 1 ; i < size ; i++) { while(downLen > 1 && ccw(all[down[downLen - 2]], all[down[downLen - 1]], all[i]) < 0) downLen--; down[downLen++] = i; } int convexSize = upLen + downLen - 2; if(convexSize != n) { writer.println("NO"); } else { Arrays.sort(A, cmp); boolean find = false; for(int i = 0 ; i < upLen ; i++) { int idx = Arrays.binarySearch(A, all[up[i]], cmp); if(idx < 0) find = true; } for(int i = 0 ; i < downLen ; i++) { int idx = Arrays.binarySearch(A, all[down[i]], cmp); if(idx < 0) find = true; } if(find) writer.println("NO"); else writer.println("YES"); } writer.flush(); writer.close(); } private static long ccw(int[] o, int[] p1, int[] p2) { long x1 = p1[0] - o[0]; long y1 = p1[1] - o[1]; long x2 = p2[0] - o[0]; long y2 = p2[1] - o[1]; return x1*y2 - x2*y1; } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
25c8d672b046777713560e4dfdfd9ce5
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Polygons { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); Point [] A = new Point [n]; for(int i=0;i<n;++i) A[i] = new Point(sc.nextDouble(),sc.nextDouble(),true); int m =sc.nextInt(); Point [] B = new Point[m]; for(int i=0;i<m;++i) B[i] = new Point(sc.nextDouble(),sc.nextDouble(),false); Point [] tot = new Point[n+m]; for(int i=0;i<n+m;++i) if(i<n) tot[i] = A[i]; else tot[i] = B[i-n]; // tot[n+m] = tot[0]; Point [] pts = convexHull(tot); for(int i=0;i<pts.length;++i) if(!pts[i].A) { System.out.println("NO"); return; } System.out.println("YES"); } static Point[] convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } // if(size < 0) size = 0 for empty set of points return Arrays.copyOf(ans, size); } static class Point implements Comparable<Point> { static final double EPS = 1e-9; double x, y; boolean A; Point(double a, double b,boolean k) { x = a; y = b; A=k; } public String toString() { return x + " " + y; } public int compareTo(Point p) { if (Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if (Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } // returns true if it is on the line defined by a and b boolean onLine(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } boolean onSegment(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return onRay(a, b) && onRay(b, a); } // returns true if it is on the ray whose start point is a and passes through b boolean onRay(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); // implement equals() } // returns true if it is on the left side of Line pq // add EPS to LHS if on-line points are accepted static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) + EPS > 0; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } // Another way: find closest point and calculate the distance between it and p } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } // s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
0b3208504e5ed75b639141c301554f8e
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import sun.print.resources.serviceui; import java.io.*; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point[] A = new Point[n]; for(int i = 0; i < n; ++i) A[n - i - 1] = new Point(sc.nextInt(), sc.nextInt()); A = fixPolygon(A); boolean good = true; int m = sc.nextInt(); while(m-->0) good &= inPolygon(new Point(sc.nextInt(), sc.nextInt()), A); out.println(good ? "YES" : "NO"); out.close(); } static Point[] fixPolygon(Point[] A) { int best = 0; for(int i = 1; i < A.length; ++i) if(A[i].x < A[best].x || A[i].x == A[best].x && A[i].y < A[best].y) best = i; Point[] B = new Point[A.length]; int j = 0; for(int i = best; i < A.length; ++i) B[j++] = A[i]; for(int i = 0; i < best; ++i) B[j++] = A[i]; return B; } static class Point { int x, y; Point(int a, int b) { x = a; y = b; } } static boolean inPolygon(Point p, Point[] g) // O(log n), g[0] is the smallest point { if(g[0].x == p.x && g[0].y == p.y) return false; Point base = g[0]; int belowPoint = -1, lo = 1, hi = g.length - 1; while(lo <= hi) { int mid = (lo + hi) / 2; if(onLeft(base, g[mid], p, true)) { belowPoint = mid; lo = mid + 1; } else hi = mid - 1; } if(belowPoint == -1) return false; int abovePoint = belowPoint == g.length - 1 ? belowPoint : belowPoint + 1; return inside(base, g[belowPoint], g[abovePoint], p, belowPoint > 1, false, abovePoint < g.length - 1); } static boolean inside(Point a, Point b, Point c, Point p, boolean x, boolean y, boolean z) { return onLeft(a, b, p, x) && onLeft(b, c, p, y) && onLeft(c, a, p, z); } static boolean onLeft(Point p, Point q, Point r, boolean f) { if(f) return 1l * (q.x - p.x) * (r.y - p.y) - 1l * (q.y - p.y) * (r.x - p.x) >= 0; return 1l * (q.x - p.x) * (r.y - p.y) - 1l * (q.y - p.y) * (r.x - p.x) > 0; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
12eab6d126764b9c347fd8d3caf7de87
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import sun.print.resources.serviceui; import java.io.*; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point[] A = new Point[n]; for(int i = 0; i < n; ++i) A[i] = new Point(sc.nextInt(), sc.nextInt()); boolean good = true; int m = sc.nextInt(); while(m-->0) good &= inPolygon(new Point(sc.nextInt(), sc.nextInt()), A); out.println(good ? "YES" : "NO"); out.close(); } static class Point { int x, y; Point(int a, int b) { x = a; y = b; } } static boolean inPolygon(Point p, Point[] g) // O(log n) { int a = 1, b = g.length - 1; if(cross(g[0], g[b], g[a]) > 0) { a ^= b; b ^= a; a ^= b; } // for clockwise polygons if(cross(g[0], g[b], p) >= 0 || cross(g[0], g[a], p) <= 0) return false; while(Math.abs(a - b) > 1) { int c = (a + b) / 2; if(cross(g[0], g[c], p) > 0) a = c; else b = c; } return cross(g[a], g[b], p) > 0; } static long cross(Point p, Point q, Point r) { return 1l * (q.x - p.x) * (r.y - p.y) - 1l * (q.y - p.y) * (r.x - p.x); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
3af8c5d2c101c4e9438e034b44ef8384
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P166B { int n; long [][] a, va; boolean checkIntern(long x, long y) { for (int i = 0; i < n; i++) { if ((va[i][0] * (y - a[i][1]) - va[i][1] * (x - a[i][0])) >= 0) { return false; } } return true; } public void run() throws Exception { n = nextInt(); a = new long [n][]; va = new long [n][]; for (int i = 0; i < n; i++) { a[i] = readLong(2); } for (int i = 0; i < n; i++) { va[i] = new long [] {a[(i + 1) % n][0] - a[i][0], a[(i + 1) % n][1] - a[i][1]}; } TreeMap<Long, TreeSet<Long>> b = new TreeMap(); for (int i = nextInt(); i > 0; i--) { long [] xy = readLong(2); TreeSet<Long> bx = b.getOrDefault(xy[0], new TreeSet()); bx.add(xy[1]); b.put(xy[0], bx); } if (!checkIntern(b.firstKey(), b.firstEntry().getValue().first()) || !checkIntern(b.firstKey(), b.firstEntry().getValue().last()) || !checkIntern(b.lastKey(), b.lastEntry().getValue().first()) || !checkIntern(b.lastKey(), b.lastEntry().getValue().last())) { println("NO"); return; } println("YES"); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P166B().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
412ad48c0005ef3c967bb341e91881ee
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Polygons { static final double EPS = 1e-15; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); Point [] A = new Point [n]; for(int i=0;i<n;++i) A[i] = new Point(sc.nextDouble(),sc.nextDouble(),true); int m =sc.nextInt(); Point [] B = new Point[4*m]; for(int i=0;i<4*m;i+=4) { double x = sc.nextDouble();double y = sc.nextDouble(); B[i] = new Point(x+EPS,y+EPS,false); B[i+1] = new Point(x+EPS,y-EPS,false); B[i+2] = new Point(x-EPS,y+EPS,false); B[i+3] = new Point(x-EPS,y-EPS,false); } Point [] tot = new Point[n+4*m+1]; for(int i=0;i<n+4*m;++i) if(i<n) tot[i] = A[i]; else tot[i] = B[i-n];//System.err.println(Arrays.toString(tot)); tot[n+4*m] = tot[0]; Point [] pts = convexHull(tot);//System.err.println(Arrays.toString(pts)); for(int i=0;i<pts.length;++i) if(!pts[i].A) { System.out.println("NO"); return; } System.out.println("YES"); } static Point[] convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p) ) --size; ans[size++] = p; } // if(size < 0) size = 0 for empty set of points return Arrays.copyOf(ans, size); } static class Point implements Comparable<Point> { double x, y; boolean A; Point(double a, double b,boolean k) { x = a; y = b; A=k; } public String toString() { return x + " " + y; } public int compareTo(Point p) { if (Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if (Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } // returns true if it is on the line defined by a and b boolean onLine(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } boolean onSegment(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return onRay(a, b) && onRay(b, a); } // returns true if it is on the ray whose start point is a and passes through b boolean onRay(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); // implement equals() } // returns true if it is on the left side of Line pq // add EPS to LHS if on-line points are accepted static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } // Another way: find closest point and calculate the distance between it and p } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } // s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
8626f6ce0a58b8d54e01b694382e3566
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.StringTokenizer; public class Polygons { static Point[] convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } if(size < 0) size = 0; //for empty set of points return (Arrays.copyOf(ans, size)); } public static final double EPS =1e-9; public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = s.nextInt(); ArrayList<Point> p = new ArrayList<>(); Point[] A = new Point[n]; for (int i = 0; i < n; i++) { Point pt = new Point(s.nextDouble(), s.nextDouble()); p.add(pt); A[i] = pt; } int m = s.nextInt(); for (int i = 0; i < m; i++) { Point pt = new Point(s.nextDouble(), s.nextDouble()); p.add(pt); } Point[] tmp = new Point[p.size()]; for (int i = 0; i < p.size(); i++) { tmp[i] = p.get(i); } //System.out.println(tmp.length +"THE FUCK"); Point[] output = convexHull(tmp); HashSet<Point> check = new HashSet<>(); for (int i = 0; i < output.length; i++) { check.add(output[i]); } // for (int i = 0; i < A.length; i++) { // System.out.println(A[i].x +" "+ A[i].y); // } // System.out.println("blalalala"); // for (int i = 0; i < output.length; i++) { // System.out.println(output[i].x +" "+ output[i].y); // } if(check.size() != A.length){ pw.println("NO"); pw.flush(); return; } for (int i = 0; i < A.length; i++) { if(!check.contains(A[i])) { pw.println("NO"); pw.flush(); return; } } pw.println("YES"); pw.flush(); } static class Point implements Comparable<Point>{ double x,y; public Point(double x,double y){ this.x = x; this.y = y; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > -EPS; } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput() throws InterruptedException {Thread.sleep(4000);} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
8acb91e6afb7c70090731dd83fcf7e5a
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class B { Reader in; PrintWriter out; String TEST_INPUT=""; void solve(){ int n=in.nextInt(); Vect[] A = new Vect[n]; for(int i=0; i<n; i++) A[i]=new Vect(in.nextLong(),in.nextLong()); int m=in.nextInt(); for(int i=0; i<m; i++){ Vect p = new Vect(in.nextLong(),in.nextLong()); if(!inside(p,A)){ out.print("NO"); return; } } out.print("YES"); } boolean inside(Vect p, Vect[] A){ int ini=1, fin=A.length-2; while(ini<=fin){ int mid = (ini+fin)>>1; Vect a = A[mid].subs(A[0]), b=A[mid+1].subs(A[mid]), c=A[0].subs(A[mid+1]); Vect op = p.subs(A[0]), midp = p.subs(A[mid]), midp1 = p.subs(A[mid+1]); if(b.prodvectZ(midp)>=0) return false; if(a.prodvectZ(op)>=0) fin=mid-1; else if(c.prodvectZ(midp1)>=0) ini=mid+1; else return true; } if(fin<=0 || ini>=A.length-1) return false; return true; } class Vect{ public long x,y; Vect(long x, long y){ this.x=x; this.y=y; } public Vect subs(Vect o){ return new Vect(x-o.x,y-o.y); } public long prodvectZ(Vect o){ return (x*o.y - y*o.x); } } void run(){ in=(TEST_INPUT.isEmpty() ? new Reader(): new Reader(TEST_INPUT)); out=new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args){ new B().run(); } class Reader{ BufferedReader br; StringTokenizer st; public Reader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String s){ br = new BufferedReader(new StringReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace();} } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
6bcddcff5b6f0c805a634eb91e1aad9a
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
// package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static final double EPS = 1e-9; static Point [] p; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point [] p = new Point[n]; for (int i = 0; i < n; ++i) { p[i] = new Point(sc.nextDouble(), sc.nextDouble()); } int m = sc.nextInt(); boolean inside = true; while(m-->0){ inside &= inside(p, new Point(sc.nextDouble(), sc.nextDouble())); } out.println(inside?"YES":"NO"); out.flush(); out.close(); } static boolean inside(Point [] p, Point q){ int lo = 1, hi = p.length-1; if(ccw(p[0], p[lo], q) || ccw(p[hi], p[0], q)) return false; for (int i = 0; i < 100; ++i) { int mid = (lo+hi)/2; if(ccw(p[0], p[mid], q)){ hi = mid; } else lo = mid; } return !ccw(p[lo], p[hi], q); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) >= 0; } static class Point { double x, y; Point(double a, double b) { x = a; y = b; } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
49fa1e69b7f18911eae00d3247aff61b
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class polygons { public static void main (String[] args) throws IOException, InterruptedException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter o=new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); Point[] outside = new Point [n]; for(int i=0;i<n;i++){ StringTokenizer st = new StringTokenizer(in.readLine()); double x= Double.parseDouble(st.nextToken()); double y= Double.parseDouble(st.nextToken()); outside[i]= new Point(x, y); } int m = Integer.parseInt(in.readLine()); Point[] p = new Point [n+m]; HashSet<Point> inside = new HashSet<>(); int i=0; for(;i<n;i++){ p[i]= outside[i]; } for(;i<n+m;i++){ StringTokenizer st = new StringTokenizer(in.readLine()); double x= Double.parseDouble(st.nextToken()); double y= Double.parseDouble(st.nextToken()); Point s= new Point(x, y); p[i]=s; inside.add(s); } Polygon poly = (new Polygon(p)).convexHull(p); boolean flag =true; for(int j=0;j<poly.g.length;j++){ if(inside.contains(poly.g[j])) flag=false; } if(flag) o.println("YES"); else o.println("NO"); o.flush(); o.close(); } } class Polygon { // Cases to handle: collinear points, polygons with n < 3 static final double EPS = 1e-9; Point[] g; //first point = last point, counter-clockwise representation Polygon(Point[] o) { g = o; } double perimeter() { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) sum += g[i].dist(g[i+1]); return sum; } double area() //clockwise/anti-clockwise check, for convex/concave polygons { double area = 0.0; for(int i = 0; i < g.length - 1; ++i) area += g[i].x * g[i+1].y - g[i].y * g[i+1].x; return Math.abs(area) / 2.0; //negative value in case of clockwise } boolean inside(Point p) //for convex/concave polygons - winding number algorithm { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) { double angle = Point.angle(g[i], p, g[i+1]); if((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i+1])) return true; if(Point.ccw(p, g[i], g[i+1])) sum += angle; else sum -= angle; } return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; //abs makes it work for clockwise } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static Polygon convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } // if(size < 0) size = 0 for empty set of points return new Polygon(Arrays.copyOf(ans, size)); } } class Point implements Comparable<Point>{ static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > -EPS; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } // Another way: find closest point and calculate the distance between it and p } class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
34d2f161e4666abd4c94196bde06cc77
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class CF { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point[] g = new Point[n]; boolean ans = true; for (int i = 0; i < n; i++) g[i] = new Point(sc.nextDouble(), sc.nextDouble()); int m = sc.nextInt(); while (m-- > 0) { ans &= insidelogn(new Point(sc.nextDouble(), sc.nextDouble()), g); } out.println(ans ? "YES" : "NO"); // System.out.println(insidelogn(new Point(-10, 0), g)); out.flush(); out.close(); } public static boolean insidelogn(Point p, Point[] g) { int a = g.length - 1; int b = 1; if (ccw(g[0], g[b], p) >= 0 || !Point.ccw(g[0], g[a], p)) return false; while (Math.abs(a - b) > 1) { int c = (a + b) / 2; // System.out.println(c + " " + Point.ccw(g[0], g[c], p)); if (Point.ccw(g[0], g[c], p)) a = c; else b = c; // System.out.println(a + " " + b); } return Point.ccw(g[a], g[b], p); } static double ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)); } public static class Point implements Comparable<Point> { static final double EPS = 1e-9; double x, y; @Override public String toString() { return (int) x + " " + (int) y; } Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if (Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if (Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } // for integer points and rotation by 90 (counterclockwise) : swap x and y, // negate x Point rotate(double theta, Point p) // rotate around p { Vector v = new Vector(p, new Point(0, 0)); return translate(v).rotate(theta).translate(v.reverse()); } Point translate(Vector v) { return new Point(x + v.x, y + v.y); } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } // returns true if it is on the line defined by a and b boolean onLine(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } boolean onSegment(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return onRay(a, b) && onRay(b, a); } // returns true if it is on the ray whose start point is a and passes through b boolean onRay(Point a, Point b) { if (a.compareTo(b) == 0) return compareTo(a) == 0; return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); // implement equals() } // returns true if it is on the left side of Line pq // add EPS to LHS if on-line points are accepted static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static double distToLine(Point p, Point a, Point b) // distance between point p and a line defined by points a, // b (a != b) { if (a.compareTo(b) == 0) return p.dist(a); // formula: c = a + u * ab Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); Point c = a.translate(ab.scale(u)); return p.dist(c); } } public static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } // s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
58e623c8872a89f4892bdc0b3f7b972e
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
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.Stack; import java.util.List; import java.util.Vector; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ReaderFastIO in = new ReaderFastIO(inputStream); PrintWriter out = new PrintWriter(outputStream); BPolygons solver = new BPolygons(); solver.solve(1, in, out); out.close(); } static class BPolygons { public void solve(int testNumber, ReaderFastIO in, PrintWriter out) { int n = in.nextInt(); List<Point2D> polygonA = new Vector<>(); for (int i = 0; i < n; i++) { polygonA.add(new Point2D(in.nextInt(), in.nextInt())); } int m = in.nextInt(); List<Point2D> polygonB = new Vector<>(); for (int i = 0; i < m; i++) { polygonB.add(new Point2D(in.nextInt(), in.nextInt())); } Vector<Point2D> polygonC = new Vector<>(); for (Point2D p : polygonB) { if (p.onSegment(polygonA.get(0), polygonA.get(polygonA.size() - 1))) { polygonC.add(p); } else if (p.onSegment(polygonA.get(0), polygonA.get(1))) { polygonC.add(p); } } polygonB.addAll(polygonA); GrahamScan gs = new GrahamScan(polygonB.toArray(new Point2D[]{})); for (Point2D p : gs.hull()) { polygonC.add(p); } if (polygonA.size() != polygonC.size()) { out.println("NO"); return; } Collections.sort(polygonA, (x, y) -> x.compareTo(y)); Collections.sort(polygonC, (x, y) -> x.compareTo(y)); boolean ok = true; for (int i = 0; i < n; i++) { if (polygonA.get(i).equals(polygonC.get(i)) == false) { ok = false; } } out.println(ok == true ? "YES" : "NO"); } } static class ReaderFastIO { BufferedReader br; StringTokenizer st; public ReaderFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } public ReaderFastIO(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); } 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()); } } static class GrahamScan { private Stack<Point2D> hull = new Stack<Point2D>(); public GrahamScan(Point2D[] points) { if (points == null) throw new IllegalArgumentException("argument is null"); if (points.length == 0) throw new IllegalArgumentException("array is of length 0"); // defensive copy int n = points.length; Point2D[] a = new Point2D[n]; for (int i = 0; i < n; i++) { if (points[i] == null) throw new IllegalArgumentException("points[" + i + "] is null"); a[i] = points[i]; } // preprocess so that a[0] has lowest y-coordinate; break ties by x-coordinate // a[0] is an extreme point of the convex hull // (alternatively, could do easily in linear time) Arrays.sort(a); // sort by polar angle with respect to base point a[0], // breaking ties by distance to a[0] Arrays.sort(a, 1, n, a[0].polarOrder()); hull.push(a[0]); // a[0] is first extreme point hull.push(a[1]); // Graham scan; note that a[n-1] is extreme point different from a[0] for (int i = 2; i < n; i++) { Point2D top = hull.pop(); while (Point2D.ccw(hull.peek(), top, a[i]) < 0) { top = hull.pop(); } hull.push(top); hull.push(a[i]); } assert isConvex(); } public Iterable<Point2D> hull() { Stack<Point2D> s = new Stack<Point2D>(); for (Point2D p : hull) s.push(p); return s; } private boolean isConvex() { int n = hull.size(); if (n <= 2) return true; Point2D[] points = new Point2D[n]; int k = 0; for (Point2D p : hull()) { points[k++] = p; } for (int i = 0; i < n; i++) { if (Point2D.ccw(points[i], points[(i + 1) % n], points[(i + 2) % n]) <= 0) { return false; } } return true; } } static final class Point2D implements Comparable<Point2D> { private final double x; private final double y; public Point2D(double x, double y) { if (Double.isInfinite(x) || Double.isInfinite(y)) throw new IllegalArgumentException("Coordinates must be finite"); if (Double.isNaN(x) || Double.isNaN(y)) throw new IllegalArgumentException("Coordinates cannot be NaN"); if (x == 0.0) this.x = 0.0; // convert -0.0 to +0.0 else this.x = x; if (y == 0.0) this.y = 0.0; // convert -0.0 to +0.0 else this.y = y; } public static int ccw(Point2D a, Point2D b, Point2D c) { double area2 = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); if (area2 < 0) return -1; else if (area2 > 0) return +1; else return 0; } public int compareTo(Point2D that) { if (this.y < that.y) return -1; if (this.y > that.y) return +1; if (this.x < that.x) return -1; if (this.x > that.x) return +1; return 0; } public Comparator<Point2D> polarOrder() { return new PolarOrder(); } public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Point2D that = (Point2D) other; return this.x == that.x && this.y == that.y; } public String toString() { return "(" + x + ", " + y + ")"; } public int hashCode() { int hashX = ((Double) x).hashCode(); int hashY = ((Double) y).hashCode(); return 31 * hashX + hashY; } public boolean onSegment(Point2D pi, Point2D pj) { if (ccw(this, pi, pj) != 0) return false; if (Math.min(pi.x, pj.x) <= x && x <= Math.max(pi.x, pj.x) && Math.min(pi.y, pj.y) <= y && y <= Math.max(pi.y, pj.y)) return true; return false; } private class PolarOrder implements Comparator<Point2D> { public int compare(Point2D q1, Point2D q2) { double dx1 = q1.x - x; double dy1 = q1.y - y; double dx2 = q2.x - x; double dy2 = q2.y - y; if (dy1 >= 0 && dy2 < 0) return -1; // q1 above; q2 below else if (dy2 >= 0 && dy1 < 0) return +1; // q1 below; q2 above else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal if (dx1 >= 0 && dx2 < 0) return -1; else if (dx2 >= 0 && dx1 < 0) return +1; else return 0; } else return -ccw(Point2D.this, q1, q2); // both above or below // Note: ccw() recomputes dx1, dy1, dx2, and dy2 } } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
38ea1bf9b3007454fccaf585d7fd1028
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Point { long X; long Y; Point(long X, long Y){ this.X =X; this.Y =Y; } } static long orient(Point p, Point q, Point r) { long val = (((q.Y - p.Y) * (r.X - q.X)) - ((q.X - p.X) * (r.Y - q.Y))); if (val == 0L) return val; return (val > 0L)? 1L: 2L; } static boolean segment(Point p, Point q, Point r) { if (q.X <= Math.max(p.X, r.X) && q.X >= Math.min(p.X, r.X) && q.Y <= Math.max(p.Y, r.Y) && q.Y >= Math.min(p.Y, r.Y)){ return true; } return false; } static long cross(Point a, Point b){ return ((a.X*b.Y)-(b.X*a.Y)); } static Point minus(Point a,Point b){ return new Point((a.X-b.X),(a.Y-b.Y)); } static boolean inside(int N,Point[] polygon,Point P){ if((orient(polygon[0],P,polygon[1])==0L && segment(polygon[0],P,polygon[1])) || ((orient(polygon[0],P,polygon[N-1])==0L && segment(polygon[0],P,polygon[N-1])))){ return false; } Point p1 = minus(polygon[N-1],polygon[0]); Point p2 = minus(polygon[1],polygon[0]); Point pVector = minus(P,polygon[0]); if(!(cross(p1, pVector)<=0 && cross(p2,pVector)>=0)){ return false; } int L = 0, R = N - 1; while(R-L>1){ int mid = (L + R)/2; Point current = minus(polygon[mid],polygon[0]); if(cross(current,pVector) >= 0){ L = mid; }else{ R = mid; } } if(L <(N-1)){ if(orient(polygon[L],P,polygon[L+1])==0L && segment(polygon[L],P,polygon[L+1])){ return false; } Point side = minus(polygon[L+1],polygon[L]); Point pointSideVector = minus(P,polygon[L]); return (cross(side,pointSideVector) >=0); } return true; } public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); Point[] points=new Point[n]; for(int i=n-1;i>=0;i--){ st=new StringTokenizer(br.readLine()); points[i]=new Point(Long.parseLong(st.nextToken()),Long.parseLong(st.nextToken())); } int q=Integer.parseInt(br.readLine()); int count=0; for(int i=0;i<q;i++){ st=new StringTokenizer(br.readLine()); if(inside(n,points,new Point(Long.parseLong(st.nextToken()),Long.parseLong(st.nextToken())))){ count++; } } if(count==q){ pw.println("YES"); }else { pw.println("NO"); } pw.close(); } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
ad9113100eac53cec5dc374a4090797c
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class B { static final double INF = 1e9, EPS = 1e-9; static class Point implements Comparable<Point> { double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point other) { if (Math.abs(x - other.x) > EPS) return x > other.x ? 1 : -1; if (Math.abs(y - other.y) > EPS) return y > other.y ? 1 : -1; return 0; } public static int ccw(Point a, Point b, Point c) { return (int) ((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)); } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } double cross(Vector v) { return x * v.y - y * v.x; } } static class Polygon { Point[] g; Polygon(Point[] o) { g = o; } static Point[] convexHull(Point[] points) { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n << 1]; int size = 0, start = 0; for (int i = 0; i < n; i++) { Point p = points[i]; while (size - start >= 2 && (Point.ccw(ans[size - 2], ans[size - 1], p) < 0)) size--; ans[size++] = p; } start = --size; for (int i = n - 1; i >= 0; i--) { Point p = points[i]; while (size - start >= 2 && ((Point.ccw(ans[size - 2], ans[size - 1], p) < 0))) size--; ans[size++] = p; } return Arrays.copyOf(ans, size); } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); Point[] p = new Point[N + 1]; for (int i = N; i > 0; i--) p[i] = new Point(sc.nextInt(), sc.nextInt()); p[0] = p[N]; int M = sc.nextInt(); Point[] q = new Point[M + 1]; TreeSet<Point> set = new TreeSet<Point>(); for (int i = M; i > 0; i--) { q[i] = new Point(sc.nextInt(), sc.nextInt()); set.add(new Point(q[i].x, q[i].y)); } q[0] = q[M]; Point[] all = new Point[N + M]; for (int i = 1; i <= N; i++) all[i - 1] = p[i]; for (int i = 1; i <= M; i++) all[N + i - 1] = q[i]; Point[] Hull = Polygon.convexHull(all); for (Point P : Hull) { if (set.contains(P)) { System.out.println("NO"); return; } } System.out.println("YES"); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
1f94bd643cfe38149bbb4e71acb14606
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Point point[] = new Point[n]; for (int i = 0; i < n; i++) point[i] = new Point(s.nextInt(), s.nextInt()); PointInPolygonQuery pointInPolygonQuery = new PointInPolygonQuery(point); boolean ans = true; int m = s.nextInt(); while (m-- > 0) { Point q = new Point(s.nextInt(), s.nextInt()); ans &= pointInPolygonQuery.query(q) > 0; } System.out.println(ans ? "YES" : "NO"); /*Polygon[] p = new Polygon[n]; for (int i = 0; i < n; i++) { int c = s.nextInt(); Point[] h = new Point[c]; for (int j = 0; j < c; j++) { h[j] = new Point(s.nextInt(), s.nextInt()); } p[i] = new Polygon(h); } Polygon ans = p[0]; for (int i = 1; i < n; i++) { // System.out.println(ans); // System.out.println("Adding -- > " + p[i].toString()); ans = ans.intersection(p[i]); } // System.out.println(ans); System.out.println(Math.abs(ans.area() * 1.0 / 2));*/ } public static class Polygon { @Override public String toString() { return "Polygon [p=" + Arrays.deepToString(p) + "]"; } int n; Point p[]; public Polygon(Point[] p) { this.n = p.length; this.p = p; } public int next(int i) { return i == n - 1 ? 0 : (i + 1); } public int prev(int i) { return i == 0 ? (n - 1) : (i - 1); } public long area() { long area = 0; for (int i = 0; i < n; ++i) area += p[i].x * (p[prev(i)].y - p[next(i)].y); return area; } public Polygon intersection(Polygon o) { Point[] newpoints = new Point[n * o.n + n + o.n]; int ptr = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < o.n; j++) { Point p1 = p[i]; Point p2 = p[next(i)]; Point p3 = o.p[j]; Point p4 = o.p[o.next(j)]; Line l1 = new Line(p1, p2); Line l2 = new Line(p3, p4); Point xx = l1.intersect(l2); if (xx != null) { if (xx.x >= Math.min(p1.x, p2.x) && xx.x <= Math.max(p1.x, p2.x) && xx.y >= Math.min(p1.y, p2.y) && xx.y <= Math.max(p1.y, p2.y)) { if (xx.x >= Math.min(p3.x, p4.x) && xx.x <= Math.max(p3.x, p4.x) && xx.y >= Math.min(p3.y, p4.y) && xx.y <= Math.max(p3.y, p4.y)) { if (xx.x == p1.x && xx.y == p1.y) continue; if (xx.x == p2.x && xx.y == p2.y) continue; if (xx.x == p3.x && xx.y == p3.y) continue; if (xx.x == p4.x && xx.y == p4.y) continue; newpoints[ptr++] = xx; } } } } } // System.out.println(Arrays.deepToString(Arrays.copyOf(newpoints, ptr))); PointInPolygonQuery pq = new PointInPolygonQuery(p); for (int i = 0; i < o.n; i++) { if (pq.query(o.p[i]) >= 0) { newpoints[ptr++] = o.p[i]; } } // System.out.println(Arrays.deepToString(Arrays.copyOf(newpoints, ptr))); pq = new PointInPolygonQuery(o.p); for (int i = 0; i < n; i++) { if (pq.query(p[i]) >= 0) { newpoints[ptr++] = p[i]; } } // System.out.println(Arrays.deepToString(Arrays.copyOf(newpoints, ptr))); return new Polygon(new PointInPolygonQuery(Arrays.copyOf(newpoints, ptr)).total); } } static class PointInPolygonQuery { Point[] upper, lower, total; double minx = Integer.MAX_VALUE; double maxx = Integer.MIN_VALUE; double miny1 = Integer.MAX_VALUE; double miny2 = Integer.MIN_VALUE; double maxy1 = Integer.MAX_VALUE; double maxy2 = Integer.MIN_VALUE; PointInPolygonQuery(Point[] p) { findHull(p); total = new Point[upper.length + lower.length - 2]; int ptr = 0; for (int i = 0; i < lower.length - 1; i++) { total[ptr++] = lower[i]; } for (int i = 0; i < upper.length - 1; i++) { total[ptr++] = upper[i]; } total = Arrays.copyOf(total, ptr); for (int i = 0; i < (upper.length + 1) / 2; i++) { Point temp = upper[i]; upper[i] = upper[upper.length - 1 - i]; upper[upper.length - 1 - i] = temp; } for (int i = 0; i < total.length; i++) { if (total[i].x < minx) { minx = total[i].x; } if (total[i].x > maxx) { maxx = total[i].x; } } for (int i = 0; i < total.length; i++) { if (total[i].x == minx) { miny1 = Math.min(miny1, total[i].y); miny2 = Math.max(miny2, total[i].y); } if (total[i].x == maxx) { maxy1 = Math.min(maxy1, total[i].y); maxy2 = Math.max(maxy2, total[i].y); } } // System.out.println("Upper " + Arrays.deepToString(upper)); // System.out.println("Lower " + Arrays.deepToString(lower)); // System.out.println("minx " + minx + " " + miny1 + " "+ miny2); // System.out.println("maxx " + maxx + " " + maxy1 + " "+ maxy2); } int query(Point p) { if (p.x < upper[0].x || p.x > upper[upper.length - 1].x) return -1; if (p.x == minx) { if (p.y >= miny1 && p.y <= miny2) { return 0; } else return -1; } if (p.x == maxx) { if (p.y >= maxy1 && p.y <= maxy2) { return 0; } else return -1; } return -1 * above(lower, p) * above(upper, p); } int above(Point[] hull, Point p) { int lo = 0, hi = hull.length - 1; while (true) { int mid = (lo + hi) / 2; if (p.x >= hull[mid].x && p.x <= hull[mid + 1].x) { // System.out.println("Query for " + p +" :: > " + hull[mid] +" "+ hull[mid + 1]); return (int) Math.signum(hull[mid + 1].minus(hull[mid]).cross(p.minus(hull[mid]))); } else if (p.x >= hull[mid].x) lo = mid; else hi = mid; } } void findHull(Point[] points) { int n = points.length; Arrays.sort(points); lower = new Point[2 * n]; upper = new Point[2 * n]; int k = 0, start = 0; for (int i = 0; i < n; i++) { Point p = points[i]; while (k - start >= 2 && p.minus(lower[k - 1]).cross(p.minus(lower[k - 2])) >= 0) k--; lower[k++] = p; } lower = Arrays.copyOf(lower, k); start = 0; k = 0; for (int i = n - 1; i >= 0; i--) { Point p = points[i]; while (k - start >= 2 && p.minus(upper[k - 1]).cross(p.minus(upper[k - 2])) >= 0) k--; upper[k++] = p; } upper = Arrays.copyOf(upper, k); } } static public class Point implements Comparable<Point> { double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public int compareTo(Point o) { if (x != o.x) return Double.compare(x, o.x); return Double.compare(y, o.y); } public double dot(Point o) { return x * 1L * o.x + y * 1L * o.y; } public double cross(Point o) { return x * 1L * o.y - y * 1L * o.x; } public Point minus(Point p) { return new Point(x - p.x, y - p.y); } // slope of a-c > a-b public static double ccw(Point a, Point b, Point c) { return (c.y - a.y) * 1L * (b.x - a.x) - (b.y - a.y) * 1L * (c.x - a.x); } @Override public String toString() { return "[" + x + ", " + y + "]"; } public double dist(Point o) { double X = x - o.x; double Y = y - o.y; return Math.sqrt(X * X + Y * Y); } } static public class Line { public double a, b, c; public static final double EPS = 1e-9; public Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public Line(double m, double c) { new Line(m, -1.0, c); } public Line(Point p1, Point p2) { a = +(p1.y - p2.y); b = -(p1.x - p2.x); c = p1.x * p2.y - p2.x * p1.y; } public boolean isParallel(Line line) { return (a * line.b - b * line.a) < EPS; } public boolean isPerpendicular(Line line) { return sign(a * line.a + b * line.b) == 0; } public Point intersect(Line line) { double d = a * line.b - line.a * b; if (sign(d) == 0) return null; double x = -(c * line.b - line.c * b) / d; double y = -(a * line.c - line.a * c) / d; return new Point(x, y); } public Point dist(Point a) { double m = -1 / slope(); double c = a.y - m * a.x; return intersect(new Line(m, c)); } public double slope() { return sign(-a / b) == 0 ? 0 : (-a / b); } public static int sign(double a) { return a < -EPS ? -1 : a > EPS ? 1 : 0; } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
f38147e340d34418962e416ca0247aa6
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class Point { int x, y; Point (int xx, int yy) { x = xx; y = yy; } } static boolean inside (Point[] A, Point p) { if (!cw(A[0], A[1], p) || !cw (A[A.length - 1], A[0], p)) return false; int lo = 1, hi = A.length - 1; for (int cnt = 0; cnt <= 20; cnt++) { int mid = lo + ((hi - lo) >> 1); if (cw(A[0], A[mid], p)) { lo = mid; } else hi = mid; } return cw (A[lo], A[lo + 1], p); } static boolean cw (Point a, Point b, Point p) { long x1 = b.x - a.x , y1 = b.y - a.y; long x2 = p.x - b.x , y2 = p.y - b.y; return x1 * y2 - x2 * y1 < 0; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point[] A = new Point[n]; for (int i = 0; i < n; i++) A[i] = new Point (sc.nextInt(), sc.nextInt()); int m = sc.nextInt(); boolean ok = true; for (int i = 0; i < m; i++) { ok &= inside (A, new Point(sc.nextInt(), sc.nextInt())); } out.println(ok ? "YES" : "NO"); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
d2f6a26c933466b8c39f725a13afed84
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; @SuppressWarnings("unchecked") public class B { public static void main(String[] args) { new B(); } int aLen,bLen; Vector a[],b[]; final double EPSILON = 1E-12; B() { Scanner in = new Scanner(System.in); aLen = in.nextInt(); a = new Vector[aLen]; for(int i=0;i<aLen;i++){ a[i] = new Vector(in.nextLong(),in.nextLong()); } bLen = in.nextInt(); b = new Vector[bLen]; for(int i=0;i<bLen;i++) b[i] = new Vector(in.nextLong(),in.nextLong()); ArrayList<Vector> hull = getHull(new ArrayList<Vector>(Arrays.asList(a)),true); //System.out.println(hull); //System.out.println(Arrays.toString(hullHi)); //System.out.println(Arrays.toString(hullLo)); for(Vector p : b){ if(!pointInPolygon(p)){ System.out.println("NO"); return; } } System.out.println("YES"); in.close(); } //STRICTLY inside boolean pointInPolygon(Vector p){ return above(hullHi,p)==-1 && above(hullLo,p)==1; } // 1 = above // 0 = on //-1 = below //-2 = N/A //FIXME: See case 42 below. A point is on the range of a vertical line (which it's ON) //and a horizontal line (which it's ABOVE). This method finds the horizontal line first and returns //the wrong answer. int above(Vector[] points, Vector p){ int lo = 0, hi = points.length-2; //System.out.println(p); if(p.x<points[0].x || p.x>points[points.length-1].x) return -2; while(lo<=hi){ int mid = lo + (hi-lo)/2; Vector a = points[mid], b = points[mid+1]; if(p.x<a.x){ //look further to the left hi = mid-1; continue; }else if(p.x>b.x){ //look further to the right lo = mid+1; continue; }else{ //Wow! We're in range! //System.out.printf("In range! %s--%s\n",a,b); if(a.x==b.x){ //vertical line. This can happen on the left or rightmost edges. if(a.x==points[0].x) //keep going until you find an appropriate horizontal-er line. lo = mid+1; else hi = mid-1; // if(p.y > Math.max(a.y,b.y)) // return 1; // else if(p.y < Math.min(a.y, b.y)) // return -1; // else // return 0; continue; } //the extreme edges can consist of a series of vertical lines. //These checks treat them as one straight line, as well as //making sure p isn't directly above the adjacent horizontal-er edge. if (mid != 0 && a.x == p.x && a.x == points[0].x) { b = a; a = points[0]; } if (mid != points.length - 1 && p.x == b.x && b.x == points[points.length - 1].x) { a = b; b = points[points.length - 1]; } //default check if(a.x==b.x){ //uh-oh! if(p.y>a.y && p.y>b.y) return 1; if(p.y<a.y && p.y<b.y) return -1; else return 0; } double lineY = a.y + (double)(b.y-a.y)/(b.x-a.x) * (p.x-a.x); //lineY may be NaN. That's NOT OK //System.out.printf("lineY=%.10f\n",lineY); if(Math.abs(lineY-p.y)<=EPSILON) return 0; else if(p.y > lineY) return 1; else return -1; } } return -2; } // static int above(Vector[] vs, Vector p) { // int n = vs.length; // if (p.x < vs[0].x || p.x > vs[n - 1].x) return -2; // int min = 0, max = n - 2, mid; // while (min <= max) { // mid = (min + max) / 2; // Vector a = vs[mid], b = vs[mid + 1]; // if (p.x < a.x) max = mid - 1; // else if (p.x > b.x) min = mid + 1; // else if (a.x == b.x) { // if (a.x == vs[0].x) min = mid + 1; // else max = mid - 1; // } else { // if (mid != 0 && a.x == p.x && a.x == vs[0].x) { // b = a; a = vs[0]; // } // if (mid != n - 1 && b.x == p.x && b.x == vs[n - 1].x) { // a = b; b = vs[n - 1]; // } // if (p.y > a.y && p.y > b.y) return 1; // if (p.y < a.y && p.y < b.y) return -1; // return Long.signum(b.sub(a).cross(p.sub(a))); // } // } // return -2; // } static Vector hullLo[], hullHi[]; //Thanks, Tim!! static ArrayList<Vector> getHull(ArrayList<Vector> ps, boolean shouldCalc) { ArrayList<Vector> s = (ArrayList<Vector>) ps.clone(); Collections.sort(s); int n = s.size(), j = 2, k = 2; if (s.size() < 3) { return s; } Vector[] lo = new Vector[n], up = new Vector[n]; lo[0] = s.get(0); lo[1] = s.get(1); for (int i = 2; i < n; i++) { Vector p = s.get(i); while (j > 1 && !rightTurn(lo[j - 2], lo [j - 1], p)) j--; lo[j++] = p; } up[0] = s.get(n - 1); up[1] = s.get(n - 2); for (int i = n - 3; i >= 0; i--) { Vector p = s.get(i); while (k > 1 && !rightTurn(up[k - 2], up[k - 1], p)) k--; up[k++] = p; } ArrayList<Vector> res = new ArrayList<>(); for (int i = 0; i < k; i++) res.add(up[i]); for (int i = 1; i < j - 1; i++) res.add(lo[i]); if (shouldCalc) { hullHi = new Vector[k]; hullLo = new Vector[j]; for (int i = 0; i < k; i++) hullHi[i] = up[k - i - 1]; for (int i = 0; i < j; i++) hullLo[i] = lo[i]; } return res; } static boolean rightTurn(Vector a, Vector b, Vector c) { return b.sub(a).cross(c.sub(a)) > 0; } static class Vector implements Comparable<Vector> { long x, y; public Vector(long xx, long yy) { x = xx; y = yy; } public Vector sub(Vector v) { return new Vector(x - v.x, y - v.y); } public Vector add(Vector v) { return new Vector(x + v.x, y + v.y); } public long cross(Vector v) { return x * v.y - y * v.x; } public long dot(Vector v) { return x * v.x + y * v.y; } public long mag2() { return dot(this); } public int compareTo(Vector v) { if (x == v.x) return Long.compare(y, v.y); return Long.compare(x, v.x); } public String toString() { return String.format("(%d, %d)", x, y); } } } /* 6 -2 1 0 3 3 3 4 1 3 -2 2 -2 4 0 1 2 2 3 1 1 0 5 1 2 4 2 3 -3 -2 -2 -2 1 4 0 1 1 2 4 1 2 -1 5 -1 2 2 3 4 1 3 -2 0 -3 5 1 0 1 1 3 1 5 -1 2 -1 CASE 42: 4 -10 -10 -10 10 10 10 10 -10 3 10 0 2 2 1 5 CASE 52: 3 -1000000000 0 1000000000 1 1000000000 -2 3 -999999999 0 999999999 0 999999999 -1 */
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
07cac11fc83969074b17e388b4869ef9
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; @SuppressWarnings("unchecked") public class B { public static void main(String[] args) { new B(); } int aLen,bLen; Vector a[],b[]; final double EPSILON = 1E-12; //this value was too big, and got a wrong answer... B() { Scanner in = new Scanner(System.in); aLen = in.nextInt(); a = new Vector[aLen]; for(int i=0;i<aLen;i++){ a[i] = new Vector(in.nextLong(),in.nextLong()); } bLen = in.nextInt(); b = new Vector[bLen]; for(int i=0;i<bLen;i++) b[i] = new Vector(in.nextLong(),in.nextLong()); ArrayList<Vector> hull = getHull(new ArrayList<Vector>(Arrays.asList(a)),true); //System.out.println(hull); //System.out.println(Arrays.toString(hullHi)); //System.out.println(Arrays.toString(hullLo)); for(Vector p : b){ if(!pointInPolygon(p)){ System.out.println("NO"); return; } } System.out.println("YES"); in.close(); } //STRICTLY inside boolean pointInPolygon(Vector p){ return above(hullHi,p)==-1 && above(hullLo,p)==1; } // 1 = above // 0 = on //-1 = below //-2 = N/A //FIXME: See case 42 below. A point is on the range of a vertical line (which it's ON) //and a horizontal line (which it's ABOVE). This method finds the horizontal line first and returns //the wrong answer. int above(Vector[] points, Vector p){ int lo = 0, hi = points.length-2; //System.out.println(p); if(p.x<points[0].x || p.x>points[points.length-1].x) return -2; while(lo<=hi){ int mid = lo + (hi-lo)/2; Vector a = points[mid], b = points[mid+1]; if(p.x<a.x){ //look further to the left hi = mid-1; continue; }else if(p.x>b.x){ //look further to the right lo = mid+1; continue; }else{ //Wow! We're in range! //System.out.printf("In range! %s--%s\n",a,b); if(a.x==b.x){ //vertical line. This can happen on the left or rightmost edges. if(a.x==points[0].x) //keep going until you find an appropriate horizontal-er line. lo = mid+1; else hi = mid-1; // if(p.y > Math.max(a.y,b.y)) // return 1; // else if(p.y < Math.min(a.y, b.y)) // return -1; // else // return 0; continue; } //the extreme edges can consist of a series of vertical lines. //These checks treat them as one straight line, as well as //making sure p isn't directly above the adjacent horizontal-er edge. if (mid != 0 && a.x == p.x && a.x == points[0].x) { b = a; a = points[0]; } if (mid != points.length - 1 && p.x == b.x && b.x == points[points.length - 1].x) { a = b; b = points[points.length - 1]; } //default check if(a.x==b.x){ //uh-oh! if(p.y>a.y && p.y>b.y) return 1; if(p.y<a.y && p.y<b.y) return -1; else return 0; } return Long.signum(b.sub(a).cross(p.sub(a))); } } return -2; } // static int above(Vector[] vs, Vector p) { // int n = vs.length; // if (p.x < vs[0].x || p.x > vs[n - 1].x) return -2; // int min = 0, max = n - 2, mid; // while (min <= max) { // mid = (min + max) / 2; // Vector a = vs[mid], b = vs[mid + 1]; // if (p.x < a.x) max = mid - 1; // else if (p.x > b.x) min = mid + 1; // else if (a.x == b.x) { // if (a.x == vs[0].x) min = mid + 1; // else max = mid - 1; // } else { // if (mid != 0 && a.x == p.x && a.x == vs[0].x) { // b = a; a = vs[0]; // } // if (mid != n - 1 && b.x == p.x && b.x == vs[n - 1].x) { // a = b; b = vs[n - 1]; // } // if (p.y > a.y && p.y > b.y) return 1; // if (p.y < a.y && p.y < b.y) return -1; // return Long.signum(b.sub(a).cross(p.sub(a))); // } // } // return -2; // } static Vector hullLo[], hullHi[]; //Thanks, Tim!! static ArrayList<Vector> getHull(ArrayList<Vector> ps, boolean shouldCalc) { ArrayList<Vector> s = (ArrayList<Vector>) ps.clone(); Collections.sort(s); int n = s.size(), j = 2, k = 2; if (s.size() < 3) { return s; } Vector[] lo = new Vector[n], up = new Vector[n]; lo[0] = s.get(0); lo[1] = s.get(1); for (int i = 2; i < n; i++) { Vector p = s.get(i); while (j > 1 && !rightTurn(lo[j - 2], lo [j - 1], p)) j--; lo[j++] = p; } up[0] = s.get(n - 1); up[1] = s.get(n - 2); for (int i = n - 3; i >= 0; i--) { Vector p = s.get(i); while (k > 1 && !rightTurn(up[k - 2], up[k - 1], p)) k--; up[k++] = p; } ArrayList<Vector> res = new ArrayList<>(); for (int i = 0; i < k; i++) res.add(up[i]); for (int i = 1; i < j - 1; i++) res.add(lo[i]); if (shouldCalc) { hullHi = new Vector[k]; hullLo = new Vector[j]; for (int i = 0; i < k; i++) hullHi[i] = up[k - i - 1]; for (int i = 0; i < j; i++) hullLo[i] = lo[i]; } return res; } static boolean rightTurn(Vector a, Vector b, Vector c) { return b.sub(a).cross(c.sub(a)) > 0; } static class Vector implements Comparable<Vector> { long x, y; public Vector(long xx, long yy) { x = xx; y = yy; } public Vector sub(Vector v) { return new Vector(x - v.x, y - v.y); } public Vector add(Vector v) { return new Vector(x + v.x, y + v.y); } public long cross(Vector v) { return x * v.y - y * v.x; } public long dot(Vector v) { return x * v.x + y * v.y; } public long mag2() { return dot(this); } public int compareTo(Vector v) { if (x == v.x) return Long.compare(y, v.y); return Long.compare(x, v.x); } public String toString() { return String.format("(%d, %d)", x, y); } } } /* 6 -2 1 0 3 3 3 4 1 3 -2 2 -2 4 0 1 2 2 3 1 1 0 5 1 2 4 2 3 -3 -2 -2 -2 1 4 0 1 1 2 4 1 2 -1 5 -1 2 2 3 4 1 3 -2 0 -3 5 1 0 1 1 3 1 5 -1 2 -1 CASE 42: 4 -10 -10 -10 10 10 10 10 -10 3 10 0 2 2 1 5 CASE 52: 3 -1000000000 0 1000000000 1 1000000000 -2 3 -999999999 0 999999999 0 999999999 -1 */
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
85bf5efa26bd592e788055baa3bd5eb9
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
//package maths; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class PointInPolygon { static boolean pointInPolygon(Point p,Point []pts) { int l,r,mid; int n=pts.length; for( l=1,r=n-1,mid=(l+r)/2;l<r;mid=(l+r)/2) { Vec a=new Vec(pts[0],pts[mid]),b=new Vec(pts[0],p); if(a.cross(b)>=0) r=mid; else l=mid+1; } Vec a = new Vec(pts[0],pts[n-1]),b=new Vec(pts[0],p); Vec aa=new Vec(pts[l],pts[l-1]),bb=new Vec(pts[l],p); return!(l<2||a.cross(b)<=0 ||aa.cross(bb)<=0); } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Point []pts=new Point [n]; for(int i=0;i<n;i++) pts[i]=new Point(sc.nextInt(),sc.nextInt()); int m=sc.nextInt(); boolean ok=true; while(m-->0) ok&=pointInPolygon(new Point(sc.nextInt(),sc.nextInt()), pts); System.out.println(ok?"YES":"NO"); } static class Point { int x,y; Point (int a,int b){ x=a; y=b; } } static class Vec{ int x,y; Vec(Point a,Point b){ x=b.x-a.x; y=b.y-a.y; } int cross(Vec other) { long a=x*1L*other.y; long b=y*1L*other.x; return a>b?1:a==b?0:-1; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in){ br=new BufferedReader (new InputStreamReader(in)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer (br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
3fc867afb53b9c7af93008205fabfdef
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
//package maths; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class PointInPolygon { static boolean inside(Point [] p, Point q){ int lo = 1, hi = p.length-1; if(ccw(p[0], p[lo], q) || ccw(p[hi], p[0], q)) return false; for (int i = 0; i < 100; ++i) { int mid = (lo+hi)/2; if(ccw(p[0], p[mid], q)){ hi = mid; } else lo = mid; } return !ccw(p[lo], p[hi], q); } static boolean ccw(Point p, Point q, Point r) { return new Vec(p, q).cross(new Vec(p, r)) >= 0; } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Point []pts=new Point [n]; for(int i=0;i<n;i++) pts[i]=new Point(sc.nextInt(),sc.nextInt()); int m=sc.nextInt(); boolean ok=true; while(m-->0) ok &=inside(pts,new Point(sc.nextInt(),sc.nextInt())); System.out.println(ok?"YES":"NO"); } static class Point { int x,y; Point (int a,int b){ x=a; y=b; } } static class Vec{ int x,y; Vec(Point a,Point b){ x=b.x-a.x; y=b.y-a.y; } int cross(Vec other) { long a=x*1L*other.y; long b=y*1L*other.x; return a>b?1:a==b?0:-1; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in){ br=new BufferedReader (new InputStreamReader(in)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer (br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
37e494d7181cdf2bda0250a8d8858a61
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
//package maths; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class PointInPolygon { /*static boolean pointInPolygon(Point p,Point []pts) { int n=pts.length-1; int l=0 } */ public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Point []pts=new Point [n+1]; for(int i=1;i<=n;i++) pts[i]=new Point(sc.nextInt(),sc.nextInt()); int m=sc.nextInt(); int l,r,mid; String ans="YES"; while(m-->0) { int x=sc.nextInt(),y=sc.nextInt(); Point p=new Point(x,y); for( l=2,r=n,mid=(l+r)/2;l<r;mid=(l+r)/2) { Vec a=new Vec(pts[1],pts[mid]),b=new Vec(pts[1],p); if(a.cross(b)>=0) r=mid; else l=mid+1; } Vec a = new Vec(pts[1],pts[n]),b=new Vec(pts[1],p); Vec aa=new Vec(pts[l],pts[l-1]),bb=new Vec(pts[l],p); if(l<3||a.cross(b)<=0 ||aa.cross(bb)<=0) ans="NO"; } System.out.println(ans); } static class Point { int x,y; Point (int a,int b){ x=a; y=b; } } static class Vec{ int x,y; Vec(Point a,Point b){ x=b.x-a.x; y=b.y-a.y; } int cross(Vec other) { long a=x*1L*other.y; long b=y*1L*other.x; return a>b?1:a==b?0:-1; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in){ br=new BufferedReader (new InputStreamReader(in)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer (br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
da04c5f07d5ea34e970e44472115b0ca
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class A { static Point[] convexHull(Point[] points) { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } return Arrays.copyOf(ans, size); } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); Point []a=new Point[n]; for(int i=0;i<n;i++) a[i]=new Point(sc.nextInt(),sc.nextInt()); int m=sc.nextInt(); Point []b=new Point[m]; for(int i=0;i<m;i++) b[i]=new Point(sc.nextInt(),sc.nextInt()); Point []c=new Point [n+m]; for(int i=0;i<n;i++) c[i]=a[i]; for(int i=0;i<m;i++) c[i+n]=b[i]; Point []hull=convexHull(c); Arrays.sort(b); boolean found=false; for(Point p:hull) { int lo=0; int hi=m-1; while(lo<=hi && !found) { int mid=(lo+hi)/2; if(b[mid].x>p.x) hi=mid-1; else if(b[mid].x<p.x) lo=mid+1; else if(b[mid].y>p.y) hi=mid-1; else if(b[mid].y<p.y) lo=mid+1; else found=true; } if(found) break; } pw.println(found?"NO":"YES"); pw.close(); } static class Point implements Comparable<Point> { int x,y; Point(int d,int e) { x=d;y=e; } int cross(Point p) { long ans=x*1L*p.y-y*1L*p.x; return ans>0?1:ans==0?0:-1; } boolean onSegment(Point p1,Point p2) { return x>=Math.min(p1.x, p2.x) && x<=Math.max(p1.x, p2.x) &&y>=Math.min(p1.y, p2.y) && y<=Math.max(p1.y, p2.y); } public String toString() { return x+" "+y; } public double dist(Point p) { double dx=x-p.x; double dy=y-p.y; return Math.sqrt(dx*dx+dy*dy); } public int compareTo(Point other) { if(x!=other.x) return x-other.x; return y-other.y; } static Point toVec(Point a,Point b) { return new Point(b.x-a.x,b.y-a.y); } static double angle(Point a,Point b,Point c) { Point x=toVec(b,a),y=toVec(b,c); double dot=x.x*y.x + x.y*y.y; double d=b.dist(a)*b.dist(c); return Math.acos(dot/d); } static boolean ccw(Point p,Point q,Point r) { return toVec(p,q).cross(toVec(p,r))!=-1; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
175ae1613d47b8b891cd5056055b7aa9
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.util.Scanner; public class CF166B_Polygons { final static double EPS=1e-9; static Point g[]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); g = new Point[n]; for(int i=0;i<n;i++){ g[i]=new Point(sc.nextInt(), sc.nextInt()); } int m = sc.nextInt(); boolean f = true; while(m-->0){ f&=inside(new Point(sc.nextInt(), sc.nextInt())); } if(f) System.out.println("YES"); else System.out.println("NO"); } private static boolean inside( Point p) { // TODO Auto-generated method stub int lo = 1, hi = g.length-1; if(ccw(g[0], g[lo], p) || ccw(g[hi], g[0], p)) return false; for (int i = 0; i < 100; ++i) { int mid = (lo+hi)/2; if(ccw(g[0], g[mid], p)){ hi = mid; } else lo = mid; } return !ccw(g[lo], g[hi], p); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) >= 0; } static class Point{ int x,y; public Point(int x, int y) { this.x = x; this.y = y; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this( b.x- a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
0d2978fea48f7bf68ac06197bf9dee17
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TC_a { static final double EPS = 1e-9; static class Point { long x,y; public Point(int x,int y) { this.x = x; this.y = y; } public String toString() { return "("+x+","+y+")"; } boolean onLine(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } } static class Vector { long x,y; public Vector(Point a, Point b) { x = a.x - b.x; y = a.y - b.y; } public long cross(Vector c) { return this.x*c.y - this.y*c.x; } } static long side(long x1, long y1, long x2, long y2,long x, long y){ return 1L*(y2 - y1)*1L*(x - x1) + 1L*(-x2 + x1)*(y - y1); } static boolean pointInTriangle(long x1, long y1, long x2, long y2, long x3, long y3, long x, long y) { boolean checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; boolean checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; boolean checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; //System.out.println(checkSide1+" "+checkSide2+" "+checkSide3); return checkSide1 && checkSide2 && checkSide3; } static boolean inside(Point a, Point b, Point c, Point pt) { return pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,pt.x,pt.y); } static boolean bad(int i,int j) { if((i + 1) % n == j || (j + 1) % n == i) return true; return false; } static boolean notOnLine(Point a, Point b,Point ch) { return !ch.onLine(a, b); } static int n; public static void main(String[]args)throws Throwable { Scanner sc = new Scanner(System.in); n = sc.nextInt(); Point p[] = new Point[n]; for(int i = 0 ; i < n ; ++i) p[i] = new Point(sc.nextInt(),sc.nextInt()); int m = sc.nextInt(); while(m-- > 0) { Point pt = new Point(sc.nextInt(),sc.nextInt()); int lo = 1, hi = n - 1; int ans = -1; while(lo <= hi) { int mid = lo + (hi - lo) / 2; Vector v1 = new Vector(p[mid],p[0]); Vector v2 = new Vector(pt,p[0]); //System.err.println(mid +" "+v1.cross(v2)); if(v1.cross(v2) < 0) { ans = mid + 1; lo = mid + 1; } else hi = mid - 1; } if(ans == -1 || ans == n || ans == 1) { System.out.println("NO"); return; } if(!inside(p[0],p[ans - 1],p[ans],pt)) { System.out.println("NO"); return; } else { //System.out.println(ans); boolean ok = true; if(bad(0,ans - 1)) { ok &= notOnLine(p[ans - 1],p[0],pt); } if(bad(0,ans)) { ok &= notOnLine(p[ans],p[0],pt); } if(bad(ans - 1,ans)) { ok &= notOnLine(p[ans],p[ans - 1],pt); } if(!ok) { System.out.println("NO"); return; } } } System.out.println("YES"); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(s));} String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
a864657b6f329d390ccb354d60eb2d34
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.TreeSet; public final class CF_113_B{ static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static int MX=Integer.MAX_VALUE; // check if strictly inside static boolean inside(int u,int v,ArrayList<Integer> leftx,ArrayList<Integer> lefty,ArrayList<Integer> rightx,ArrayList<Integer> righty){ // first check left int id=Collections.binarySearch(lefty,v); if (id==0 || id==lefty.size()-1) return false; if (id<0) id=-id-2; if (id<0 || id==lefty.size()-1) return false; int x0=leftx.get(id); int y0=lefty.get(id); int x1=leftx.get(id+1); int y1=lefty.get(id+1); long dx=x1-x0; long dy=y1-y0; long du=u-x0; long dv=v-y0; // check with scalar product of (dy,-dx) long sp=dy*du-dx*dv; if (sp<=0) return false; // then right id=Collections.binarySearch(righty,-v); if (id==0 || id==righty.size()-1) return false; if (id<0) id=-id-2; if (id<0 || id==righty.size()-1) return false; x0=rightx.get(id); y0=-righty.get(id); x1=rightx.get(id+1); y1=-righty.get(id+1); dx=x1-x0; dy=y1-y0; du=u-x0; dv=v-y0; // check with scalar product of (dy,-dx) sp=dy*du-dx*dv; if (sp<=0) return false; return true; } // Global vars static BufferedWriter out; static InputReader reader; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); int n=reader.readInt(); int[] x=new int[n]; int[] y=new int[n]; int top=-1; int highest=Integer.MIN_VALUE; int bottom=-1; int lowest=Integer.MAX_VALUE; // identify top and bottom for (int i=0;i<n;i++){ x[i]=reader.readInt(); y[i]=reader.readInt(); if (y[i]>highest){ highest=y[i]; top=i; } if (y[i]<lowest){ lowest=y[i]; bottom=i; } } if (bottom>top) top+=n; int m=reader.readInt(); int[] u=new int[m]; int[] v=new int[m]; for (int i=0;i<m;i++){ u[i]=reader.readInt(); v[i]=reader.readInt(); } ArrayList<Integer> leftx=new ArrayList<Integer>(); ArrayList<Integer> lefty=new ArrayList<Integer>(); ArrayList<Integer> rightx=new ArrayList<Integer>(); ArrayList<Integer> righty=new ArrayList<Integer>(); for (int i=bottom;i<=top;i++){ leftx.add(x[i%n]); lefty.add(y[i%n]); } for (int i=top;i<=bottom+n;i++){ rightx.add(x[i%n]); righty.add(-y[i%n]); } String res="YES"; loop:for (int i=0;i<m;i++){ if (!inside(u[i],v[i],leftx,lefty,rightx,righty)){ res="NO"; break loop; } } output(res); try { out.close(); } catch (Exception e){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
21e6df66c52737c7431056a22273932d
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class B166 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); Point[] a = new Point[n]; for(int i = 0; i<n; i++) a[i] = new Point(input.nextInt(), input.nextInt()); Pip pip = new Pip(a); int m = input.nextInt(); Point[] b = new Point[m]; for(int i = 0; i<m; i++) b[i] = new Point(input.nextInt(), input.nextInt()); boolean good = true; for(int i = 0; i<m; i++) good &= pip.query(b[i]); out.println(good ? "YES" : "NO"); out.close(); } static class Pip { Point[] upper, lower; Pip(Point[] p) { findHull(p); for(int i = 0; i<(upper.length+1)/2; i++) { Point temp = upper[i]; upper[i] = upper[upper.length-1-i]; upper[upper.length-1-i] = temp; } } /* * Returns true if p is strictly inside the polygon and false otherwise. */ boolean query(Point p) { if(p.x <= upper[0].x || p.x >= upper[upper.length-1].x) return false; return above(lower, p) == 1 && above(upper, p) == -1; } int above(Point[] hull, Point p) { int lo = 0, hi = hull.length-1; while(true) { int mid = (lo+hi)/2; if(p.x >= hull[mid].x && p.x <= hull[mid+1].x) return (int)Math.signum(hull[mid+1].minus(hull[mid]).cross(p.minus(hull[mid]))); else if(p.x >= hull[mid].x) lo = mid; else hi = mid; } } void findHull( Point[] points) { int n = points.length; Arrays.sort( points); lower = new Point[2 * n]; upper = new Point[2*n]; int k = 0, start = 0; for(int i = 0; i < n; i ++) { Point p = points[i]; while(k-start >= 2 && p.minus(lower[k-1]).cross(p.minus(lower[k-2])) >= 0) k--; lower[k++] = p; } lower = Arrays.copyOf(lower, k); start = 0; k = 0; for(int i = n-1 ; i >= 0 ; i --) { Point p = points[i]; while(k - start >= 2 && p.minus(upper[k-1]).cross(p.minus(upper[k-2])) >= 0) k--; upper[k++] = p; } upper = Arrays.copyOf(upper, k); } } static class Point implements Comparable<Point> { double x, y; public Point(double xx, double yy) { x = xx; y = yy; } public int compareTo(Point o) { if(x != o.x) return Double.compare(x, o.x); return Double.compare(y, o.y); } double cross(Point p) { return x * p.y - y * p.x; } Point minus(Point p) { return new Point(x - p.x, y - p.y); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(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 Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
aba3524ef811cb99b4d625b8f4a2a0c7
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class B166 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); Point[] a = new Point[n]; for(int i = 0; i<n; i++) a[i] = new Point(input.nextInt(), input.nextInt()); findHull(a); for(int i = 0; i<upper.length; i++) { if(i < upper.length-1-i) { Point temp = upper[i]; upper[i] = upper[upper.length-1-i]; upper[upper.length-1-i] = temp; } } //for(Point p : upper) out.println("u: "+p.x+" "+p.y); //for(Point p : lower) out.println("l: "+p.x+" "+p.y); int m = input.nextInt(); Point[] b = new Point[m]; for(int i = 0; i<m; i++) b[i] = new Point(input.nextInt(), input.nextInt()); boolean good = true; for(int i = 0; i<m; i++) good &= inside(b[i]); out.println(good ? "YES" : "NO"); out.close(); } static boolean inside(Point p) { if(p.x <= upper[0].x || p.x >= upper[upper.length-1].x) return false; //System.out.println(above(lower, p)+" "+above(upper, p)); return above(lower, p) == 1 && above(upper, p) == -1; } static int above(Point[] hull, Point p) { int lo = 0, hi = hull.length-1; while(true) { int mid = (lo+hi)/2; if(p.x >= hull[mid].x && p.x <= hull[mid+1].x) { long cross = p.minus(hull[mid]).cross(hull[mid+1].minus(hull[mid])); if(cross == 0) return 0; if(cross > 0) return -1; return 1; } else if(p.x >= hull[mid].x) lo = mid; else hi = mid; } } //Monotone Chain Convex Hull Algorithm //O(nlogn), where n is the number of points //returns all vertices and intermediate points of the hull in counter-clockwise order //Point class needs minus(Point that), comparator of increasing x then y, and cross(Point that) static Point[] lower, upper; public static void findHull( Point[] points) { int n = points.length; Arrays.sort( points); lower = new Point[2 * n]; // In between we may have a 2n points upper = new Point[2*n]; int k = 0, start = 0; // start is the first insertion point for(int i = 0; i < n; i ++) // Finding lower layer of hull { Point p = points[i]; while( k - start >= 2 && p.minus( lower[k-1] ).cross(p.minus( lower[k-2] ) ) >= 0 ) k--; lower[k++] = p; } // drop off last point from lower layer //--k ; lower = Arrays.copyOf(lower, k); start = 0; k = 0; for(int i = n-1 ; i >= 0 ; i --) // Finding top layer from hull { Point p = points[i]; while( k - start >= 2 && p.minus( upper[k-1] ).cross(p.minus( upper[k-2] ) ) >= 0 ) k--; upper[k++] = p; } upper = Arrays.copyOf(upper, k); } static class Point implements Comparable<Point> { long x, y; public Point(long xx, long yy) { x = xx; y = yy; } public int compareTo(Point o) { if(x != o.x) return Long.compare(x, o.x); return Long.compare(y, o.y); } long cross(Point p) { return x * p.y - y * p.x; } Point minus(Point p) { return new Point(x - p.x, y - p.y); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(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 Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
7242212b474d78d87dfc3da381d327c0
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.*; import java.util.*; public class B166 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); Point[] a = new Point[n]; for(int i = 0; i<n; i++) a[i] = new Point(input.nextInt(), input.nextInt()); Pip pip = new Pip(a); int m = input.nextInt(); Point[] b = new Point[m]; for(int i = 0; i<m; i++) b[i] = new Point(input.nextInt(), input.nextInt()); boolean good = true; for(int i = 0; i<m; i++) good &= pip.query(b[i]); out.println(good ? "YES" : "NO"); out.close(); } static class Pip { Point[] upper, lower; Pip(Point[] p) { findHull(p); for(int i = 0; i<upper.length; i++) { if(i < upper.length-1-i) { Point temp = upper[i]; upper[i] = upper[upper.length-1-i]; upper[upper.length-1-i] = temp; } } } /* * Returns true if p is strictly inside the polygon and false otherwise. */ boolean query(Point p) { if(p.x <= upper[0].x || p.x >= upper[upper.length-1].x) return false; return above(lower, p) == 1 && above(upper, p) == -1; } int above(Point[] hull, Point p) { int lo = 0, hi = hull.length-1; while(true) { int mid = (lo+hi)/2; if(p.x >= hull[mid].x && p.x <= hull[mid+1].x) return (int)Long.signum(hull[mid+1].minus(hull[mid]).cross(p.minus(hull[mid]))); else if(p.x >= hull[mid].x) lo = mid; else hi = mid; } } void findHull( Point[] points) { int n = points.length; Arrays.sort( points); lower = new Point[2 * n]; upper = new Point[2*n]; int k = 0, start = 0; for(int i = 0; i < n; i ++) { Point p = points[i]; while(k-start >= 2 && p.minus(lower[k-1]).cross(p.minus(lower[k-2])) >= 0) k--; lower[k++] = p; } lower = Arrays.copyOf(lower, k); start = 0; k = 0; for(int i = n-1 ; i >= 0 ; i --) { Point p = points[i]; while( k - start >= 2 && p.minus( upper[k-1] ).cross(p.minus( upper[k-2] ) ) >= 0 ) k--; upper[k++] = p; } upper = Arrays.copyOf(upper, k); } } static class Point implements Comparable<Point> { long x, y; public Point(long xx, long yy) { x = xx; y = yy; } public int compareTo(Point o) { if(x != o.x) return Long.compare(x, o.x); return Long.compare(y, o.y); } long cross(Point p) { return x * p.y - y * p.x; } Point minus(Point p) { return new Point(x - p.x, y - p.y); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(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 Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
5d16ee063579480c1a8b95ea1e294f6c
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Polygons { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int a = Integer.parseInt(br.readLine()); Point[] pA = new Point[a + 1]; ArrayList<Point> con = new ArrayList<>(); for (int i = a; i > 0; i--) { StringTokenizer st = new StringTokenizer(br.readLine()); Point p = new Point(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); pA[i] = p; con.add(p); } pA[0] = pA[a]; Polygon polA = new Polygon(pA); int b = Integer.parseInt(br.readLine()); Point[] pB = new Point[b + 1]; for (int i = b; i > 0; i--) { StringTokenizer st = new StringTokenizer(br.readLine()); Point p = new Point(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); pB[i] = p; con.add(p); } pB[0] = pB[b]; boolean isIn = true; Point[] all = new Point[con.size()]; for(int i=0;i<con.size();i++) { all[i] = con.get(i); } Polygon fin = Polygon.convexHull(all); if(fin.g.length!=polA.g.length) isIn = false; else { for(int i=0;i<fin.g.length;i++) { if(bs(fin.g[i],pB)) { isIn = false; break; } } } pw.println((isIn) ? "YES" : "NO"); pw.close(); } public static boolean bs(Point p,Point[]ps) { int start = 0; int end = ps.length-1; int mid = (start+end)/2; while(start < end) { if(p.compareTo(ps[mid])==0) return true; if(p.compareTo(ps[mid])==1) { start = mid+1; mid = (start+end)/2; } if(p.compareTo(ps[mid])==-1) { end = mid-1; mid = (start+end)/2; } } return false; } static class Line { static final double INF = 1e9, EPS = 1e-9; double a, b, c; Line(Point p, Point q) { if (Math.abs(p.x - q.x) < EPS) { a = 1; b = 0; c = -p.x; } else { a = (p.y - q.y) / (q.x - p.x); b = 1.0; c = -(a * p.x + p.y); } } Line(Point p, double m) { a = -m; b = 1; c = -(a * p.x + p.y); } boolean parallel(Line l) { return Math.abs(a - l.a) < EPS && Math.abs(b - l.b) < EPS; } boolean same(Line l) { return parallel(l) && Math.abs(c - l.c) < EPS; } Point intersect(Line l) { if (parallel(l)) return null; double x = (b * l.c - c * l.b) / (a * l.b - b * l.a); double y; if (Math.abs(b) < EPS) y = -l.a * x - l.c; else y = -a * x - c; return new Point(x, y); } Point closestPoint(Point p) { if (Math.abs(b) < EPS) return new Point(-c, p.y); if (Math.abs(a) < EPS) return new Point(p.x, -c); return intersect(new Line(p, 1 / a)); } } static class LineSegment { Point p, q; LineSegment(Point a, Point b) { p = a; q = b; } boolean intersect(LineSegment ls) { Line l1 = new Line(p, q), l2 = new Line(ls.p, ls.q); if (l1.parallel(l2)) { if (l1.same(l2)) return p.between(ls.p, ls.q) || q.between(ls.p, ls.q) || ls.p.between(p, q) || ls.q.between(p, q); return false; } Point c = l1.intersect(l2); return c.between(p, q) && c.between(ls.p, ls.q); } } static class Point implements Comparable<Point> { static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } public int compareTo(Point p) { if (Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if (Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) >= 0; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } // s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Polygon { // Cases to handle: collinear points, polygons with n < 3 static final double EPS = 1e-9; Point[] g; // first point = last point, counter-clockwise representation Polygon(Point[] o) { g = o; } double perimeter() { double sum = 0.0; for (int i = 0; i < g.length - 1; ++i) sum += g[i].dist(g[i + 1]); return sum; } double area() // clockwise/anti-clockwise check, for convex/concave polygons { double area = 0.0; for (int i = 0; i < g.length - 1; ++i) area += g[i].x * g[i + 1].y - g[i].y * g[i + 1].x; return Math.abs(area) / 2.0; // negative value in case of clockwise } boolean isConvex() { if (g.length <= 3) // point or line return false; boolean ccw = Point.ccw(g[g.length - 2], g[0], g[1]); // edit ccw check to accept collinear points for (int i = 1; i < g.length - 1; ++i) if (Point.ccw(g[i - 1], g[i], g[i + 1]) != ccw) return false; return true; } boolean inside(Point p) // for convex/concave polygons - winding number algorithm { double sum = 0.0; for (int i = 0; i < g.length - 1; ++i) { double angle = Point.angle(g[i], p, g[i + 1]); if ((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i + 1])) return true; if (Point.ccw(p, g[i], g[i + 1])) sum += angle; else sum -= angle; } return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; // abs makes it work for clockwise } /* * Another way if the polygon is convex 1. Triangulate the poylgon through p 2. * Check if sum areas == poygon area 3. Handle empty polygon */ Polygon cutPolygon(Point a, Point b) // returns the left part of the polygon, swap a & b for the right part { Point[] ans = new Point[g.length << 1]; Line l = new Line(a, b); Vector v = new Vector(a, b); int size = 0; for (int i = 0; i < g.length; ++i) { double left1 = v.cross(new Vector(a, g[i])); double left2 = i == g.length - 1 ? 0 : v.cross(new Vector(a, g[i + 1])); if (left1 + EPS > 0) ans[size++] = g[i]; if (left1 * left2 + EPS < 0) ans[size++] = l.intersect(new Line(g[i], g[i + 1])); } if (size != 0 && ans[0] != ans[size - 1]) // necessary in case g[0] is not in the new polygon ans[size++] = ans[0]; return new Polygon(Arrays.copyOf(ans, size)); } static Polygon convexHull(Point[] points) // all points are unique, remove duplicates, edit ccw to accept // collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n << 1]; int size = 0, start = 0; for (int i = 0; i < n; i++) { Point p = points[i]; while (size - start >= 2 && !Point.ccw(ans[size - 2], ans[size - 1], p)) --size; ans[size++] = p; } start = --size; for (int i = n - 1; i >= 0; i--) { Point p = points[i]; while (size - start >= 2 && !Point.ccw(ans[size - 2], ans[size - 1], p)) --size; ans[size++] = p; } // if(size < 0) size = 0 for empty set of points return new Polygon(Arrays.copyOf(ans, size)); } Point centroid() // center of mass { double cx = 0.0, cy = 0.0; for (int i = 0; i < g.length - 1; i++) { double x1 = g[i].x, y1 = g[i].y; double x2 = g[i + 1].x, y2 = g[i + 1].y; double f = x1 * y2 - x2 * y1; cx += (x1 + x2) * f; cy += (y1 + y2) * f; } double area = area(); // remove abs cx /= 6.0 * area; cy /= 6.0 * area; return new Point(cx, cy); } } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
4c01b31323c61ff1c4479261a454bcaf
train_001.jsonl
1332516600
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class B { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Point[] a = new Point[n]; TreeSet<Point> set = new TreeSet<>(); for(int i = 0; i < n; i++) set.add(a[i] = new Point(sc.nextDouble(), sc.nextDouble())); int m = sc.nextInt(); Point[] b = new Point[m]; for(int i = 0; i < m; i++) b[i] = new Point(sc.nextDouble(), sc.nextDouble()); Point[] all = new Point[n + m]; for(int i = 0; i < n; i++) all[i] = new Point(a[i].x, a[i].y); for(int i = n; i < n + m; i++) { all[i] = new Point(b[i - n].x, b[i - n].y); if(set.contains(all[i])) { out.println("NO"); out.flush(); return; } } Polygon hull = Polygon.convexHull(all); for(Point p : hull.g) if(!set.contains(p)){out.println("NO"); out.flush(); return;} out.println("YES"); out.flush(); out.close(); } static class Polygon { // Cases to handle: collinear points, polygons with n < 3 static final double EPS = 1e-9; Point[] g; //first point = last point, counter-clockwise representation Polygon(Point[] o) { g = o; } static Polygon convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points { int n = points.length; Arrays.sort(points); Point[] ans = new Point[n<<1]; int size = 0, start = 0; for(int i = 0; i < n; i++) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } start = --size; for(int i = n-1 ; i >= 0 ; i--) { Point p = points[i]; while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; ans[size++] = p; } // if(size < 0) size = 0 for empty set of points return new Polygon(Arrays.copyOf(ans, size)); } } static class Point implements Comparable<Point> { static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) >= 0; } } static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } double cross(Vector v) { return x * v.y - y * v.x; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0", "5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1", "5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1"]
2 seconds
["YES", "NO", "NO"]
null
Java 8
standard input
[ "sortings", "geometry" ]
d9eb0f6f82bd09ea53a1dbbd7242c497
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
2,100
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
standard output
PASSED
a8da8e48583b5ac1f00ea45f6e0e01ec
train_001.jsonl
1342450800
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper "Malevich and Life" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, x + 1, ..., x + k - 1 for some x (1 ≤ x ≤ n - k + 1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for x ≤ i ≤ x + k - 1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1, k2, ..., km. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all n - ki + 1 possible values. Help him to find the expected heights.
256 megabytes
import java.io.*; import java.lang.Math; import java.util.*; public class Main { public BufferedReader in; public Formatter out; //public PrintStream out; public boolean log_enabled = false; int n; long[] A; int[] L,R,T; public int findtLeft(int i) { if (i==0) { return 1; } if (A[i-1]<=A[i]) { return 1; } int j = i-1; while ((j>=0)&&(A[j]>A[i])) { j -= L[j]; } return i-j; } public int findtRight(int i) { if (i==n-1) { return 1; } if (A[i+1]<A[i]) { return 1; } int j = i+1; while ((j<n)&&(A[j]>=A[i])) { j += R[j]; } return j-i; } public void test() { int i; /* n = 1000000; out.format("%d\n", n); for (i=0; i<n; i++) { out.format("%d ", (int)(Math.random()*1000000000+1)); } out.format("\n%d\n", n); for (i=0; i<n; i++) { out.format("%d ", i+1); } out.format("\n", n); if (n>=1000000) { return; } */ n = readInt(); A = new long[n]; for (i=0; i<n; i++) { A[i] = readInt(); } int t,k,m = readInt(); int K[] = new int[m]; for (i=0; i<m; i++) { K[i] = readInt(); } L = new int[n]; R = new int[n]; T = new int[n]; for (i=0; i<n; i++) { L[i] = findtLeft(i); } for (i=n-1; i>=0; i--) { R[i] = findtRight(i); T[i] = L[i]+R[i]; } long[] dSa = new long[n+1]; long[] dSl = new long[n+1]; long[] dSr = new long[n+1]; long[] dSlk = new long[n+1]; long[] dSrk = new long[n+1]; for (i=0; i<n; i++) { dSa[i] = dSl[i] = dSr[i] = dSlk[i] = dSrk[i] = 0; } long Sa = 0; for (i=0; i<n; i++) { Sa += A[i]; if (T[i] <= n) { dSa[T[i]] += -A[i]; dSl[T[i]] += -A[i]*L[i]; dSr[T[i]] += -A[i]*R[i]; } dSl[L[i]] += A[i]*L[i]; dSr[R[i]] += A[i]*R[i]; dSlk[L[i]] += -A[i]; dSrk[R[i]] += -A[i]; } double[] Kres = new double[n+1]; long Sl = 0, Sr = 0, Slk = Sa, Srk = Sa; for (k=1; k<=n; k++) { Sa += dSa[k]; Sl += dSl[k]; Sr += dSr[k]; Slk += dSlk[k]; Srk += dSrk[k]; logWrite("%d: Sa=%d, Sl=%d, Slk=%d, Sr=%d, Srk=%d\n", k, Sa, Sl, Slk, Sr, Srk); Kres[k] = Sl + Slk*k + Sr + Srk*k - k*Sa; } for (i=0; i<m; i++) { k = K[i]; out.format("%.12f\n", Kres[k] / (n-k+1)); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new Formatter (new BufferedWriter(new OutputStreamWriter(System.out)));; //out = System.out; //in = new BufferedReader(new FileReader("in.txt")); //out = new PrintStream(new File("out.txt")); } catch (Exception e) { return; } //while (true) { //int t = readInt(); for (int i=0; i<t; i++) { test(); } } out.flush(); } public static void main(String args[]) { new Main().run(); } private StringTokenizer tokenizer = null; public int readInt() { return Integer.parseInt(readToken()); } public long readLong() { return Long.parseLong(readToken()); } public double readDouble() { return Double.parseDouble(readToken()); } public String readLn() { try { String s; while ((s = in.readLine()).length()==0); return s; } catch (Exception e) { return ""; } } public String readToken() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (Exception e) { return ""; } } public int[] readIntArray(int n) { int[] x = new int[n]; readIntArray(x, n); return x; } public void readIntArray(int[] x, int n) { for (int i=0; i<n; i++) { x[i] = readInt(); } } public void logWrite(String format, Object... args) { if (!log_enabled) { return; } out.format(format, args); } }
Java
["3\n3 2 1\n3\n1 2 3", "2\n1 1\n3\n1 2 1"]
5 seconds
["2.000000000000000\n1.500000000000000\n1.000000000000000", "1.000000000000000\n1.000000000000000\n1.000000000000000"]
NoteLet's consider the first sample test. There are three possible positions of the fence for k1 = 1. For the first position (x = 1) the height is 3, for the second one (x = 2) the height is 2, for the third one (x = 3) the height is 1. As the fence position is chosen uniformly, the expected height of the fence equals ; There are two possible positions of the fence for k2 = 2. For the first position (x = 1) the height is 2, for the second one (x = 2) the height is 1. The expected height of the fence equals ; There is the only possible position of the fence for k3 = 3. The expected height of the fence equals 1.
Java 6
standard input
[ "data structures", "dsu", "binary search" ]
a8859b3f0f5db57c359399bd9315e240
The first line contains a single integer n (1 ≤ n ≤ 106) — the number of planks in the fence. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the height of the i-th plank of the fence. The third line contains an integer m (1 ≤ m ≤ 106) and the next line contains m space-separated integers k1, k2, ..., km (1 ≤ ki ≤ n) where ki is the width of the desired fuchsia-colored rectangle in planks.
2,500
Print m whitespace-separated real numbers, the i-th number equals the expected value of the rectangle height, if its width in planks equals ki. The value will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
d77cac65e68910d1ba2639fda4b455b5
train_001.jsonl
1342450800
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper "Malevich and Life" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, x + 1, ..., x + k - 1 for some x (1 ≤ x ≤ n - k + 1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for x ≤ i ≤ x + k - 1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1, k2, ..., km. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all n - ki + 1 possible values. Help him to find the expected heights.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { private int[] heights; private boolean[] present; private int[] next; private int[] last; private int[] queue; public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); heights = IOUtils.readIntArray(in, count); int[] order = new int[count]; int[] temp = new int[count]; for (int i = 0; i < count; i++) order[i] = temp[i] = i; sort(order, temp, 0, count); long[] delta = new long[count + 2]; present = new boolean[count]; Arrays.fill(present, true); next = new int[count]; for (int i = 0; i < count; i++) next[i] = i + 1; last = new int[count]; for (int i = 0; i < count; i++) last[i] = i - 1; int[] left = new int[count]; int[] right = new int[count]; queue = new int[count]; for (int i = count - 1; i >= 0; i--) { present[order[i]] = false; left[order[i]] = get(order[i], last); right[order[i]] = get(order[i], next); } for (int i = 0; i < count; i++) { delta[0] += heights[i]; delta[Math.min(i - left[i], right[i] - i)] -= heights[i]; delta[Math.max(i - left[i], right[i] - i)] -= heights[i]; delta[right[i] - left[i]] += heights[i]; } long sum = 0; long curDelta = 0; long[] answer = new long[count + 1]; for (int i = 0; i < count; i++) { curDelta += delta[i]; sum += curDelta; answer[i + 1] = sum; } int queryCount = in.readInt(); for (int i = 0; i < queryCount; i++) { int query = in.readInt(); out.printLine((double)answer[query] / (count - query + 1)); } } private int get(int i, int[] next) { int size = 0; while (!(i < 0 || i >= heights.length || present[i])) { queue[size++] = i; i = next[i]; } for (int j = 0; j < size; j++) next[queue[j]] = i; return i; } private void sort(int[] order, int[] temp, int from, int to) { if (to - from <= 1) return; int middle = (from + to) >> 1; sort(temp, order, from, middle); sort(temp, order, middle, to); int firstIndex = from; int secondIndex = middle; int index = from; while (firstIndex < middle && secondIndex < to) { if (heights[temp[firstIndex]] < heights[temp[secondIndex]]) order[index++] = temp[firstIndex++]; else order[index++] = temp[secondIndex++]; } if (firstIndex != middle) System.arraycopy(temp, firstIndex, order, index, to - index); if (secondIndex != to) System.arraycopy(temp, secondIndex, order, index, to - index); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["3\n3 2 1\n3\n1 2 3", "2\n1 1\n3\n1 2 1"]
5 seconds
["2.000000000000000\n1.500000000000000\n1.000000000000000", "1.000000000000000\n1.000000000000000\n1.000000000000000"]
NoteLet's consider the first sample test. There are three possible positions of the fence for k1 = 1. For the first position (x = 1) the height is 3, for the second one (x = 2) the height is 2, for the third one (x = 3) the height is 1. As the fence position is chosen uniformly, the expected height of the fence equals ; There are two possible positions of the fence for k2 = 2. For the first position (x = 1) the height is 2, for the second one (x = 2) the height is 1. The expected height of the fence equals ; There is the only possible position of the fence for k3 = 3. The expected height of the fence equals 1.
Java 6
standard input
[ "data structures", "dsu", "binary search" ]
a8859b3f0f5db57c359399bd9315e240
The first line contains a single integer n (1 ≤ n ≤ 106) — the number of planks in the fence. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the height of the i-th plank of the fence. The third line contains an integer m (1 ≤ m ≤ 106) and the next line contains m space-separated integers k1, k2, ..., km (1 ≤ ki ≤ n) where ki is the width of the desired fuchsia-colored rectangle in planks.
2,500
Print m whitespace-separated real numbers, the i-th number equals the expected value of the rectangle height, if its width in planks equals ki. The value will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
3a14d05530dc5f0fd251b1dcd3605569
train_001.jsonl
1342450800
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper "Malevich and Life" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, x + 1, ..., x + k - 1 for some x (1 ≤ x ≤ n - k + 1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for x ≤ i ≤ x + k - 1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1, k2, ..., km. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all n - ki + 1 possible values. Help him to find the expected heights.
256 megabytes
import java.io.*; import java.util.*; public class Solution { private StringTokenizer st; private BufferedReader in; private PrintWriter out; public void solve() throws IOException { int n = nextInt(); // Random rnd = new Random(); long[] a = new long[n + 1]; for (int i = 0; i < n; ++i) { a[i] = nextLong(); // a[i] = rnd.nextInt(n) + 1; } int[] rooml = new int[n]; int[] roomr = new int[n]; int[] stack = new int[n + 2]; int stp = 1; stack[0] = n; for (int i = n - 1; i >= 0; --i) { while (a[stack[stp - 1]] >= a[i]) { stp--; } roomr[i] = stack[stp - 1] - i; stack[stp++] = i; } stp = 1; for (int i = 0; i < n; ++i) { while (a[stack[stp - 1]] > a[i]) { stp--; } rooml[i] = i - (stack[stp - 1] == n ? -1 : stack[stp - 1]); stack[stp++] = i; } long[] ans = new long[n + 2]; long[] d2t = new long[n + 2]; for (int i = 0; i < n; ++i) { d2t[0] += a[i]; d2t[rooml[i]] -= a[i]; d2t[roomr[i]] -= a[i]; d2t[rooml[i] + roomr[i]] += a[i]; } long dt = 0; for (int i = 0; i <= n; ++i) { dt += d2t[i]; ans[i + 1] = ans[i] + dt; } if (ans[n + 1] != 0) { throw new AssertionError(); } int m = nextInt(); for (int i = 0; i < m; ++i) { int q = nextInt(); out.println((double)ans[q] / (n - q + 1)); } } public void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); out.close(); } void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } static boolean failed = false; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution().run(); } }
Java
["3\n3 2 1\n3\n1 2 3", "2\n1 1\n3\n1 2 1"]
5 seconds
["2.000000000000000\n1.500000000000000\n1.000000000000000", "1.000000000000000\n1.000000000000000\n1.000000000000000"]
NoteLet's consider the first sample test. There are three possible positions of the fence for k1 = 1. For the first position (x = 1) the height is 3, for the second one (x = 2) the height is 2, for the third one (x = 3) the height is 1. As the fence position is chosen uniformly, the expected height of the fence equals ; There are two possible positions of the fence for k2 = 2. For the first position (x = 1) the height is 2, for the second one (x = 2) the height is 1. The expected height of the fence equals ; There is the only possible position of the fence for k3 = 3. The expected height of the fence equals 1.
Java 6
standard input
[ "data structures", "dsu", "binary search" ]
a8859b3f0f5db57c359399bd9315e240
The first line contains a single integer n (1 ≤ n ≤ 106) — the number of planks in the fence. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the height of the i-th plank of the fence. The third line contains an integer m (1 ≤ m ≤ 106) and the next line contains m space-separated integers k1, k2, ..., km (1 ≤ ki ≤ n) where ki is the width of the desired fuchsia-colored rectangle in planks.
2,500
Print m whitespace-separated real numbers, the i-th number equals the expected value of the rectangle height, if its width in planks equals ki. The value will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
7813bd356ab565a83858089cc8a4a2d0
train_001.jsonl
1372433400
Fox Ciel has a board with n rows and n columns, there is one integer in each cell.It's known that n is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size x rows and x columns, then all numbers in it will be multiplied by -1.Return the maximal sum of numbers in the board that she can get by these operations.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Mike Lee */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; /*try { inputStream = new FileInputStream("boardgame.in"); } catch (IOException e) { throw new RuntimeException(e); } */ OutputStream outputStream = System.out; /*try { outputStream = new FileOutputStream("boardgame.out"); } catch (IOException e) { throw new RuntimeException(e); } */ Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BoardGame solver = new BoardGame(); solver.solve(1, in, out); out.close(); } } class BoardGame { final int kInf = Integer.MIN_VALUE; public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(), x = n / 2; int[][] board = new int[n][n]; int[] a = new int[n]; int[][] f = new int[n / 2][2]; int ans = -kInf; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) board[i][j] = in.nextInt(); for (int s = 0; s < (1 << (x + 1)); s++) { for (int i = 0; i <= x; i++) a[i] = (s & (1 << i)) > 0 ? 1 : -1; for (int i = x + 1; i < n; i++) a[i] = a[x] * a[i - x - 1]; for (int i = 0; i < n / 2; i++) f[i][0] = f[i][1] = 0; for (int i = 0; i < x; i++) for (int j = 0; j < x; j++) { int val1 = board[i][j] + board[i][j + x + 1] * a[i] + board[i + x + 1][j] + board[i + x + 1][j + x + 1] * a[i] * a[x]; int val2 = board[i][j] + board[i][j + x + 1] * a[i] + board[i + x + 1][j] * -1 + board[i + x + 1][j + x + 1] * a[i] * a[x] * -1; val1 = Math.max(val1, -val1); val2 = Math.max(val2, -val2); f[j][0] += val1; f[j][1] += val2; } for (int i = 0; i < n / 2; i++) { f[i][0] += board[x][i] + board[x][i + x + 1] * a[x]; f[i][1] += -board[x][i] - board[x][i + x + 1] * a[x]; } int tmp = 0; for (int i = 0; i < n; i++) tmp += a[i] * board[i][x]; for (int i = 0; i < x; i++) tmp += Math.max(f[i][0], f[i][1]); ans = Math.max(ans, tmp); } out.print(ans); } }
Java
["3\n-1 -1 1\n-1 1 -1\n1 -1 -1", "5\n-2 0 0 0 -2\n0 -2 0 -2 0\n0 0 -2 0 0\n0 -2 0 -2 0\n-2 0 0 0 -2"]
4 seconds
["9", "18"]
NoteIn the first test, we can apply this operation twice: first on the top left 2 × 2 sub-board, then on the bottom right 2 × 2 sub-board. Then all numbers will become positive.
Java 7
standard input
[ "dp", "greedy", "math" ]
7f9d69890e6b7acbfd419388f5d3cef5
The first line contains an integer n, (1 ≤ n ≤ 33, and n is an odd integer) — the size of the board. Each of the next n lines contains n integers — the numbers in the board. Each number doesn't exceed 1000 by its absolute value.
2,900
Output a single integer: the maximal sum of numbers in the board that can be accomplished.
standard output
PASSED
65581d1c6a93c8bff78cdbf8b635d10d
train_001.jsonl
1372433400
Fox Ciel has a board with n rows and n columns, there is one integer in each cell.It's known that n is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size x rows and x columns, then all numbers in it will be multiplied by -1.Return the maximal sum of numbers in the board that she can get by these operations.
256 megabytes
import java.util.*; import java.io.*; public class CielAndFlipboard { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner cin = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BoardGame solver = new BoardGame(); solver.solve(1, cin, out); out.close(); } } class BoardGame { final int kInf = Integer.MIN_VALUE; public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(), x = n / 2; int[][] board = new int[n][n]; int[] a = new int[n]; int[][] f = new int[n / 2][2]; int ans = -kInf; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = in.nextInt(); } } for (int s = 0; s < (1 << (x + 1)); s++) { for (int i = 0; i <= x; i++) { a[i] = (s & (1 << i)) > 0 ? 1 : -1; } for (int i = x + 1; i < n; i++) { a[i] = a[x] * a[i - x - 1]; } for (int i = 0; i < n / 2; i++) { f[i][0] = f[i][1] = 0; } for (int i = 0; i < x; i++) { for (int j = 0; j < x; j++) { int val1 = board[i][j] + board[i][j + x + 1] * a[i] + board[i + x + 1][j] + board[i + x + 1][j + x + 1] * a[i] * a[x]; int val2 = board[i][j] + board[i][j + x + 1] * a[i] + board[i + x + 1][j] * -1 + board[i + x + 1][j + x + 1] * a[i] * a[x] * -1; val1 = Math.max(val1, -val1); val2 = Math.max(val2, -val2); f[j][0] += val1; f[j][1] += val2; } } for (int i = 0; i < n / 2; i++) { f[i][0] += board[x][i] + board[x][i + x + 1] * a[x]; f[i][1] += -board[x][i] - board[x][i + x + 1] * a[x]; } int tmp = 0; for (int i = 0; i < n; i++) tmp += a[i] * board[i][x]; for (int i = 0; i < x; i++) { tmp += Math.max(f[i][0], f[i][1]); } ans = Math.max(ans, tmp); } out.print(ans); } }
Java
["3\n-1 -1 1\n-1 1 -1\n1 -1 -1", "5\n-2 0 0 0 -2\n0 -2 0 -2 0\n0 0 -2 0 0\n0 -2 0 -2 0\n-2 0 0 0 -2"]
4 seconds
["9", "18"]
NoteIn the first test, we can apply this operation twice: first on the top left 2 × 2 sub-board, then on the bottom right 2 × 2 sub-board. Then all numbers will become positive.
Java 7
standard input
[ "dp", "greedy", "math" ]
7f9d69890e6b7acbfd419388f5d3cef5
The first line contains an integer n, (1 ≤ n ≤ 33, and n is an odd integer) — the size of the board. Each of the next n lines contains n integers — the numbers in the board. Each number doesn't exceed 1000 by its absolute value.
2,900
Output a single integer: the maximal sum of numbers in the board that can be accomplished.
standard output
PASSED
cd0854b46392187d2aa1d63a462c98aa
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class MainClass { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.nextInt(); HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); int c=0,s=0,max=-1; for(int i=0;i<n;i++) { int x=in.nextInt(); if(hm.containsKey(x)){ int y=hm.get(x); hm.replace(x, y+1); } else { hm.put(x, 1); } } c=0; Iterator<Integer> a= hm.values().iterator(); while(a.hasNext()) { s++; if(a.next()%2==1) { out.println("Conan"); break; } else c++; } if(c==s) { out.println("Agasa"); } out.flush(); out.close(); } } class InputReader{ private final InputStream stream; private final byte[] buf=new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream){this.stream=stream;} public int read()throws IOException{ if(curChar>=numChars){ curChar=0; numChars=stream.read(buf); if(numChars<=0) return -1; } return buf[curChar++]; } public final int nextInt()throws IOException{return (int)nextLong();} public final long nextLong()throws IOException{ int c=read(); while(isSpaceChar(c)){ c=read(); if(c==-1) throw new IOException(); } boolean negative=false; if(c=='-'){ negative=true; c=read(); } long res=0; do{ if(c<'0'||c>'9')throw new InputMismatchException(); res*=10; res+=(c-'0'); c=read(); }while(!isSpaceChar(c)); return negative?(-res):(res); } public final int[] readIntBrray(int size)throws IOException{ int[] arr=new int[size]; for(int i=0;i<size;i++)arr[i]=nextInt(); return arr; } public final String next()throws IOException{ int c=read(); while(isSpaceChar(c))c=read(); StringBuilder res=new StringBuilder(); do{ res.append((char)c); c=read(); }while(!isSpaceChar(c)); return res.toString(); } public final String nextLine()throws IOException{ int c=read(); while(isSpaceChar(c))c=read(); StringBuilder res=new StringBuilder(); do{ res.append((char)c); c=read(); }while(c!='\n'&&c!=-1); return res.toString(); } private boolean isSpaceChar(int c){ return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
2b5d85b280b0e46d7fc3cfd9b6aa2de4
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.util.*; import java.text.*; public class Main{ public static void main(String[] afzalkhan){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int A[] = new int[100000]; int B[] = new int[100005]; for(int i=0;i<N;i++){ A[i] = sc.nextInt(); B[A[i]]++; } for(int i=0;i<100000;i++){ if(B[A[i]]%2==1){ System.out.println("Conan"); return; } } System.out.println("Agasa"); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
ac0b7ed2273bf4a0bc9b4778221475f2
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * * @author jmbangue */ public class ConanAgasa { public static void main(String[] args){ BufferedInputStream bf = new BufferedInputStream(System.in); BufferedReader r = new BufferedReader( new InputStreamReader(bf, StandardCharsets.UTF_8)); OutputStream out = new BufferedOutputStream ( System.out ); try { int n = Integer.parseInt(r.readLine()); String[] tab = r.readLine().split(" "); int[] a = new int[n]; int[] c = new int[100001]; int max = 0; for (int i=0;i<n;i++){ a[i] = Integer.parseInt(tab[i]); c[a[i]]++; max = Math.max(max,a[i]); } Arrays.sort(a); boolean aa = true; int j = n-1; while(j>=0){ int cnt = c[a[j]]; if (cnt%2==1) { aa = false; break; } j -= cnt; } String ret = aa ? "Agasa":"Conan"; out.write((ret+"\n").getBytes()); out.flush(); }catch(Exception ex){ ex.printStackTrace(); } } private static int readInt(InputStream in) throws IOException { int ret = 0; boolean dig = false; for (int c = 0; (c = in.read()) != -1; ) { if (c >= '0' && c <= '9') { dig = true; ret = ret * 10 + c - '0'; } else if (dig) break; } return ret; } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
c7a19ce89c609e9377f0df10a1f4cb76
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { BufferedReader br; StringTokenizer in; PrintWriter pw; Random r; int INF = (int) 1e9; long LNF = (long) 1e18; long mod = (long) (1e9 + 7); // you shall not hack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // /*\ // /// /^\ // /// ~~~~ (___) // /// ~~~~~~~~ \\__ // _/_/_ ~/ .& . \~ \\ \ // [____] ~| (__) |~/ \\/ // /_/\ \~|~~~~~~~~~~ /\\ // \ ~~~~~~~~~~ _/ \\ // \ _ ~~ _/\ \\ // / | / \ \\ // | / | \ \\ // / / ___ | \ // /___| | __| |_______\ // _| | | |_ // |____| |____| // P.S this is omnipotent Gandalf void solve() throws IOException { int n = nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Arrays.sort(a); ArrayList<Integer> z = new ArrayList<>(); int last = a[n - 1]; z.add(0); int w = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] == last) { z.set(z.size() - 1, z.get(z.size() - 1) + 1); } else { z.add(1); last = a[i]; } } for (int i = 0; i < z.size(); i++) { if (z.get(i) % 2 == 1) { pw.print("Conan"); return; } } pw.print("Agasa"); } //*************************************** class road { int to; int w; public road(int tto, int ww) { to = tto; w = ww; } } class pair { int a; int b; public pair(int aa, int bb) { a = aa; b = bb; } } Comparator<pair> bya = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.a != o2.a) return Integer.compare(o1.a, o2.a); return Integer.compare(o1.b, o2.b); } }; Comparator<pair> byb = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.b != o2.b) return Integer.compare(o1.b, o2.b); return Integer.compare(o1.a, o2.a); } }; Comparator<road> byw = new Comparator<road>() { @Override public int compare(road o1, road o2) { if (o1.w != o2.w) return Integer.compare(o1.w, o2.w); return Integer.compare(o1.to, o2.to); } }; Comparator<road> byto = new Comparator<road>() { @Override public int compare(road o1, road o2) { return Integer.compare(o1.to, o2.to); } }; class node { int sz; int val; // long sum; node L; node R; int prior; public node(int val) { this.val = val; prior = r.nextInt(); L = null; R = null; sz = 1; // sum = (long)val * val; } void add(int z) { val = val + z; // sum = (long)val * val; } } void relax(node c) { if (c == null) return; c.sz = sfsz(c.L) + sfsz(c.R) + 1; // c.sum = sfsum(c.L) + sfsum(c.R) + c.val * c.val; } int sfsz(node c) { if (c == null) return 0; return c.sz; } node merge(node a, node b) { if (a == null) return b; if (b == null) return a; if (a.prior > b.prior) { a.R = merge(a.R, b); relax(a); return a; } else { b.L = merge(a, b.L); relax(b); return b; } } pairn split(node c, int s) { if (c == null) return new pairn(null, null); if (sfsz(c.L) >= s) { pairn p = split(c.L, s); c.L = p.b; relax(c); // relax(p.a); return new pairn(p.a, c); } else { pairn p = split(c.R, s - sfsz(c.L) - 1); c.R = p.a; relax(c); // relax(p.b); return new pairn(c, p.b); } } class pairn { node a; node b; public pairn(node a, node b) { this.a = a; this.b = b; } } String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } // boolean check() public void run() throws IOException { r = new Random(5); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("input.txt")); // pw = new PrintWriter(new FileWriter("output.txt")); // br = new BufferedReader(new FileReader("river.in")); // pw = new PrintWriter(new FileWriter("river.out")); solve(); pw.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
cb4c0d0917f1122fad345b229e80b875
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigDecimal; public class R458B { public static void main (String[] args) throws java.lang.Exception { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int max = 0, max_count = 0; HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < n; i++) { int temp = in.nextInt(); if (!hm.containsKey(temp)) { hm.put(temp, 0); } hm.put(temp, hm.get(temp) + 1); } for (int x : hm.keySet()) { if (hm.get(x) % 2 == 1) { w.println("Conan"); w.close(); return; } } w.println("Agasa"); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
1d0ff1a8a890fd47eb43be80aa40f85c
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.util.Collections; public class Solution { static class Solver { Solver() { } public void solve(FastScanner sc, PrintWriter out) throws IOException { int n = sc.nextInt(); int[] freq = new int[(int)1e5+1]; for(int i = 0; i < n; i++) { freq[sc.nextInt()]++; } boolean f = false; for(int i = 0; i < freq.length; i++) { if(freq[i] % 2 == 1) { f = true; break; } } out.println(f ? "Conan" : "Agasa"); } } public static void main(String[] args) throws IOException{ FastScanner scanner = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); (new Solver()).solve(scanner, out); out.flush(); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch(Exception e) { e.printStackTrace(); } } boolean hasNextToken() { if(st == null) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { } } return st.hasMoreTokens(); } String next() { while(st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() throws IOException{ return br.readLine(); } byte nextByte() { return Byte.parseByte(next()); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
cb46fddf9bebb20ca174fb66ce5af12b
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.HashMap; public class CFR458B { static int n, a, count[] = new int[100001]; static HashMap<String, ArrayList<Integer>> hm = new HashMap<>(); static String ins[]; static boolean isWinConan = false; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); n = Integer.parseInt(br.readLine()); ins = br.readLine().split(" "); for (int i = 0; i < n; i++) { a = Integer.parseInt(ins[i]); count[a]++; } for (int i = 0; i < 100001; i++) { if ((count[i] & 1) != 0) { isWinConan = true; } } bw.write(isWinConan ? "Conan\n" : "Agasa\n"); bw.flush();bw.close(); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
1f00a30fc508beb00476e4f20df40c87
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class cc_B { InputStream is; PrintWriter out; int n; long a[]; private boolean oj = System.getProperty("ONLINE_JUDGE") != null; void solve() { int n = ni(); int arr[] = na(n); Arrays.sort(arr); int max = arr[n - 1]; // int count = 0; int ind[] = new int[1000000 + 1]; for (int i = 0; i < n; i++) { ind[arr[i]] = i + 1; } boolean flag = false; //tr(arr); for (int i = 0; i < n; i++) { if (ind[arr[i]] % 2 == 1) { flag = true; } } if (flag) { out.println("Conan"); } else { out.println("Agasa"); } } void run() throws Exception { String INPUT = "C:\\Users\\Admin\\Desktop\\input.txt"; is = oj ? System.in : new FileInputStream(INPUT); 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 Thread(null, new Runnable() { public void run() { try { new cc_B().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } 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 void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
53f5ff02432304a66bf5095f6b5c56eb
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
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.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class B_ { static int dp[][]; static int n; static Integer[] arr; static int[] nxt; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); dp = new int[2][n]; arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); nxt = new int[n]; Arrays.sort(arr); Arrays.fill(dp[0], -1); Arrays.fill(dp[1], -1); nxt[n-1] = n; for (int i = n-2; i >= 0; i--) { if(arr[i].equals(arr[i+1])) nxt[i] = nxt[i+1]; else nxt[i] = i+1; } for (int i = n-1; i >= 0; i-= 1000) { solve(1, i); solve(0, i); } int winner = solve(0, 0); if(winner == 0) System.out.println("Conan"); else System.out.println("Agasa"); pw.flush(); pw.close(); } private static int solve(int turn, int ind) { if(ind == n) return 1-turn; if(dp[turn][ind] != -1) return dp[turn][ind]; int win1 = solve(1-turn, ind+1); int win2 = solve(turn, nxt[ind]); if(win1 == turn || win2 == turn) return dp[turn][ind] = turn; else return dp[turn][ind] = 1-turn; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File((s)))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
184a6e1b1063c5066a4a255e09c4c216
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class CardGameB458 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n=Integer.parseInt(in.readLine()); int[] vals=new int[n]; StringTokenizer st=new StringTokenizer(in.readLine()); for(int i=0;i<n;i++) vals[i]=Integer.parseInt(st.nextToken()); Arrays.sort(vals); if(n%2==1) out.println("Conan"); else { int count=1; for(int i=1;i<n;i++) { if(vals[i]==vals[i-1]) count++; else { if(count%2==1) { out.println("Conan"); out.close(); return; } count=1; } } out.println("Agasa"); } in.close(); out.close(); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
0d248390a323b264e1f3e9f5a38ae693
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner in = new Scanner(System.in); int a; a=in.nextInt(); if(a==1){ System.out.println("Conan"); return;} int l; int[] b=new int[100009]; for(int i=0;i<a;i++){ b[in.nextInt()]++; } for(int x:b){ if(x%2!=0){ System.out.println("Conan"); return; } } System.out.println("Agasa"); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
114997c1a5e16c46b6aa3bc7b223c2e4
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class scorify{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int n = in.nextInt(),count=0,temp,one=0; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0 ; i<n ; i++){ temp = in.nextInt(); if(map.containsKey(temp)){ map.put(temp,map.get(temp)+1); }else{map.put(temp,1);} } for(Map.Entry m:map.entrySet()){ if((int)(m.getValue())!=1){ if((int)(m.getValue())%2!=0){count++;} }else{one++;} } if(one>=1){count++;} if(count>=1){ System.out.println("Conan"); }else{System.out.println("Agasa");} } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
640716c562f0a53d43fa91207aff43dd
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
//Code by Sounak, IIEST import java.io.*; import java.math.*; import java.util.*; import java.util.Arrays; public class Test1{ public static void main(String args[])throws IOException{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; int i,max=0,count=1; boolean ch=false; for(i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.sort(a); max=a[n-1]; for(i=n-2;i>=0;i--) { if(a[i]==max) count++; else { if(count%2==1) { ch=true; break; } else { count=1; max=a[i]; } } } if(count%2==1) ch=true; if(ch) System.out.println("Conan"); else System.out.println("Agasa"); } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
fbd62418261da3eee7ff55c0f5f1fce2
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
//package codeforce_458; import java.util.*; public class B { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { list.add(in.nextInt()); } Collections.sort(list); int current = list.get(list.size()-1); int len = 0; while(!list.isEmpty()) { int temp = list.remove(list.size()-1); if(temp != current) { if(len%2 == 1) { System.out.println("Conan"); System.exit(0); } else { current = temp; len = 1; } } else { len++; } } if(len%2 == 1) { System.out.println("Conan"); System.exit(0); } else { System.out.println("Agasa"); System.exit(0); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
ca419c8a39c9cbedda5638d7a8645313
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] cards = new int[n]; for (int i = 0; i < n; i++) { cards[i] = sc.nextInt(); } Arrays.sort(cards); if (n / 2 == 0) { System.out.println("Conan"); return; } int i; for ( i = 0; i < cards.length - 1; i++) { if (cards[i] != cards[i + 1]) { System.out.println("Conan"); return; } i++; } if (i == n - 1) { System.out.println("Conan"); return; } System.out.println("Agasa"); // pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
bce3548ce84a3921117688959e4eba60
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class B914 { public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String in[] = br.readLine().trim().split(" " ); int mx = 0; int a[] = new int[n]; Map<Integer, Integer>M = new HashMap<>(); for (int i=0;i<n;++i) { int x = Integer.parseInt(in[i]); a[i] = x; if (x>mx) { mx = x; } int cnt = (M.containsKey(x)) ? M.get(x) : 0; M.put(x, cnt+1); } int cnt = 0; // System.out.println(mx + " " + res); for (int i=0;i<n;++i) { if (M.get(a[i]) % 2 == 0) { cnt++; } } if (cnt == n) { System.out.println("Agasa"); } else { System.out.println("Conan"); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
0a95e1824ba2c0c2f26390efec53bb2d
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
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 */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private static final int MAX = (int) 1e5 + 1; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = new int[n], b = new int[MAX]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); b[a[i]]++; } for (int i = MAX - 1; i > -1; i--) { if (b[i] % 2 == 1) { out.print("Conan"); return; } } out.print("Agasa"); } } static class InputReader { private InputStream stream; private final int SIZE = 1 << 10; private byte[] buffer = new byte[SIZE]; private int current; private int size; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (size == -1) throw new InputMismatchException(); if (current >= size) { current = 0; try { size = stream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buffer[current++]; } public int nextInt() { int c = read(); while (isSpaceCharacter(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c - '0'; c = read(); } while (!isSpaceCharacter(c)); return result * sign; } private boolean isSpaceCharacter(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } 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(String s) { writer.print(s); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
f2a17448c72d1575893ec2583b2e5ee3
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
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 */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private static final int MAX = (int) 1e5 + 1; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = new int[n], b = new int[MAX]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); b[a[i]]++; } for (int i = 0; i < MAX; i++) { if (b[i] % 2 == 1) { out.print("Conan"); return; } } out.print("Agasa"); } } static class InputReader { private InputStream stream; private final int SIZE = 1 << 10; private byte[] buffer = new byte[SIZE]; private int current; private int size; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (size == -1) throw new InputMismatchException(); if (current >= size) { current = 0; try { size = stream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buffer[current++]; } public int nextInt() { int c = read(); while (isSpaceCharacter(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c - '0'; c = read(); } while (!isSpaceCharacter(c)); return result * sign; } private boolean isSpaceCharacter(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } 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(String s) { writer.print(s); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
c17eb46a3344fc9016891bb487e7d3e5
train_001.jsonl
1516462500
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj &lt; ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(), max = 100005; int[] cards = new int[max]; boolean winConan = false; for (int i = 0; i < n; i++) cards[in.nextInt()]++; for (int i = 0; i < max; i++) { if (cards[i] % 2 == 1) { winConan = true; break; } } out.println(winConan == true ? "Conan" : "Agasa"); } } }
Java
["3\n4 5 7", "2\n1 1"]
2 seconds
["Conan", "Agasa"]
NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.
Java 8
standard input
[ "implementation", "greedy", "games" ]
864593dc3911206b627dab711025e116
The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.
1,200
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
standard output
PASSED
da6ca2775954b10342384e3ef89976bf
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D2 { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); out.println(solve(s, t)); out.flush(); out.close(); } private static int solve(char[] s, char[] t) { int ans = 0; int[] rg = new int[t.length]; for(int i = t.length - 1; i >= 0; i--) { int pos = s.length - 1; if(i + 1 < t.length) pos = rg[i+1] - 1; while(s[pos] != t[i]) pos--; rg[i] = pos; } int pos = 0; for (int i = 0; i < s.length; i++) { int rpos = s.length-1; if(pos < t.length) rpos = rg[pos]-1; ans = Math.max(ans, rpos - i + 1); if(pos < t.length && t[pos] == s[i]) pos++; } return ans; } 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
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
c903bfccd01b306c255fec9d576b5546
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; public class RemoveSubstrings { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); String t = br.readLine(); int left = -1; int right = s.length(); int count = 0; int maxDist = 0; int[] leftInds = new int[t.length()]; for (int i = 0; i < s.length(); i++) { if (count < t.length()) { if (s.charAt(i) == t.charAt(count)) { leftInds[count] = i; count++; maxDist = Integer.max(maxDist, i - left - 1); left = i; } } else { break; } } maxDist = Integer.max(maxDist, right - left - 1); for (int i = 1; i < t.length(); i++) { count--; char a = t.charAt(count); left = leftInds[count-1]; for (int j = right - 1; j > left; j--) { if (a == s.charAt(j)) { right = j; break; } } maxDist = Integer.max(maxDist, right - left - 1); //System.out.println(left + " " + right); } for (int j = right - 1; j >= 0; j--) { if (t.charAt(0) == s.charAt(j)) { right = j; break; } } maxDist = Integer.max(maxDist, right); System.out.println(maxDist); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
8d3091fe602037be280568caeb2f7844
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.Arrays; public class _1203D2 { BufferedReader bf; InputStream is; public _1203D2(InputStream is){ this.is = is; this.bf = new BufferedReader(new InputStreamReader(is)); } public int[] ints(int size){ try{ String[] data = bf.readLine().split(" "); data = Arrays.stream(data).filter(s -> !s.trim().isEmpty()).toArray(String[]::new); int i = 0; int[] array = new int[size]; for(String s : data) array[i++] = Integer.parseInt(s); return array; }catch (Exception e){ e.printStackTrace(); } return null; } public int getInt(){ try{ return Integer.parseInt(bf.readLine().replace(" ","")); } catch (IOException e) { e.printStackTrace(); } return 0; } public long[] longs(int size){ try{ String[] data = bf.readLine().split(" "); int i = 0; long[] array = new long[size]; for(String s : data) array[i++] = Long.parseLong(s); return array; } catch (IOException e) { e.printStackTrace(); } return null; } public long getLong(){ try{ return Long.parseLong(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } return 0; } public String intsToString(int[] data){ StringBuilder stringBuilder = new StringBuilder(); for(int e : data) stringBuilder.append(e).append(" "); return stringBuilder.toString(); } public String getString() throws Exception{ return bf.readLine(); } public int computeOne(String a,String b){ int[] one = getFirst(a,b); int[] two = getLast(a,b); int max = 0; for(int i = 0,h=one.length,temp;i<h;i++){ temp = two[i] - one[i] - 1; max = temp > max ? temp : max; } return max; } private int[] getFirst(String a, String b){ int[] send = new int[b.length()+1]; send[0] = -1; int i = 1; int j = 0; int lenb = b.length()+1; while (i<lenb){ if(a.charAt(j)==b.charAt(i-1)) send[i++] = j; j++; } return send; } private int[] getLast(String a, String b){ int[] send = new int[b.length()+1]; send[b.length()] = a.length(); int i = send.length-2; int j = a.length()-1; while (i>=0){ if(a.charAt(j)==b.charAt(i)) send[i--] = j; j--; } return send; } public void run() throws Exception{ System.out.println(computeOne(getString(),getString())); } public static void main(String...args) throws Exception{ new _1203D2(System.in).run(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
4d773074b4a5165dd9bc74d653724161
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class removeSubstring { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static String[] line; static PrintWriter pw = new PrintWriter(System.out); static int n, m; static char[] s, t; static int[] pre, post; public static void main(String[] args) throws IOException { s = br.readLine().toCharArray(); n = s.length; t = br.readLine().toCharArray(); m = t.length; pre = new int[m]; int tIdx = 0; for(int i = 0; i < n && tIdx < m; ++i) { if(s[i] == t[tIdx]) { pre[tIdx] = i; ++tIdx; } } tIdx = m - 1; post = new int[m]; for(int i = n - 1; i >= 0 && tIdx >= 0; --i) { if(s[i] == t[tIdx]) { post[tIdx] = i; --tIdx; } } //try all split points int out = 0; for(int x = 0; x < m - 1; ++x) { int idx1 = pre[x], idx2 = post[x + 1]; int curr = idx2 - idx1 - 1; out = Math.max(out, curr); } //try first int curr = post[0]; out = Math.max(out, curr); //try last curr = n - 1 - pre[m - 1]; out = Math.max(out, curr); System.out.println(out); } static void l() throws IOException { line = br.readLine().split(" "); } static int p(String in) { return Integer.parseInt(in); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
72df4ee1f74cfdfd2aebb675acf79de4
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD1 solver = new TaskD1(); solver.solve(1, in, out); out.close(); } static class TaskD1 { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.next(); String t = in.next(); int[] first = new int[t.length()]; int[] last = new int[t.length()]; int idx = 0; for (int i = 0; i < s.length(); ++i) { if (idx >= t.length()) break; if (s.charAt(i) == t.charAt(idx)) { first[idx] = i; ++idx; } } idx = t.length() - 1; for (int i = s.length() - 1; i >= 0; --i) { if (idx < 0) break; if (s.charAt(i) == t.charAt(idx)) { last[idx] = i; --idx; } } int res = Math.max(last[0], s.length() - first[t.length() - 1] - 1); for (int i = 0; i < t.length() - 1; ++i) { res = Math.max(res, last[i + 1] - first[i] - 1); } out.println(res); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream), 2444334); 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(); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
2515895dfd1d410652e6ab55dc2f0677
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import static java.lang.System.out; import static java.lang.Math.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); String rs = (new StringBuilder(s)).reverse().toString(); String t = in.nextLine(); String rt = (new StringBuilder(t)).reverse().toString(); int[] loc = new int[t.length()]; int[] rloc = new int[t.length()]; calcLoc(t, s, loc); calcLoc(rt, rs, rloc); for (int i = 0; i < rloc.length; i++) { rloc[i] = s.length() - rloc[i] - 1; } // System.out.println(java.util.Arrays.toString(loc)); // System.out.println(java.util.Arrays.toString(rloc)); int res = 0; res = max(res, s.length() - loc[loc.length -1] - 1); res = max(res, rloc[rloc.length - 1]); for (int i = 0; i < loc.length - 1; i++) { res = max(res, rloc[loc.length - i - 2] - loc[i] - 1); } System.out.println(res); } static void calcLoc(String t, String s, int[] loc) { int curr = 0; for (int i = 0; i < t.length(); i++) { while (t.charAt(i) != s.charAt(curr)) { curr++; } loc[i] = curr; curr++; } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
30da5154d3db90ec2aba424516ca0702
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static PrintWriter pr; static int cin() throws Exception { return Integer.valueOf(br.readLine()); } static int[] split() throws Exception { String[] cmd=br.readLine().split(" "); int[] ans=new int[cmd.length]; for(int i=0;i<cmd.length;i++) { ans[i]=Integer.valueOf(cmd[i]); } return ans; } static long[] splitL() throws IOException { String[] cmd=br.readLine().split(" "); long[] ans=new long[cmd.length]; for(int i=0;i<cmd.length;i++) { ans[i]=Long.valueOf(cmd[i]); } return ans; } static int sum(long n) { int ans=0; while(n!=0) { ans=ans+(int)(n%10); n=n/10; } return ans; } static int gcd(int x,int y) { if(x==0) return y; if(y==0) return x; if(x>y) return gcd(x%y,y); else return gcd(x,y%x); } static int calc(int mx,int sum,int n) { if(sum>=n) return 0; int res=1+Math.min(calc(mx,sum+mx,n),calc(mx+1,sum+1,n)); return res; } static int[]forward; static int[]backward; static boolean possible(int l,String s,String t) { for(int i=0;i<s.length();i++) { int j=i+l-1; if(j>=s.length()) break; int x=0; if(i!=0) x+=forward[i-1]; if(j!=s.length()-1) x+=backward[j+1]; if(x>=t.length()) { return true; } } return false; } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub br=new BufferedReader(new InputStreamReader(System.in)); pr=new PrintWriter(new OutputStreamWriter(System.out)); int cases=1; while(cases!=0) { cases--; String s=br.readLine(); String t=br.readLine(); forward=new int[s.length()]; backward=new int[s.length()]; int j=0; for(int i=0;i<s.length();i++) { if(j<t.length() && s.charAt(i)==t.charAt(j)) j++; forward[i]=j; } j=t.length()-1; int cnt=0; for(int i=s.length()-1;i>=0;i--) { if(j>=0 && s.charAt(i)==t.charAt(j)) { j--; cnt++; } backward[i]=cnt; } int lo=0; int hi=s.length(); int ans=0; while(lo<hi) { int mid=(lo+hi)/2; if(possible(mid,s,t)) { ans=Math.max(ans, mid); lo=mid+1; } else hi=mid-1; } if(possible(lo,s,t)) ans=Math.max(ans, lo); System.out.println(ans); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
50deede397dedec831463b36e52c8d8e
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { static long mod=(long)(1e+9 + 7); //static long mod=(long)998244353; static int[] sieve; static ArrayList<Integer> primes; static PrintWriter out; static fast s; static StringBuilder fans; static int x_dir[]; static int y_dir[]; public static void solve() { char ch1[]=s.nextLine().toCharArray(); char ch2[]=s.nextLine().toCharArray(); int n=ch1.length; int m=ch2.length; ArrayList<Integer> start=new ArrayList<Integer>(); ArrayList<Integer> end=new ArrayList<Integer>(); int j=0; for(int i=0;i<n;i++) if(j<m && ch1[i]==ch2[j]) {start.add(i);j++;} j=m-1; for(int i=n-1;i>=0;i--) if(j>=0 && ch1[i]==ch2[j]) {end.add(i);j--;} int max=Math.max(n-1-start.get(m-1), end.get(m-1)); for(int i=0;i<start.size()-1;i++) max=Math.max(max, end.get(end.size()-1-i-1)-start.get(i)-1); fans.append(max); } public static void main(String[] args) throws java.lang.Exception { s = new fast(); out=new PrintWriter(System.out); fans=new StringBuilder(""); int t=1; while(t>0) { solve(); t--; } out.println(fans); out.close(); } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; //Return floor log2n public static long log2(long bits) // returns 0 for bits=0 { int log = 0; if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; } if( bits >= 256 ) { bits >>>= 8; log += 8; } if( bits >= 16 ) { bits >>>= 4; log += 4; } if( bits >= 4 ) { bits >>>= 2; log += 2; } return log + ( bits >>> 1 ); } public static boolean next_permutation(int a[]) { int i=0,j=0;int index=-1; int n=a.length; for(i=0;i<n-1;i++) if(a[i]<a[i+1]) index=i; if(index==-1) return false; i=index; for(j=i+1;j<n && a[i]<a[j];j++); int temp=a[i]; a[i]=a[j-1]; a[j-1]=temp; for(int p=i+1,q=n-1;p<q;p++,q--) { temp=a[p]; a[p]=a[q]; a[q]=temp; } return true; } public static void sieve(int size) { sieve=new int[size+1]; primes=new ArrayList<Integer>(); sieve[1]=1; for(int i=2;i*i<=size;i++) { if(sieve[i]==0) { for(int j=i*i;j<size;j+=i) {sieve[j]=1;} } } for(int i=2;i<=size;i++) { if(sieve[i]==0) primes.add(i); } } public static long pow(long a, long p){ long o = 1; for(; p>0; p>>=1){ if((p&1)==1)o = mul(o, a); a = mul(a, a); } return o; } public static long add(long... a){ long o = 0; for(long x:a)o = (o+mod+x)%mod; return o; } public static long mul(long... a){ long p = 1; for(long x:a)p = (mod+(p*x)%mod)%mod; return p; } public static long mod_inv(long n) { return pow(n,mod-2); } public long gcd(long r,long ans) { if(r==0) return ans; return gcd(ans%r,r); } public fast() { this(System.in); } public fast(InputStream is) { i = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = i.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 nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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 int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
cb74222f82b9f67ab18a4d91a0fb29fd
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class ProblemD { public static void main(String[] args) { // TODO Auto-generated method stub Scanner S = new Scanner(System.in); String s = S.next(); String t = S.next(); int[] left = new int[t.length()]; int[] right = new int[t.length()]; int l = 0; for(int i=0;i<t.length();i++) { while(s.charAt(l) != t.charAt(i)) l++; left[i] = l; l++; } int r = s.length()-1; for(int i=t.length()-1;i>=0;i--) { while(s.charAt(r) != t.charAt(i)) r--; right[i] = r; r--; } int ans = right[0]; for(int i=0;i<t.length()-1;i++) { ans = Math.max(ans, right[i+1]-left[i]-1); } ans = Math.max(ans, s.length()-1-left[t.length()-1]); System.out.println(ans); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
6b22cbc12bde0b853fcafb6e276ce70b
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String a = br.readLine(); String b = br.readLine(); char[] s = a.toCharArray(); char[]t = b.toCharArray(); int n = s.length; int m = t.length; int[] first = new int[m]; int[] last = new int[m]; int j = 0; for (int i = 0; i < m; i++) { while (s[j] != t[i]) j++; first[i] = j; j++; } j = n - 1; for (int i = m - 1; i >= 0; i--) { while (s[j] != t[i]) j--; last[i] = j--; } int ans = Math.max(last[0], n - 1 - first[m - 1]); for (int i = 0; i < m - 1; i++) ans = Math.max(ans, last[i + 1] - first[i] - 1); System.out.println(ans); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
5c0f18e979c1aaf8fb41cd450d92de6c
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; public class D21203 { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); String t = br.readLine(); int sl = s.length(); int tl = t.length(); int[] l = new int[tl]; int[] r = new int[tl]; for(int i=0,j=0;i<sl && j<tl;i++) { if(s.charAt(i)==t.charAt(j)) l[j++]=i; } for(int i=sl-1,j=tl-1;i>=0 && j>=0;i--) { if(s.charAt(i)==t.charAt(j)) r[j--]=i; } int v = r[0]; for(int i=0;i<tl-1;i++) { v = Math.max(v, r[i+1]-l[i]-1); } v = Math.max(v, sl-l[tl-1]-1); System.out.println(v); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
2ee9280ff14c95ac52471a9e862f6851
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { solver s = new solver(); long t = 1; while (t > 0) { s.solve(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); token = null; } public String next() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class card { long a; int cnt; int i; public card(long a, int cnt, int i) { this.a = a; this.cnt = cnt; this.i = i; } } static class ascend implements Comparator<pair> { public int compare(pair o1, pair o2) { if (o1.a != o2.a) return (int) (o1.a - o2.a); else return o1.b - o2.b; } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; static void shuffle(long a[]) { List<Long> l = new ArrayList<>(); for (int i = 0; i < a.length; i++) l.add(a[i]); Collections.shuffle(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } static boolean valid(int i, int j, int r, int c, char ch[][]) { if (i >= 0 && i < r && j >= 0 && j < c && ch[i][j] != '#') { // System.out.println(i+" /// "+j); return true; } else { // System.out.println(i+" //f "+j); return false; } } static void seive() { for (int i = 2; i < 100001; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 100001; j += i) v[j] = true; } } } static int binary(LinkedList<Integer> a, long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a.get(mid) == val) { r = mid - 1; ans = mid; } else if (a.get(mid) > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(int x, int y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } /* void dijsktra(int s, List<pair> l[], int n) { PriorityQueue<pair> pq = new PriorityQueue<>(new ascend()); int dist[] = new int[100005]; boolean v[] = new boolean[100005]; for (int i = 1; i <= n; i++) dist[i] = 1000000000; dist[s] = 0; for (int i = 1; i < n; i++) { if (i == s) pq.add(new pair(s, 0)); else pq.add(new pair(i, 1000000000)); } while (!pq.isEmpty()) { pair node = pq.remove(); v[node.a] = true; for (int i = 0; i < l[node.a].size(); i++) { int v1 = l[node.a].get(i).a; int w = l[node.a].get(i).b; if (v[v1]) continue; if ((dist[node.a] + w) < dist[v1]) { dist[v1] = dist[node.a] + w; pq.add(new pair(v1, dist[v1])); } } } }*/ } static class pair { long a; int b; public pair(long a, int i) { this.a = a; this.b = i; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static int inf = 5000013; static class solver { DecimalFormat df = new DecimalFormat("0.000000000"); extra e = new extra(); long mod = 1000000007; void solve() { String s = sc.next(); int n = s.length(); String t = sc.next(); int m = t.length(); int fro[] = new int[200005]; fro[0] = -1; for (int i = 0, j = 0; j < m; i++, j++) { while (s.charAt(i) != t.charAt(j)) i++; fro[j + 1] = i; } long ans = 0; for (int i = n - 1, j = m - 1; j >= 0; i--, j--) { while (s.charAt(i) != t.charAt(j)) i--; ans = Math.max(ans, i - fro[j] - 1); } ans = Math.max(ans, n - fro[m] - 1); System.out.println(ans); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
ae3c495619db00c91e8903ac06b32e72
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class RemoveTheSubstring { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { long mod = (long)(1000000007); public void solve(int testNumber, InputReader in, PrintWriter out) { while(testNumber-->0){ String a = in.next(); String s = in.next(); int l = a.indexOf(s.charAt(0)); int r = a.lastIndexOf(s.charAt(s.length()-1)); ArrayList<ArrayList<Integer>> c = new ArrayList<>(); for(int i=0;i<26;i++) c.add(new ArrayList<>()); for(int i=l;i<=r;i++) c.get(a.charAt(i)-'a').add(i); int length = s.length(); int first[] = new int[length]; int last[] = new int[length]; first[0] = l; last[length-1] = r; for(int i=length-2;i>=0;i--){ int x = lowerLastBound(c.get(s.charAt(i)-'a') , last[i+1]); last[i] = c.get(s.charAt(i)-'a').get(x); } for(int i=1;i<length;i++){ int x = upperFirstBound(c.get(s.charAt(i)-'a') , first[i-1]); first[i] = c.get(s.charAt(i)-'a').get(x); } int max = Math.max(last[0] , a.length() - 1 - first[length-1]); for(int i=0;i<length-1;i++){ max = Math.max(max , last[i+1] - first[i]-1); } // print1d(first, out); // print1d(last , out); out.println(max); } } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ int value; int delete; Combine(int val , int delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(a%b==0) return b; return gcd(b , a%b); } public void print2d(int a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
61e7b6c1ddf6371e2d83aec8b9ee577a
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class TaskD { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1=in.next(); String s2=in.next(); //System.out.println(s1.length() + " " + s2.length()); int[] front=new int[s2.length()]; int[] back= new int[s2.length()]; int n=s1.length(); int m =s2.length(); for(int i=0,j=0;i<n && j<m;i++){ if(s1.charAt(i)==s2.charAt(j)){ front[j]=i; j++; } } for(int i=n-1,j=m-1;i>=0 && j>=0;i--){ if(s1.charAt(i)==s2.charAt(j)){ back[j]=i; j--; } } int ans=Math.max(back[0], n-front[m-1]-1); for(int i=1;i<m;i++){ ans=Math.max(ans, (back[i]-front[i-1]-1)); } System.out.println(ans); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
f0ac96815b039532810e3194042e0524
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
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.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author keyur_jain */ 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); TaskD2 solver = new TaskD2(); solver.solve(1, in, out); out.close(); } static class TaskD2 { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.nextString(); String t = in.nextString(); int n = s.length(), m = t.length(); Integer[] prefixMatch = new Integer[n]; Integer[] suffixMatch = new Integer[n]; int j = 0; for (int i = 0; i < n; i++) { if (j < m && s.charAt(i) == t.charAt(j)) { j += 1; prefixMatch[i] = j; } else { prefixMatch[i] = (i != 0) ? prefixMatch[i - 1] : 0; } } j = 0; for (int i = n - 1; i >= 0; i--) { if (j < m && s.charAt(i) == t.charAt(m - j - 1)) { j += 1; suffixMatch[i] = j; } else { suffixMatch[i] = (i != n - 1) ? suffixMatch[i + 1] : 0; } } int answer = n - BinarySearch.LowerBound(prefixMatch, m) - 1; for (int i = n - 1; i >= 0; i--) { int have = suffixMatch[i]; int need = m - have; int idx = BinarySearch.LowerBound(prefixMatch, need); if (need == 0) idx = -1; answer = Math.max(answer, i - idx - 1); } out.println(answer); } } static class BinarySearch { public static <T extends Comparable<T>> int LowerBound(T[] arr, T x) { int lo = 0, hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) >> 1; if (arr[mid].compareTo(x) < 0) { lo = mid + 1; } else { hi = mid; } } return (arr[lo].compareTo(x) < 0) ? arr.length : lo; } } 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 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 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 println(int i) { writer.println(i); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
f537c9f41165506a066a8446b299b5c7
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("input.txt")); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); String s = br.readLine(); String t = br.readLine(); ArrayList<Integer>[] ind = new ArrayList['z' - 'a' + 1]; for (int i = 0; i < ind.length; i++) { ind[i] = new ArrayList<>(); } int j = 0; char now; now = t.charAt(j); for (int i = 0; i < s.length(); i++) { if (j < t.length()) now = t.charAt(j); if (s.charAt(i) == now) { ind[s.charAt(i) - 'a'].add(i); j++; } else { if (ind[s.charAt(i) - 'a'].size() > 0) ind[s.charAt(i) - 'a'].add(i); } } int[] arr2 = new int[t.length()]; int first = ind[t.charAt(0) - 'a'].get(0); arr2[0]=first; for (int i = 1; i < t.length(); i++) { int lo=0; int hi=ind[t.charAt(i) - 'a'].size() - 1; while(lo<=hi){ int mid=(lo+hi)>>1; if(ind[t.charAt(i) - 'a'].get(mid) > first){ hi=mid-1; arr2[i] =ind[t.charAt(i) - 'a'].get(mid); } else lo=mid+1; } first=arr2[i]; } int[] arrangement = new int[t.length()]; int last = ind[t.charAt(t.length() - 1) - 'a'].get(ind[t.charAt(t.length() - 1) - 'a'].size() - 1); arrangement[t.length() - 1] = last; for (int i = t.length() - 2; i >= 0; i--) { int lo=0; int hi=ind[t.charAt(i) - 'a'].size() - 1; while(lo<=hi){ int mid=(lo+hi)>>1; if(ind[t.charAt(i) - 'a'].get(mid) < last){ lo=mid+1; arrangement[i] =ind[t.charAt(i) - 'a'].get(mid); } else hi=mid-1; } last=arrangement[i]; } int max = 0; for (int i = 0; i < t.length() - 1; i++) { max = Math.max(max, arrangement[i + 1] - arr2[i] - 1); } max = Math.max(max, arrangement[0]); max = Math.max(max, s.length() - 1 - arr2[t.length() - 1]); out.println(max); out.flush(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
5eda4af293acbdbd7b671200540a059c
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter wr = new PrintWriter(System.out); char s1[] = sc.nextLine().toCharArray(); char s2[] = sc.nextLine().toCharArray(); int arr1[] = new int[s2.length]; int arr2[] = new int[s2.length]; int j = 0; int k = s2.length - 1; int max = 0; for (int i = 0; i < s1.length; i++) { if (s2[j] == s1[i]) { arr1[j] = i; j++; }if(j==s2.length)break; } for (int i = s1.length - 1; i >= 0; i--) { if (s2[k] == s1[i]) { arr2[k] = i; k--; }if(k==-1)break; } for (int i = 0; i < s2.length - 1; i++) { max = Math.max(max, arr2[i + 1] - arr1[i] - 1); } max = Math.max(max, arr1[0]); max = Math.max(max, s1.length - arr1[s2.length - 1] - 1); max = Math.max(max, arr2[0]); max = Math.max(max, s1.length - arr2[s2.length - 1] - 1); wr.print(max); wr.flush(); wr.close(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
1bfd8a0830d106671468e3f8b9648f7e
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; import java.io.FileWriter; // Solution public class Main { public static void main (String[] argv) { new Main(); } boolean test = false; final int MOD = 998244353; //1000000007; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); int ns = s.length, nt = t.length; int[] llen = new int[nt]; for (int i = 0, j = 0; i < nt; i++) { while (s[j] != t[i]) j++; // now s[j] == t[i] llen[i] = ++j; //the length of shortest prefix of s that contains t[0...i] //System.out.println("llen " + i + " = " + llen[i]); } int maxLen = ns - llen[nt-1]; for (int i = nt - 1, j = ns - 1; i >= 0; i--) { while (s[j] != t[i]) j--; //System.out.println("matched " + i + " = " + j); // now s[j] == t[i] // need to fit t[0...(i-1)] is shortest prefix of s if (i > 0) maxLen = Math.max(maxLen, j - llen[i-1]); else maxLen = Math.max(maxLen, j); //update j j--; } System.out.println(maxLen); } private int mod_add(int a, int b) { int v = a + b; if (v >= MOD) v -= MOD; return v; } private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2); if (x3 > x2 || y4 < y1 || y3 > y2) return 0L; //(x3, ?, x2, ?) int yL = Math.max(y1, y3); int yH = Math.min(y2, y4); int xH = Math.min(x2, x4); return f(x3, yL, xH, yH); } //return #black cells in rectangle private long f(int x1, int y1, int x2, int y2) { long dx = 1L + x2 - x1; long dy = 1L + y2 - y1; if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0) return 1L * dx * dy / 2; return 1L * dx * dy / 2 + 1; } private int dist(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } private boolean less(int x, int y, int xx, int yy) { return x < xx || y > yy; } private int mul(int x, int y) { return (int)(1L * x * y % MOD); } private int add(int x, int y) { return (x + y) % MOD; } private int nBit1(int v) { int v0 = v; int c = 0; while (v != 0) { ++c; v = v & (v - 1); } return c; } private long abs(long v) { return v > 0 ? v : -v; } private int abs(int v) { return v > 0 ? v : -v; } private int common(int v) { int c = 0; while (v != 1) { v = (v >>> 1); ++c; } return c; } private void reverse(char[] a, int i, int j) { while (i < j) { swap(a, i++, j--); } } private void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; } private int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } private long gcd(long x, long y) { if (y == 0) return x; return gcd(y, x % y); } private int max(int a, int b) { return a > b ? a : b; } private long max(long a, long b) { return a > b ? a : b; } private int min(int a, int b) { return a > b ? b : a; } private long min(long a, long b) { return a > b ? b : a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return null; //e.printStackTrace(); } return str; } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
0a9fcfed85cefed312de06ed7eb25980
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class RemoveTheSubstring { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); String s = scanner.next(); String t = scanner.next(); int n = s.length(); int m = t.length(); int[] front = new int[m]; int[] back = new int[m]; int p = 0; for(int i =0; i < m; i++) { while(s.charAt(p) != t.charAt(i)) p++; front[i] = p++; } p = n-1; for(int i = m-1; i >= 0; i--) { while(s.charAt(p) != t.charAt(i)) p--; back[i] = p--; } int best = Math.max(back[0], n-front[m-1]-1); for(int i = 0; i < m-1; i++) { best = Math.max(best, back[i+1] - front[i]-1); } out.println(best); out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
21ee3fe22f12c92b374be511426b03b5
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class codeforces{ // Input static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); 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() { String s = null; try { s = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return s; } public String nextParagraph() { String line = null; String ans = ""; try { while ((line = reader.readLine()) != null) { ans += line; } } catch (IOException e) { throw new RuntimeException(e); } return ans; } } //Template static int mod = 998244353; static void printArray(int ar[]){ for(int x:ar) System.out.print(x+" ");} static void printArray(ArrayList<Integer> ar){ for(int x:ar) System.out.print(x+" ");} static long gcd(long a, long b){ if (a == 0) return b; return gcd(b%a, a);} static long power(long x, long y, int p) { long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1;x = (x * x) % p; } return res;} static void takeArrayInput(InputReader sc, int ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextInt(); } static void takeArrayInput(InputReader sc, long ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextLong(); } static void take2dArrayInput(InputReader sc, int ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextInt(); } static void take2dArrayInput(InputReader sc, long ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextLong(); } static ArrayList<ArrayList<Integer>> graph(InputReader sc, int n, int m){ ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); for(int i=0;i<n;i++) list.add(new ArrayList<Integer>()); for(int i=0;i<m;i++){ int u = sc.nextInt(); int v = sc.nextInt(); list.get(u).add(v); list.get(v).add(u); } return list; } // Write Code Here static class Data { int u; int v; public Data(int e, int val) { this.u = e; this.v = val; } } static void sieveOfEratosthenes(int n, ArrayList<Integer> pr) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p pr.add(p); for (int i = p * p; i <= n; i += p) prime[i] = false; } } } static int longest(String s, String t){ int p[] = new int[t.length()]; int i=0, j=0; for(i=0;i<s.length() && j<t.length();i++){ if(s.charAt(i) == t.charAt(j)){ p[j++]=i; } } j = t.length()-1; int max = s.length() - p[j] -1; char c = t.charAt(j); for(i=s.length()-1;i>=0 && j>0;i--){ if(s.charAt(i) == c){ int k = p[j-1]; max = Math.max(max, (i-k-1)); j--; c = t.charAt(j); } } return max; } public static void main(String args[]) { InputReader sc = new InputReader(); PrintWriter pw = new PrintWriter(System.out); int i=0, j=0; String s = sc.nextLine(); String t = sc.nextLine(); int m = longest(s, t); StringBuilder sb = new StringBuilder(s); s = sb.reverse().toString(); sb = new StringBuilder(t); t = sb.reverse().toString(); int p = longest(s, t); pw.println(Math.max(p, m)); pw.close(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
4d0a5562b045a61e328062eed8a430f3
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class p1203D { public void realMain() throws Exception { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000); String in = fin.readLine(); String ss = " " + in + " "; in = fin.readLine(); String ts = in; char[] s = ss.toCharArray(); char[] t = ts.toCharArray(); int n = ss.length(); int m = ts.length(); int[] match1 = new int[m + 1]; int[] match2 = new int[m + 1]; match1[0] = 0; int j = 0; for(int i = 0; i < m; i++) { boolean inced = false; while(s[j] != t[i]) { j++; inced = true; } //if(!inced) //j++; match1[i + 1] = j; j++; } match2[m] = n - 1; j = n - 1; for(int i = m - 1; i >= 0; i--) { boolean inced = false; while(s[j] != t[i]) { j--; inced = true; } match2[i] = j; j--; } //System.out.println(Arrays.toString(match1)); //System.out.println(Arrays.toString(match2)); int max = 0; for(int i = 0; i <= m; i++) { max = Math.max(max, match2[i] - match1[i]); } System.out.println(max - 1); } public static void main(String[] args) throws Exception { p1203D a = new p1203D(); a.realMain(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
532d73ab96a1ceeb268ed982cd1acb9f
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class AA { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char [] s = sc.next().toCharArray(); char [] t = sc.next().toCharArray(); int [] suf = new int[s.length]; int ans = 0; for (int i = suf.length-1; i >= 0; --i) { int add = i+1 < s.length?suf[i+1]:0; if(t.length-1-add >= 0 && t[t.length-1-add] == s[i]) ++add; suf[i] = add; if(add == t.length) ans = Math.max(ans, i); } // System.out.println(Arrays.toString(suf)); // out.println(ans); int pre = 0; int pnt = 1; for (int i = 0; i < s.length; ++i) { if(pre < t.length && t[pre] == s[i]) ++pre; if(pre == t.length) { ans = Math.max(ans, s.length-i-1); break; } while(pnt < suf.length && suf[pnt] >= t.length-pre) ++pnt; ans = Math.max(ans, pnt-i-2); // System.out.println(ans); // System.out.println(pnt); // System.out.println(pre); } out.println(ans); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
d12ccaa03b85eec7e296c03f9bde50f8
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class Q4 { static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Pair implements Comparable<Pair> { int u, v; public Pair(int u, int v) { this.u = u; this.v = v; } public int compareTo(Pair o) { return Integer.compare(u, o.u) != 0 ? Integer.compare(u, o.u) : Integer.compare(v, o.v); } } public static void main(String[] args) throws Exception { FastScanner fs = new FastScanner(System.in); String s = fs.nextToken(), t = fs.nextToken(); int n1 = s.length(), n2 = t.length(); int[] arr = new int[n2], brr = new int[n2]; int i = 0, j = 0; while (i < n2) { if (t.charAt(i) == s.charAt(j)) arr[i++] = j; j++; } i = n2 - 1; j = n1 - 1; while (i >= 0) { if (t.charAt(i) == s.charAt(j)) brr[i--] = j; j--; } int maxi = brr[0]; maxi = Math.max(maxi, n1 - 1 - arr[n2 - 1]); for (i = 0; i < n2 - 1; i++) maxi = Math.max(maxi, brr[i + 1] - arr[i] - 1); pw.println(maxi); pw.flush(); pw.close(); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
ece741e52dd4bb228bab7f6aef02f6b2
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = in.next(); String t = in.next(); int l = 0; int r = s.length() - 1; while (l < r - 1) { int m = (l + r) / 2; int posT = 0; for (int i = m; i < s.length(); i++) { if (posT < t.length() && t.charAt(posT) == s.charAt(i))posT++; } if(posT == t.length()) l = m; else r = m; } int posT = t.length() - 1; int pos[] = new int[t.length()]; for (int i = s.length() - 1; i >= 0; i--) { if (posT >= 0 && s.charAt(i) == t.charAt(posT)) { pos[posT] = i; posT--; } } int canfirst = l; int post = 0; for (int i = r; i < s.length(); i++) { if (post < t.length() && t.charAt(post) == s.charAt(i))post++; } if(post == t.length()) canfirst = r; posT = 0; int ans = 0; for (int i = 0; i < s.length(); i++) { if (posT < t.length() && s.charAt(i) == t.charAt(posT)) { if (posT == t.length() - 1) ans = Math.max(ans, s.length() - 1 - i); else { ans = Math.max(ans, pos[posT + 1] - i - 1); posT++; } } } System.out.println(Math.max(ans,canfirst)); } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
722b827fb2cb784688381016a4b14b16
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void sort(long a[]) { Random rd = new Random(); for (int i = 1; i < a.length; ++i) { int p = rd.nextInt(i); long x = a[p]; a[p] = a[i]; a[i] = x; } Arrays.sort(a); } void dfs(int from,int k){ } void add(int u,int v){ to[ct] = u; ne[ct] = h[v]; h[v] = ct++; } int r =0; void dfs1(int c,int ff){ clr[c][aa[c]]++; for(int j=h[c];j!=-1;j=ne[j]){ if(to[j]==ff) continue; dfs1(to[j],c); clr[c][1] += clr[to[j]][1]; clr[c][2] += clr[to[j]][2]; if(clr[to[j]][1]==s1&&clr[to[j]][2]==0||clr[to[j]][2]==s2&&clr[to[j]][1]==0){ r++; } } } int[] h,ne,to,fa; int clr[][]; int aa[]; int s1 = 0; int s2 = 0; boolean f(int n){ int c = 0; while(n>0){ c += n%10; n /=10; } return (c&3)==0; } int[][] next(String s){ int len = s.length(); int ne[][] = new int[len+1][26]; Arrays.fill(ne[len], -1); for(int i=len-1;i>=0;--i){ ne[i] = ne[i+1].clone(); ne[i][s.charAt(i)-'a'] = i+1; } return ne; } void solve() { String s =ns(); String t =ns(); int len =s.length(); int pref[] = new int[len]; int suf[] = new int[len+1]; int p = 0; int tlen = t.length(); for(int i=0;i<len;++i){ if(p<tlen&&s.charAt(i)==t.charAt(p)){ p++; } pref[i] = p; } p = 0; for(int i=len-1;i>=0;--i){ if(p<tlen&&s.charAt(i)==t.charAt(tlen-1-p)){ p++; } suf[i] = p; } int e = -1;int all= 0; for(int i=-1;i<len;++i){ int r = tlen- (i<0?0:pref[i]); while(e+1<=len&&suf[e+1]>=r){ e++; } all =Math.max(all,e-i-1 ); } println(all); //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } long gcd(long a,long b){ return b==0?a: gcd(b,a%b);} int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();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 << 3) + (num << 1) + (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();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
b01615c5a1411ad1458f60c0edcacae1
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(), t = sc.next().toCharArray(); int ans = 0; int n = s.length, m = t.length; int[] right = new int[n + 1]; int j = m - 1; for (int i = n - 1; i >= 0; i--) { if (j >= 0 && t[j] == s[i]) j--; right[i] = m - 1 - j; } j = 0; for (int i = 0; i < n; i++) { int need = m - j; int lo = i, hi = n, idx = n; while (lo <= hi) { int mid = lo + hi >> 1; if (right[mid] >= need) { idx = mid; lo = mid + 1; } else hi = mid - 1; } ans = Math.max(ans, idx - i); if (j != m && t[j] == s[i]) j++; } out.println(ans); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } Integer[] nextIntegerArray(int n) throws IOException { Integer[] ans = new Integer[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } int[] nextIntArray(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
5f660e3fb4cfd1972718eea1fad3776e
train_001.jsonl
1565706900
The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class Solve6 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve6().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); char[] s = sc.next().toCharArray(), t = sc.next().toCharArray(); int n = s.length, m = t.length; int[] right = new int[m], left = new int[m]; for (int i = 0, j = 0; j < m; i++) { if (s[i] == t[j]) { left[j] = i; ++j; } } for (int i = n - 1, j = m - 1; j >= 0; i--) { if (s[i] == t[j]) { right[j] = i; --j; } } int ans = Math.max(right[0], n - left[m - 1] - 1); for (int i = 1; i < m; i++) { ans = Math.max(ans, right[i] - left[i - 1] - 1); } pw.println(ans); } public int max(int[] tp, int n) { int max = tp[0]; for (int i = 1; i < tp.length; i++) { max = Math.max(max, tp[i] - tp[i - 1] - 1); } return Math.max(max, n - tp[tp.length - 1] - 1); } static class FastReader { StringTokenizer st; BufferedReader br; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public boolean hasNext() throws IOException { if (st != null && st.hasMoreTokens()) { return true; } String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return br.readLine(); } } }
Java
["bbaba\nbb", "baaba\nab", "abcde\nabcde", "asdfasdf\nfasd"]
2 seconds
["3", "2", "0", "3"]
null
Java 8
standard input
[ "two pointers", "binary search", "implementation", "greedy" ]
0fd33e1bdfd6c91feb3bf00a2461603f
The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.
1,700
Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.
standard output
PASSED
a9ac5e273e5b9c1cc46ef89c7f3bdb34
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; //http://codeforces.com/contest/1077/problem/F1 //F1. Pictures with Kittens (easy version) //Codeforces Round #521 (Div. 3) public class RecursionSimple { static int n, k, x; static Long[][][] dp; public static void main(String[] args) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader( System.in))); n = sc.nextInt(); k = sc.nextInt(); x = sc.nextInt(); dp = new Long[n + 1][n + 1][n + 1]; long arr[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } long result = countMaximumSum(k, 0, x, arr);// countMaximumSum(n, // k, x, arr); // System.out.println("Result : " + result); System.out.println(result); } public static long countMaximumSum(int nextRequiredFrom, int currentArrStart, int nowTotalRequired, long arr[]) { if (dp[nextRequiredFrom][currentArrStart][nowTotalRequired] != null) { return dp[nextRequiredFrom][currentArrStart][nowTotalRequired]; } int arrLength = arr.length - currentArrStart; // System.out.println("Called For :" + nextRequiredFrom + " " // + currentArrStart + " , " + nowTotalRequired); if (arrLength < nowTotalRequired) { dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = -1L; return -1; } else if (arrLength == nowTotalRequired) { long sum = 0; for (int i = currentArrStart; i < arr.length; i++) { sum = sum + arr[i]; } dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = sum; return sum; } else { if (nowTotalRequired == 0) { if (arrLength < k) { dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = 0L; return 0; } else { dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = -1L; return -1; } } long include = countMaximumSum(k, currentArrStart + 1, nowTotalRequired - 1, arr); if (include != -1) { include = include + arr[currentArrStart]; } if (nextRequiredFrom == 1) { dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = include; return include; } else { long notInclude = countMaximumSum(nextRequiredFrom - 1, currentArrStart + 1, nowTotalRequired, arr); notInclude = Math.max(notInclude, include); dp[nextRequiredFrom][currentArrStart][nowTotalRequired] = notInclude; return notInclude; } } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
bb2c9aa010b13b73bd6258e2868f2c0c
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class Task { int NN = 100005; int MOD = 1000000007; long INF = 1000000000000000000L; long [] a; long [][] dp; long rec(int x, int n, int k) { long ret = -INF; if(x == 0) { if(n < k) { return 0; } else { return -INF; } } if(n == 0) { return -INF; } if(dp[x][n] != -1) { return dp[x][n]; } for(int i=0;i<k && i < n;++i) { ret = Math.max(ret, rec(x - 1, n - i - 1, k) + a[n - i - 1]); } return dp[x][n] = ret; } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), K = in.nextInt(), x = in.nextInt(); a = new long[n]; dp = new long[x + 1][n + 1]; for(int i=0;i<n;++i) { a[i] = in.nextLong(); } /*for(int j=0;j<=n;++j) { if(j < K) { dp[0][j] = 0; } else { dp[0][j] = -INF; } } for(int i=1;i<=x;++i) { dp[i][0] = -INF; } for(int i=1;i<=x;++i) { AVLTree st = new AVLTree(); for(int j=1;j<=n;++j) { long value = dp[i - 1][j - 1] + a[j - 1]; st.add(value); if(j - 1 - K >= 0) { value = dp[i - 1][j - 1 - K] + a[j - 1 - K]; st.remove(value); } dp[i][j] = st.getMax(); } }*/ for(int i=0;i<=x;++i) { for(int j=0;j<=n;++j) { dp[i][j] = -1; } } long ans = rec(x, n, K); if(ans < 0) { ans = -1; } out.println(ans); } public class AVLTree{ class Node { long data; int freq; int height; Node left; Node right; public Node(long data) { this.data = data; this.freq = 1; this.height = 0; this.left = null; this.right = null; } } Node root; public void add(long value) { root = insert(root, value); } Node insert(Node node, long value) { if(node == null) { node = new Node(value); return node; } if(node.data == value) { ++node.freq; return node; } if(node.data > value) { node.left = insert(node.left, value); } else { node.right = insert(node.right, value); } node = updateHeight(node); node = balance(node); return node; } Node updateHeight(Node node) { if(node == null) { return null; } int height = 0; if(node.left != null) { height = Math.max(height, node.left.height + 1); } if(node.right != null) { height = Math.max(height, node.right.height + 1); } node.height = height; return node; } public void remove(long value) { root = delete(root, value); } Node delete(Node node, long value) { if(node == null) { return null; } if(node.data == value) { --node.freq; if(node.freq == 0) { if(node.left == null && node.right == null) { return null; } if(node.left == null) { return node.right; } if(node.right == null) { return node.left; } Node ptr = node.left; while(ptr.right != null) { ptr = ptr.right; } node.data = ptr.data; node.left = delete(node.left, ptr.data); } } else if(node.data > value) { node.left = delete(node.left, value); } else { node.right = delete(node.right, value); } node = updateHeight(node); node = balance(node); return node; } boolean isLeaf(Node node) { return node != null && node.left == null && node.right == null; } public long getMax() { Node ptr = root; while(ptr.right != null) { ptr = ptr.right; } return ptr.data; } int getLeftHeight(Node node) { if(node == null) { return 0; } return (node.left == null ? 0 : node.left.height + 1); } int getRightHeight(Node node) { if(node == null) { return 0; } return (node.right == null ? 0 : node.right.height + 1); } Node balance(Node node) { if(node == null) { return null; } int lh = getLeftHeight(node); int rh = getRightHeight(node); if(Math.abs(lh-rh) < 2) { return node; } if(lh > rh) { Node lnode = node.left; int llh = getLeftHeight(lnode); int lrh = getRightHeight(lnode); if(llh > lrh) {//LL node.left = lnode.right; lnode.right = node; node = lnode; node.right = updateHeight(node.right); node = updateHeight(node); } else {//LR Node lrnode = lnode.right; lnode.right = lrnode.left; lrnode.left = lnode; node.left = lrnode; node.left.left = updateHeight(node.left.left); node.left = updateHeight(node.left); node = updateHeight(node); node = balance(node); } } else { Node rnode = node.right; int rlh = getLeftHeight(rnode); int rrh = getRightHeight(rnode); if(rrh > rlh) {//RR node.right = rnode.left; rnode.left = node; node = rnode; node.left = updateHeight(node.left); node = updateHeight(node); } else { Node rlnode = rnode.left; rnode.left = rlnode.right; rlnode.right = rnode; node.right = rlnode; node.right.right = updateHeight(node.right.right); node.right = updateHeight(node.right); node = updateHeight(node); node = balance(node); } } return node; } public void print() { inorder(root);System.out.println(""); } public void inorder(Node node) { if(node == null) { return; } inorder(node.left); System.out.print("("+node.data+"[" + node.freq+"])"); inorder(node.right); } public void clear() { this.root = null; } public int getDepth() { return root == null ? 0 : root.height; } } } static void prepareIO(boolean isFileIO) { Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } 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
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
7b045db5e1e3e59763e723660f90f3be
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class Task { int NN = 100005; int MOD = 1000000007; long INF = 10000000000000000L; long [] a; long [][] dp; long rec(int x, int n, int k) { long ret = -INF; if(x == 0) { if(n < k) { return 0; } else { return -INF; } } if(n == 0) { return -INF; } if(dp[x][n] != -1) { return dp[x][n]; } for(int i=0;i<k && i < n;++i) { ret = Math.max(ret, rec(x - 1, n - i - 1, k) + a[n - i - 1]); } return dp[x][n] = ret; } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), K = in.nextInt(), x = in.nextInt(); a = new long[n]; dp = new long[x + 1][n + 1]; for(int i=0;i<n;++i) { a[i] = in.nextLong(); } for(int j=0;j<=n;++j) { if(j < K) { dp[0][j] = 0; } else { dp[0][j] = -INF; } } for(int i=1;i<=x;++i) { dp[i][0] = -INF; } for(int i=1;i<=x;++i) { AVLTree tree = new AVLTree(); for(int j=1;j<=n;++j) { tree.add(dp[i - 1][j - 1] + a[j - 1]); if(j-1-K >= 0) { tree.remove(dp[i - 1][j - 1 - K] + a[j - 1 - K]); } dp[i][j] = tree.getMax(); } } out.println(dp[x][n] < 0 ? -1 : dp[x][n]); } public class AVLTree{ class Node { long data; int freq; int height; Node left; Node right; public Node(long data) { this.data = data; this.freq = 1; this.height = 0; this.left = null; this.right = null; } } Node root; public void add(long value) { root = insert(root, value); } Node insert(Node node, long value) { if(node == null) { node = new Node(value); return node; } if(node.data == value) { ++node.freq; return node; } if(node.data > value) { node.left = insert(node.left, value); } else { node.right = insert(node.right, value); } node = updateHeight(node); node = balance(node); return node; } Node updateHeight(Node node) { if(node == null) { return null; } int height = 0; if(node.left != null) { height = Math.max(height, node.left.height + 1); } if(node.right != null) { height = Math.max(height, node.right.height + 1); } node.height = height; return node; } public void remove(long value) { root = delete(root, value); } Node delete(Node node, long value) { if(node == null) { return null; } if(node.data == value) { if(node.freq == 1) { if(node.left == null && node.right == null) { return null; } if(node.left == null) { return node.right; } if(node.right == null) { return node.left; } Node ptr = node.left; while(ptr.right != null) { ptr = ptr.right; } node.data = ptr.data; node.left = delete(node.left, ptr.data); } else { node.freq = node.freq - 1; } } else if(node.data > value) { node.left = delete(node.left, value); } else { node.right = delete(node.right, value); } node = updateHeight(node); node = balance(node); return node; } boolean isLeaf(Node node) { return node != null && node.left == null && node.right == null; } public long getMax() { Node ptr = root; while(ptr.right != null) { ptr = ptr.right; } return ptr.data; } int getLeftHeight(Node node) { if(node == null) { return 0; } return (node.left == null ? 0 : node.left.height + 1); } int getRightHeight(Node node) { if(node == null) { return 0; } return (node.right == null ? 0 : node.right.height + 1); } Node balance(Node node) { if(node == null) { return null; } int lh = getLeftHeight(node); int rh = getRightHeight(node); if(Math.abs(lh-rh) < 2) { return node; } if(lh > rh) { Node lnode = node.left; int llh = getLeftHeight(lnode); int lrh = getRightHeight(lnode); if(llh > lrh) {//LL node.left = lnode.right; lnode.right = node; node = lnode; node.right = updateHeight(node.right); node = updateHeight(node); } else {//LR Node lrnode = lnode.right; lnode.right = lrnode.left; lrnode.left = lnode; node.left = lrnode; node.left.left = updateHeight(node.left.left); node.left = updateHeight(node.left); node = updateHeight(node); node = balance(node); } } else { Node rnode = node.right; int rlh = getLeftHeight(rnode); int rrh = getRightHeight(rnode); if(rrh > rlh) {//RR node.right = rnode.left; rnode.left = node; node = rnode; node.left = updateHeight(node.left); node = updateHeight(node); } else { Node rlnode = rnode.left; rnode.left = rlnode.right; rlnode.right = rnode; node.right = rlnode; node.right.right = updateHeight(node.right.right); node.right = updateHeight(node.right); node = updateHeight(node); node = balance(node); } } return node; } public void print() { inorder(root);System.out.println(""); } public void inorder(Node node) { if(node == null) { return; } inorder(node.left); if(node.data >= 0) { System.out.print("("+node.data+"[" + node.freq+"])"); } inorder(node.right); } public void clear() { this.root = null; } public int getDepth() { return root == null ? 0 : root.height; } } } static void prepareIO(boolean isFileIO) { Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } 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
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
234041dafec0a6274ddda5a8af7e1bf7
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class Task { int NN = 100005; int MOD = 1000000007; long INF = 1000000000000000000L; long [] a; long [][] dp; long rec(int x, int n, int k) { long ret = -INF; if(x == 0) { if(n < k) { return 0; } else { return -INF; } } if(n == 0) { return -INF; } if(dp[x][n] != -1) { return dp[x][n]; } for(int i=0;i<k && i < n;++i) { ret = Math.max(ret, rec(x - 1, n - i - 1, k) + a[n - i - 1]); } return dp[x][n] = ret; } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), K = in.nextInt(), x = in.nextInt(); a = new long[n]; dp = new long[x + 1][n + 1]; for(int i=0;i<n;++i) { a[i] = in.nextLong(); } for(int j=0;j<=n;++j) { if(j < K) { dp[0][j] = 0; } else { dp[0][j] = -INF; } } for(int i=1;i<=x;++i) { dp[i][0] = -INF; } for(int i=1;i<=x;++i) { for(int j=1;j<=n;++j) { dp[i][j] = -INF; for(int k=0;k<K&&k<j;++k) { dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k - 1] + a[j-k-1]); } } } out.println(dp[x][n] < 0 ? -1 : dp[x][n]); } public class AVLTree{ class Node { long data; int freq; int height; Node left; Node right; public Node(long data) { this.data = data; this.freq = 1; this.height = 0; this.left = null; this.right = null; } } Node root; public void add(long value) { root = insert(root, value); } Node insert(Node node, long value) { if(node == null) { node = new Node(value); return node; } if(node.data == value) { ++node.freq; return node; } if(node.data > value) { node.left = insert(node.left, value); } else { node.right = insert(node.right, value); } node = updateHeight(node); node = balance(node); return node; } Node updateHeight(Node node) { if(node == null) { return null; } int height = 0; if(node.left != null) { height = Math.max(height, node.left.height + 1); } if(node.right != null) { height = Math.max(height, node.right.height + 1); } node.height = height; return node; } public void remove(long value) { root = delete(root, value); } Node delete(Node node, long value) { if(node == null) { return null; } if(node.data == value) { --node.freq; if(node.freq == 0) { if(node.left == null && node.right == null) { return null; } if(node.left == null) { return node.right; } if(node.right == null) { return node.left; } Node ptr = node.left; while(ptr.right != null) { ptr = ptr.right; } node.data = ptr.data; node.left = delete(node.left, ptr.data); } } else if(node.data > value) { node.left = delete(node.left, value); } else { node.right = delete(node.right, value); } node = updateHeight(node); node = balance(node); return node; } boolean isLeaf(Node node) { return node != null && node.left == null && node.right == null; } public long getMax() { Node ptr = root; while(ptr.right != null) { ptr = ptr.right; } return ptr.data; } int getLeftHeight(Node node) { if(node == null) { return 0; } return (node.left == null ? 0 : node.left.height + 1); } int getRightHeight(Node node) { if(node == null) { return 0; } return (node.right == null ? 0 : node.right.height + 1); } Node balance(Node node) { if(node == null) { return null; } int lh = getLeftHeight(node); int rh = getRightHeight(node); if(Math.abs(lh-rh) < 2) { return node; } if(lh > rh) { Node lnode = node.left; int llh = getLeftHeight(lnode); int lrh = getRightHeight(lnode); if(llh > lrh) {//LL node.left = lnode.right; lnode.right = node; node = lnode; node.right = updateHeight(node.right); node = updateHeight(node); } else {//LR Node lrnode = lnode.right; lnode.right = lrnode.left; lrnode.left = lnode; node.left = lrnode; node.left.left = updateHeight(node.left.left); node.left = updateHeight(node.left); node = updateHeight(node); node = balance(node); } } else { Node rnode = node.right; int rlh = getLeftHeight(rnode); int rrh = getRightHeight(rnode); if(rrh > rlh) {//RR node.right = rnode.left; rnode.left = node; node = rnode; node.left = updateHeight(node.left); node = updateHeight(node); } else { Node rlnode = rnode.left; rnode.left = rlnode.right; rlnode.right = rnode; node.right = rlnode; node.right.right = updateHeight(node.right.right); node.right = updateHeight(node.right); node = updateHeight(node); node = balance(node); } } return node; } public void print() { inorder(root);System.out.println(""); } public void inorder(Node node) { if(node == null) { return; } inorder(node.left); System.out.print("("+node.data+"[" + node.freq+"])"); inorder(node.right); } public void clear() { this.root = null; } public int getDepth() { return root == null ? 0 : root.height; } } } static void prepareIO(boolean isFileIO) { Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } 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
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
534f7597e509813ef352b44007a7115d
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class Task { int NN = 100005; int MOD = 1000000007; long INF = 1000000000000000000L; long [] a; long [][][] dp; long rec(int n, int x, int pos, int k) { long ret = -INF; if(dp[n][x][pos] != -1) { return dp[n][x][pos]; } if(x == 0) { if(pos <= k - 1) { return dp[n][x][pos] = 0; } return dp[n][x][pos] = -INF; } if(n == 0) { return dp[n][x][pos] = -INF; } if(n-1 > pos-k) { ret = Math.max(ret, rec(n - 1, x, pos, k)); } ret = Math.max(ret, a[n - 1] + rec(n - 1, x - 1, n - 1, k)); return dp[n][x][pos] = ret; } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), k = in.nextInt(), x = in.nextInt(); a = new long[n]; dp = new long[n + 1][x + 1][n + 1]; for(int i=0;i<n;++i) { a[i] = in.nextLong(); } for(int i=0;i<=n;++i) { for(int j=0;j<=x;++j) { for(int jj=0;jj<=n;++jj) { dp[i][j][jj] = -1; } } } long ans = rec(n, x, n, k); if(ans < 0) { ans = -1; } out.println(ans); } } static void prepareIO(boolean isFileIO) { Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } 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
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
03c8a6cbd08019af72c4b2adbcef56f7
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; public class PicturesWithKitten { public static void main(String[] args) { FastScanner scanner = new FastScanner(); int N = scanner.nextInt(); int K = scanner.nextInt(); int X = scanner.nextInt(); long[] vals = new long[N+1]; for(int i = 1; i <= N; i++) { vals[i] = scanner.nextInt(); } long[][] dp = new long[N+1][X+1]; for(int i = 0; i <= N; i++) { Arrays.fill(dp[i], -1); } dp[0][X] = 0; for(int i = 1; i <= N; i++) { for(int j = 0; j < X; j++) { for(int k = 1; k <= K && i-k >= 0; k++) { if (dp[i-k][j+1] == -1) continue; dp[i][j] = Math.max(dp[i][j], dp[i-k][j+1] + vals[i]); } } } long max = -1; for(int i = N-K+1; i <= N; i++) { max = Math.max(max, dp[i][0]); } System.out.println(max); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
ca24a63f1272cbd6522630ad5fce05bf
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; public class Solution{ static final int maxn = 205; static final long inf = (long)1e18; public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n = fs.nextInt(), k = fs.nextInt(), x = fs.nextInt(); long[] a = new long[maxn]; for(int i=1;i<=n;i++) { a[i] = fs.nextLong(); } long[][] dp = new long[maxn][maxn]; for(int i=0;i<maxn;i++) Arrays.fill(dp[i], -inf); dp[0][x] = 0; for(int i=1;i<=n;i++) { for(int j=0;j<=x;j++) { for(int p=1;p<=k;p++) { if(i-p<0) break; if(dp[i-p][j+1]==-inf) continue; dp[i][j] = Math.max(dp[i][j], dp[i-p][j+1] + a[i]); } } } long ans = -inf; for(int i=n-k+1;i<=n;i++) { ans = Math.max(ans, dp[i][0]); } if(ans==-inf) { out.println(-1); } else { out.println(ans); } } out.close(); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
61d158d160974348a654b7fcff41aa9b
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ 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); TaskF1 solver = new TaskF1(); solver.solve(1, in, out); out.close(); } static class TaskF1 { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int x = in.nextInt(); int[] beauty = in.readIntArray(n); // dp[i][j] gives max sum for first i items with j reposted long[][] dp = new long[n][x + 1]; for (long[] row : dp) Arrays.fill(row, -1); for (int end = 0; end < n; ++end) { if (end < k) dp[end][1] = beauty[end]; for (int cnt = 2; cnt <= Math.min(x, end + 1); ++cnt) { int bound = Math.max(end - k, 0); for (int last = bound; last < end; ++last) { if (dp[last][cnt - 1] != -1) { dp[end][cnt] = Math.max(dp[end][cnt], dp[last][cnt - 1] + beauty[end]); } } } } long res = -1; for (int i = n - k; i < n; ++i) res = Math.max(res, dp[i][x]); out.println(res); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private static final int BUFFER_SIZE = 32768; public InputReader(InputStream stream) { reader = new BufferedReader( new InputStreamReader(stream), BUFFER_SIZE); 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 int[] readIntArray(int length) { int[] result = new int[length]; for (int i = 0; i < length; ++i) result[i] = nextInt(); return result; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
873973f849ea4e308847e5cfec2d9c9e
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public void sort(long b[]){ Random rd = new Random(); for(int i=1;i<b.length;++i){ int c = rd.nextInt(i); long v = b[c]; b[c] = b[i]; b[i] = v; } Arrays.sort(b); } public void sort(int b[]){ Random rd = new Random(); for(int i = 1;i<b.length;++i){ int c = rd.nextInt(i); int v = b[c]; b[c]= b[i]; b[i] = v; } Arrays.sort(b); } static int groups = 0; static int[] fa; static int[] sz; static void init(int n) { groups = n; fa = new int[n]; for (int i = 1; i < n; ++i) { fa[i] = i; } sz = new int[n]; Arrays.fill(sz, 1); } static int root(int p) { while (p != fa[p]) { fa[p] = fa[fa[p]]; p = fa[p]; } return p; } static void combine(int p, int q) { int i = root(p); int j = root(q); if (i == j) { return; } if (sz[i] < sz[j]) { fa[i] = j; sz[j] += sz[i]; } else { fa[j] = i; sz[i] += sz[j]; } groups--; } class Pair { long x;long y; Pair(long xx,long yy){ x = xx;y= yy; long g = gcd(Math.abs(x),Math.abs(y)); if(xx*yy>=0){ x = Math.abs(x)/g; y = Math.abs(y)/g; }else{ x = -Math.abs(x)/g; y = Math.abs(y)/g; } } public boolean equals(Object fk){ Pair p = (Pair)fk; return x == p.x && y== p.y; } public int hashCode(){ return (int)(x*37+y); } } void dfs(int g, List<Integer> go[],boolean vis[]){ vis[g] = true; for(int u: go[g]){ int to = u; if(!vis[to]) { dfs(to, go, vis); } } } public static void main(String[] args) throws Exception { new Main().run();} TreeMap<Integer,Integer> tmp = new TreeMap<>(); void remove(int u){ int v = tmp.get(u); if(v==1){ tmp.remove(u); }else{ tmp.put(u,v-1); } } void solve(){ int n = ni(); int k = ni(); int x = ni(); long a[] = new long[n+2]; for(int i= 1;i<=n;++i){ a[i] = nl(); } if(n>x*k+k-1){ println(-1);return; } long dp[][] = new long[n+2][x+2]; for(long u[]:dp){ Arrays.fill(u,-10000000000L); } dp[0][0] = 0; for(int i=1;i<=n+1;++i){ for(int j=1;j<=x+1;++j){ for(int f=i-1;i-f<=k&&f>=0;--f){ dp[i][j] = Math.max(dp[i][j] , dp[f][j-1] + a[i]); } } } if(dp[n+1][x+1]<0){ println(-1);return; } println(dp[n+1][x+1]); // PriorityQueue<int[]> q= new PriorityQueue<>((x,y)->{return x[0]-y[0];}); // // q.offer(new int[]{0,0}); // boolean inq[] = new boolean[n]; // while(q.size()>0){ // int c[]= q.poll(); // for(int i=h[c[1]];i!=-1;i=ne[i]){ // if(!inq[to[i]]) { // q.offer(new int[]{ wt[i], to[i]}); // inq[to[i]] = true; // } // } // } } int err = 0; void go(int rt,int pt,int fa) { stk[rt] = pt; for(int i=h[rt];i!=-1;i=ne[i]) { if(to[i]==pt||to[i]==fa) continue; go(to[i],pt,rt); } } int ct = 0; void add(int u,int v){ to[ct] = v; ne[ct] = h[u]; h[u] = ct++; // // to1[ct] = u; // wt1[ct] = w; // ne1[ct] = h1[v]; // h1[v] = ct++; } int []h,ne,to,wt,qt,stk; long inv(long a, long MOD) { //return fpow(a, MOD-2, MOD); return a==1?1:(long )(MOD-MOD/a)*inv(MOD%a, MOD)%MOD; } void inverse(){ int MAXN = 10000; long inv[] = new long[MAXN+1]; inv[1] = 1; //注意初始化 long mod = 1000000007; for (int i=2; i<=MAXN; ++i) { inv[i] = (mod - mod / i) * inv[(int) (mod % i)] % mod; } } // 计算某个特别大的组合数 long C(long n,long m, long MOD) { if(m+m>n)m=n-m; long up=1,down=1; for(long i=0;i<m;i++) { up=up*(n-i)%MOD; down=down*(i+1)%MOD; } return up*inv(down, MOD)%MOD; } void solve2() { int n = ni(); String s= ns(); int g[][] = new int[3][3]; for(int i = 0;i<n;++i){ char c = s.charAt(i); int idx = 0; if(c=='G'){ idx =1; }else if(c=='B'){ idx =2; } g[c][i%3]++; } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } long gcd(long a,long b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in; // is = new FileInputStream("C:\\Users\\Luqi\\Downloads\\P1600_2.in"); out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();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 << 3) + (num << 1) + (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();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
ba893f72d02a7c732bf63d5aced16f28
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public void sort(long b[]){ Random rd = new Random(); for(int i=1;i<b.length;++i){ int c = rd.nextInt(i); long v = b[c]; b[c] = b[i]; b[i] = v; } Arrays.sort(b); } public void sort(int b[]){ Random rd = new Random(); for(int i = 1;i<b.length;++i){ int c = rd.nextInt(i); int v = b[c]; b[c]= b[i]; b[i] = v; } Arrays.sort(b); } static int groups = 0; static int[] fa; static int[] sz; static void init(int n) { groups = n; fa = new int[n]; for (int i = 1; i < n; ++i) { fa[i] = i; } sz = new int[n]; Arrays.fill(sz, 1); } static int root(int p) { while (p != fa[p]) { fa[p] = fa[fa[p]]; p = fa[p]; } return p; } static void combine(int p, int q) { int i = root(p); int j = root(q); if (i == j) { return; } if (sz[i] < sz[j]) { fa[i] = j; sz[j] += sz[i]; } else { fa[j] = i; sz[i] += sz[j]; } groups--; } class Pair { long x;long y; Pair(long xx,long yy){ x = xx;y= yy; long g = gcd(Math.abs(x),Math.abs(y)); if(xx*yy>=0){ x = Math.abs(x)/g; y = Math.abs(y)/g; }else{ x = -Math.abs(x)/g; y = Math.abs(y)/g; } } public boolean equals(Object fk){ Pair p = (Pair)fk; return x == p.x && y== p.y; } public int hashCode(){ return (int)(x*37+y); } } void dfs(int g, List<Integer> go[],boolean vis[]){ vis[g] = true; for(int u: go[g]){ int to = u; if(!vis[to]) { dfs(to, go, vis); } } } public static void main(String[] args) throws Exception { new Main().run();} TreeMap<Integer,Integer> tmp = new TreeMap<>(); void remove(int u){ int v = tmp.get(u); if(v==1){ tmp.remove(u); }else{ tmp.put(u,v-1); } } void solve(){ int n = ni(); int k = ni(); int x = ni(); long a[] = new long[n+2]; for(int i= 1;i<=n;++i){ a[i] = nl(); } if(n>x*k+k-1){ // println(-1);return; } long dp[][] = new long[n+2][x+2]; for(long u[]:dp){ Arrays.fill(u,-1000000000000000L); } dp[0][0] = 0; for(int i=1;i<=n+1;++i){ for(int j=1;j<=x+1;++j){ for(int f=i-1;i-f<=k&&f>=0;--f){ dp[i][j] = Math.max(dp[i][j] , dp[f][j-1] + a[i]); } } } if(dp[n+1][x+1]<0){ println(-1);return; } println(dp[n+1][x+1]); // PriorityQueue<int[]> q= new PriorityQueue<>((x,y)->{return x[0]-y[0];}); // // q.offer(new int[]{0,0}); // boolean inq[] = new boolean[n]; // while(q.size()>0){ // int c[]= q.poll(); // for(int i=h[c[1]];i!=-1;i=ne[i]){ // if(!inq[to[i]]) { // q.offer(new int[]{ wt[i], to[i]}); // inq[to[i]] = true; // } // } // } } int err = 0; void go(int rt,int pt,int fa) { stk[rt] = pt; for(int i=h[rt];i!=-1;i=ne[i]) { if(to[i]==pt||to[i]==fa) continue; go(to[i],pt,rt); } } int ct = 0; void add(int u,int v){ to[ct] = v; ne[ct] = h[u]; h[u] = ct++; // // to1[ct] = u; // wt1[ct] = w; // ne1[ct] = h1[v]; // h1[v] = ct++; } int []h,ne,to,wt,qt,stk; long inv(long a, long MOD) { //return fpow(a, MOD-2, MOD); return a==1?1:(long )(MOD-MOD/a)*inv(MOD%a, MOD)%MOD; } void inverse(){ int MAXN = 10000; long inv[] = new long[MAXN+1]; inv[1] = 1; //注意初始化 long mod = 1000000007; for (int i=2; i<=MAXN; ++i) { inv[i] = (mod - mod / i) * inv[(int) (mod % i)] % mod; } } // 计算某个特别大的组合数 long C(long n,long m, long MOD) { if(m+m>n)m=n-m; long up=1,down=1; for(long i=0;i<m;i++) { up=up*(n-i)%MOD; down=down*(i+1)%MOD; } return up*inv(down, MOD)%MOD; } void solve2() { int n = ni(); String s= ns(); int g[][] = new int[3][3]; for(int i = 0;i<n;++i){ char c = s.charAt(i); int idx = 0; if(c=='G'){ idx =1; }else if(c=='B'){ idx =2; } g[c][i%3]++; } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } long gcd(long a,long b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in; // is = new FileInputStream("C:\\Users\\Luqi\\Downloads\\P1600_2.in"); out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();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 << 3) + (num << 1) + (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();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
11e8197cd12dca45a24d998414978dd7
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class CFR { static final int UNCALC = -1; static final long INF = (long) 1e15; static long[][][] memo; static int k, n, a[]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); k = sc.nextInt(); int x = sc.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); memo = new long[n + 1][n][x + 1]; for (long[][] aa : memo) for (long[] b : aa) Arrays.fill(b, UNCALC); long ans = dp(-1, 0, x); if (ans < 0) out.println(-1); else out.println(ans); out.flush(); out.close(); } static long dp(int last, int idx, int rem) { if (idx == n) return 0; if (memo[last + 1][idx][rem] != UNCALC) return memo[last + 1][idx][rem]; long best = -INF; int diff = idx - last; if (rem > 0) best = Math.max(best, a[idx] + dp(idx, idx + 1, rem - 1)); if (diff < k) best = Math.max(best, dp(last, idx + 1, rem)); return memo[last + 1][idx][rem] = best; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
b250e8078db7bbeb71332876dd152e4c
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public final class TaskF1 { public static void main(String[] args) { new TaskF1(System.in, System.out); } static class Solver implements Runnable { static final long INF = (long) 1e15; int n, k, x; int[] arr; long[][][] dp; boolean possible; // BufferedReader in; InputReader in; PrintWriter out; void solve() throws IOException { n = in.nextInt(); k = in.nextInt(); x = in.nextInt(); arr = in.nextIntArray(n); dp = new long[n + 1][n + 1][x + 1]; // if ((int) Math.ceil(n / (double) k) > x) /* if (n / k > x) { out.println(-1); return; }*/ for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) Arrays.fill(dp[i][j], -1); } long max = 0; for (int i = 0; i < k; i++) { // starting at arr[i] max = Math.max(max, arr[i] + find(i + 1, i, x - 1)); } if (max == 0) out.println(-1); else out.println(max); } long find(int curr, int prev, int rem) { if (curr == n) return 0; if (rem == 0) { // System.out.println(); return (n - 1 - prev < k ? 0 : -INF); } if (curr - prev > k) return -INF; if (dp[curr][prev][rem] != -1) return dp[curr][prev][rem]; long max = Math.max(arr[curr] + find(curr + 1, curr, rem - 1), find(curr + 1, prev, rem)); return dp[curr][prev][rem] = max; } void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } // uncomment below line to change to BufferedReader // public Solver(BufferedReader in, PrintWriter out) public Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } @Override public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } 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(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { this.stream = stream; } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static long min(long... arr) { long min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static long max(long... arr) { long max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } static int min(int... arr) { int min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static int max(int... arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } } static class Utils { static boolean nextPermutation(int[] arr) { for (int a = arr.length - 2; a >= 0; --a) { if (arr[a] < arr[a + 1]) { for (int b = arr.length - 1; ; --b) { if (arr[b] > arr[a]) { int t = arr[a]; arr[a] = arr[b]; arr[b] = t; for (++a, b = arr.length - 1; a < b; ++a, --b) { t = arr[a]; arr[a] = arr[b]; arr[b] = t; } return true; } } } } return false; } } public TaskF1(InputStream inputStream, OutputStream outputStream) { // uncomment below line to change to BufferedReader // BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Thread thread = new Thread(null, new Solver(in, out), "TaskF1", 1 << 29); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { in.close(); out.flush(); out.close(); } } } /* 5 2 2 1 2 3 4 5 */
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
a3de49e3e7856ef7ed47369f8645ca6c
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int x = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); long[][] dp = new long[n][x+1]; for (int i = 0; i < n; ++i) Arrays.fill(dp[i], Long.MIN_VALUE); for (int i = 0; i < k; ++i) dp[i][1] = a[i]; for (int i = 0; i < n; ++i) { for (int j = 2; j <= x; ++j) { for (int u = 1; u <= k && u <= i; ++u) if (dp[i-u][j-1] != Long.MIN_VALUE) { dp[i][j] = Math.max(dp[i][j], dp[i-u][j-1] + a[i]); } } } long max = Long.MIN_VALUE; for (int i = 0; i < k; ++i) max = Math.max(max, dp[n - 1 - i][x]); System.out.println(max == Long.MIN_VALUE ? -1 : max); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
d81b9300f8a2c0622395b94f199e7744
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); long[][] dp = new long[n][m+1]; for (int i = 0; i < d && i < n; ++i) dp[i][1] = a[i]; for (int j = 2; j <= m; ++j) { for (int i = 0; i < n; ++i) { for (int k = i - 1; k >= 0 && k >= i - d; --k) { if (dp[k][j-1] > 0) dp[i][j] = Math.max(dp[i][j], dp[k][j-1] + a[i]); } } } long max = 0; for (int i = 1; i <= d && i <= n; ++i) max = Math.max(max, dp[n-i][m]); System.out.println(max > 0 ? max : -1); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
dcd88e999a04b05c7e757e513b0cfc62
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int x = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); long[][] dp = new long[n][x+1]; for (int i = 0; i < n; ++i) Arrays.fill(dp[i], Long.MIN_VALUE); for (int i = 0; i < k; ++i) dp[i][1] = a[i]; for (int i = 0; i < n; ++i) { for (int j = 2; j <= x; ++j) { for (int u = 1; u <= k && u <= i; ++u) dp[i][j] = Math.max(dp[i][j], dp[i-u][j-1] + a[i]); } } long max = Long.MIN_VALUE; for (int i = 0; i < k; ++i) max = Math.max(max, dp[n - 1 - i][x]); System.out.println(max < 0 ? -1 : max); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output